All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jlot.client.config.rest.RestTemplateConfig Maven / Gradle / Ivy

There is a newer version: 1.2
Show newest version
package org.jlot.client.config.rest;

import java.net.MalformedURLException;
import java.util.List;

import javax.inject.Inject;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.ClassUtils;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig
{
	@Inject
	private ClientHttpRequestFactory	clientHttpRequestFactory;

	@Bean
	public RestTemplate restTemplate ( ) throws MalformedURLException
	{
		RestTemplate template = new RestTemplate(clientHttpRequestFactory);
		addJacksonConverter(template);
		return template;
	}

	/**
	 * JacksonConverter is added to RestTemplate automatically but not to
	 * FormHttpMessageConverter when it comes to Multipart uploads, see also
	 *
	 * @see Handling
	 *      a file upload request from programmatic clients
	 *
	 * @param template
	 */
	private void addJacksonConverter ( RestTemplate template )
	{
		if (isJackson2Present())
		{
			List> messageConverters = template.getMessageConverters();
			for (HttpMessageConverter httpMessageConverter : messageConverters)
			{
				if (httpMessageConverter instanceof FormHttpMessageConverter)
				{
					FormHttpMessageConverter converter = (FormHttpMessageConverter) httpMessageConverter;
					converter.addPartConverter(new MappingJackson2HttpMessageConverter());
				}
			}
		}
	}

	private boolean isJackson2Present ( )
	{
		boolean cond1 = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", this.getClass().getClassLoader());
		boolean cond2 = ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", this.getClass().getClassLoader());
		return cond1 && cond2;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy