Java Code Examples for org.springframework.http.converter.HttpMessageConverter

The following examples show how to use org.springframework.http.converter.HttpMessageConverter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: smart-admin   Source File: SmartRestTemplateConfig.java    License: MIT License 6 votes vote down vote up
/**
 * fastJsonRestTemplate
 *
 * @return
 */
@Bean(name = "fastJsonRestTemplate")
public RestTemplate fastJsonRestTemplate() {
    RestTemplate restTemplate = new RestTemplate(httpRequestFactory());

    HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));

    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    fastConverter.setSupportedMediaTypes(fastMediaTypes);
    List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
    converters.add(1,converter);
    converters.add(fastConverter);
    return restTemplate;
}
 
Example 2
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter,
		Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
	try {
		boolean encode = false;
		if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {
			SecurityParameter serializedField = (SecurityParameter) methodParameter
					.getMethodAnnotation(SecurityParameter.class);
			encode = serializedField.inDecode();
		}

		if (encode) {
			log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密");
			 return new ParamEncryptRequestBodyAdvice.DefaultHttpInputMessage(httpInputMessage);
		} else {
			return httpInputMessage;
		}
	} catch (Exception e) {
		log.error(
				"对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:" + e.getMessage());
	}
	 return httpInputMessage;
}
 
Example 3
@SuppressWarnings("unchecked")
private void verifyMessageConverters(Object bean, boolean hasDefaultRegistrations) {
	assertNotNull(bean);
	Object value = new DirectFieldAccessor(bean).getPropertyValue("messageConverters");
	assertNotNull(value);
	assertTrue(value instanceof List);
	List<HttpMessageConverter<?>> converters = (List<HttpMessageConverter<?>>) value;
	if (hasDefaultRegistrations) {
		assertTrue("Default and custom converter expected", converters.size() > 2);
	}
	else {
		assertTrue("Only custom converters expected", converters.size() == 2);
	}
	assertTrue(converters.get(0) instanceof StringHttpMessageConverter);
	assertTrue(converters.get(1) instanceof ResourceHttpMessageConverter);
}
 
Example 4
Source Project: spring-analysis-note   Source File: DefaultServerRequest.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> T bodyInternal(Type bodyType, Class<?> bodyClass)
		throws ServletException, IOException {

	MediaType contentType =
			this.headers.contentType().orElse(MediaType.APPLICATION_OCTET_STREAM);

	for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
		if (messageConverter instanceof GenericHttpMessageConverter) {
			GenericHttpMessageConverter<T> genericMessageConverter =
					(GenericHttpMessageConverter<T>) messageConverter;
			if (genericMessageConverter.canRead(bodyType, bodyClass, contentType)) {
				return genericMessageConverter.read(bodyType, bodyClass, this.serverHttpRequest);
			}
		}
		if (messageConverter.canRead(bodyClass, contentType)) {
			HttpMessageConverter<T> theConverter =
					(HttpMessageConverter<T>) messageConverter;
			Class<? extends T> clazz = (Class<? extends T>) bodyClass;
			return theConverter.read(clazz, this.serverHttpRequest);
		}
	}
	throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
}
 
Example 5
Source Project: cf-SpringBootTrader   Source File: WebConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * configure the message converters with the date formatter.
 */
@Override
public void configureMessageConverters(
		List<HttpMessageConverter<?>> converters) {
	// Configure JSON support
	MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
	mappingJacksonHttpMessageConverter.setSupportedMediaTypes(Arrays
			.asList(MediaType.APPLICATION_JSON));
	//mappingJacksonHttpMessageConverter.getObjectMapper().configure(
	//		Feature.WRITE_DATES_AS_TIMESTAMPS, true);
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
	// There is no need to set the timezone as Jackson uses GMT and not the
	// local time zone (which is exactly what you want)
	// Note: While SimpleDateFormat is not threadsafe, Jackson Marshaller's
	// StdSerializerProvider clones the configured formatter for each thread
	mappingJacksonHttpMessageConverter.getObjectMapper().setDateFormat(
			format);
	//mappingJacksonHttpMessageConverter.getObjectMapper().configure(
	//		Feature.INDENT_OUTPUT, true);
	// mappingJacksonHttpMessageConverter.getObjectMapper().getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
	converters.add(mappingJacksonHttpMessageConverter);
}
 
Example 6
Source Project: uavstack   Source File: JSONPResponseBodyAdvice.java    License: Apache License 2.0 6 votes vote down vote up
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                              Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                              ServerHttpResponse response) {

    ResponseJSONP responseJsonp = returnType.getMethodAnnotation(ResponseJSONP.class);
    if(responseJsonp == null){
        responseJsonp = returnType.getContainingClass().getAnnotation(ResponseJSONP.class);
    }

    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    String callbackMethodName = servletRequest.getParameter(responseJsonp.callback());

    if (!IOUtils.isValidJsonpQueryParam(callbackMethodName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invalid jsonp parameter value:" + callbackMethodName);
        }
        callbackMethodName = null;
    }

    JSONPObject jsonpObject = new JSONPObject(callbackMethodName);
    jsonpObject.addParameter(body);
    beforeBodyWriteInternal(jsonpObject, selectedContentType, returnType, request, response);
    return jsonpObject;
}
 
Example 7
Source Project: spring-boot-cookbook   Source File: WebMvcConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonHttpMessageConverter httpMessageConverter = new FastJsonHttpMessageConverter();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames,
            SerializerFeature.WriteEnumUsingToString,
            SerializerFeature.WriteMapNullValue,
            SerializerFeature.WriteDateUseDateFormat);
    fastJsonConfig.setSerializeFilters(new ValueFilter() {
        @Override
        public Object process(Object o, String s, Object source) {
            if (source == null) {
                return "";
            }
            if (source instanceof Date) {
                return ((Date) source).getTime();
            }
            return source;
        }
    });
    httpMessageConverter.setFastJsonConfig(fastJsonConfig);
    converters.add(httpMessageConverter);
}
 
Example 8
@Test
public void responseBodyAdvice() throws Exception {
	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	this.handlerAdapter.setMessageConverters(converters);

	this.webAppContext.registerSingleton("rba", ResponseCodeSuppressingAdvice.class);
	this.webAppContext.refresh();

	this.request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
	this.request.setParameter("c", "callback");

	HandlerMethod handlerMethod = handlerMethod(new SimpleController(), "handleBadRequest");
	this.handlerAdapter.afterPropertiesSet();
	this.handlerAdapter.handle(this.request, this.response, handlerMethod);

	assertEquals(200, this.response.getStatus());
	assertEquals("{\"status\":400,\"message\":\"body\"}", this.response.getContentAsString());
}
 
Example 9
@Before
public void setUp() {
	ByteArrayHttpMessageConverter emptyBodyConverter = new ByteArrayHttpMessageConverter();
	emptyBodyConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

	List<HttpMessageConverter<?>> converters = new ArrayList<>(3);
	converters.add(emptyBodyConverter);
	converters.add(new ByteArrayHttpMessageConverter());
	converters.add(new ResourceHttpMessageConverter());
	converters.add(new MappingJackson2HttpMessageConverter());

	AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter();
	converter.setPartConverters(converters);

	restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
	restTemplate.setMessageConverters(Collections.singletonList(converter));
}
 
Example 10
Source Project: x-pipe   Source File: RestTemplateFactory.java    License: Apache License 2.0 6 votes vote down vote up
public static RestOperations createCommonsHttpRestTemplate(int maxConnPerRoute, int maxConnTotal,
                                                           int connectTimeout, int soTimeout, int retryTimes, RetryPolicyFactory retryPolicyFactory) {
    HttpClient httpClient = HttpClientBuilder.create()
            .setMaxConnPerRoute(maxConnPerRoute)
            .setMaxConnTotal(maxConnTotal)
            .setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build())
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).build())
            .build();
    ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
    RestTemplate restTemplate = new RestTemplate(factory);
    //set jackson mapper
    for (HttpMessageConverter<?> hmc : restTemplate.getMessageConverters()) {
        if (hmc instanceof MappingJackson2HttpMessageConverter) {
            ObjectMapper objectMapper = createObjectMapper();
            MappingJackson2HttpMessageConverter mj2hmc = (MappingJackson2HttpMessageConverter) hmc;
            mj2hmc.setObjectMapper(objectMapper);
        }
    }

    return (RestOperations) Proxy.newProxyInstance(RestOperations.class.getClassLoader(),
            new Class[]{RestOperations.class},
            new RetryableRestOperationsHandler(restTemplate, retryTimes, retryPolicyFactory));
}
 
Example 11
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
	GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
	List<HttpMessageConverter<?>> converters = createConverterList(converter);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {};
	Type type = reference.getType();
	extractor = new HttpMessageConverterExtractor<List<String>>(type, converters);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(type, null, contentType)).willReturn(true);
	given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);

	assertEquals(expected, result);
}
 
Example 12
@Test  // SPR-13592
@SuppressWarnings("unchecked")
public void converterThrowsIOException() throws IOException {
	HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream("Foobar".getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willThrow(IOException.class);
	assertThatExceptionOfType(RestClientException.class).isThrownBy(() ->
			extractor.extractData(response))
		.withMessageContaining("Error while extracting response for type [class java.lang.String] and content type [text/plain]")
		.withCauseInstanceOf(IOException.class);
}
 
Example 13
@Test // SPR-16172
public void httpEntityWithContentType() throws Exception {
	initServlet(wac -> {
		RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class);
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		messageConverters.add(new MappingJackson2HttpMessageConverter());
		messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
		adapterDef.getPropertyValues().add("messageConverters", messageConverters);
		wac.registerBeanDefinition("handlerAdapter", adapterDef);
	}, ResponseEntityController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-entity");
	MockHttpServletResponse response = new MockHttpServletResponse();
	getServlet().service(request, response);
	assertEquals(200, response.getStatus());
	assertEquals("application/xml", response.getHeader("Content-Type"));
	assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
					"<testEntity><name>Foo Bar</name></testEntity>", response.getContentAsString());
}
 
Example 14
@Before
public void setup() {
	List<Person> composers = Arrays.asList(
			new Person("Johann Sebastian Bach").setSomeDouble(21),
			new Person("Johannes Brahms").setSomeDouble(.0025),
			new Person("Edvard Grieg").setSomeDouble(1.6035),
			new Person("Robert Schumann").setSomeDouble(Double.NaN));

	List<Person> performers = Arrays.asList(
			new Person("Vladimir Ashkenazy").setSomeBoolean(false),
			new Person("Yehudi Menuhin").setSomeBoolean(true));

	this.people = new PeopleWrapper(composers, performers);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new Jaxb2RootElementHttpMessageConverter());

	this.restTemplate = new RestTemplate();
	this.restTemplate.setMessageConverters(converters);

	this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
 
Example 15
Source Project: Milkomeda   Source File: CometCollectorResponseBodyAdvice.java    License: MIT License 5 votes vote down vote up
@Override
public Object beforeBodyWrite(Object body, @NonNull MethodParameter returnType, @NonNull MediaType selectedContentType,
                              @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                              @NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        ((ServletRequestAttributes) requestAttributes).getRequest().setAttribute(REQUEST_ATTRIBUTE_BODY, body);
    }
    return body;
}
 
Example 16
Source Project: webmvc   Source File: PlaceClient.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	trustAllSSL();
	String key = args[0];
	RestTemplate tmpl = new RestTemplate();
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new MappingJacksonHttpMessageConverter());
	tmpl.setMessageConverters(converters);
	PlaceResponse response = tmpl.getForObject(URL, PlaceResponse.class,
			LOCATION, key);
	System.out.println(response);
}
 
Example 17
@Test
public void zeroContentLength() throws IOException {
	HttpMessageConverter<?> converter = mock(HttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentLength(0);
	extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);

	Object result = extractor.extractData(response);
	assertNull(result);
}
 
Example 18
Source Project: microservice-kubernetes   Source File: CustomerClient.java    License: Apache License 2.0 5 votes vote down vote up
protected RestTemplate getRestTemplate() {
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	mapper.registerModule(new Jackson2HalModule());

	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
	converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
	converter.setObjectMapper(mapper);

	return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}
 
Example 19
/**
 * Constructor with list of converters and ContentNegotiationManager as well
 * as request/response body advice instances.
 */
protected AbstractMessageConverterMethodProcessor(List<HttpMessageConverter<?>> converters,
		ContentNegotiationManager manager, List<Object> requestResponseBodyAdvice) {

	super(converters, requestResponseBodyAdvice);
	this.contentNegotiationManager = (manager != null ? manager : new ContentNegotiationManager());
	this.pathStrategy = initPathStrategy(this.contentNegotiationManager);
	this.safeExtensions.addAll(this.contentNegotiationManager.getAllFileExtensions());
	this.safeExtensions.addAll(WHITELISTED_EXTENSIONS);
}
 
Example 20
public static void configureMessageConverters(List<HttpMessageConverter<?>> converters, Gson gson) {
    // Rend possible la production de texte (getFile)
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
    stringHttpMessageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_PLAIN));
    converters.add(stringHttpMessageConverter);
    // Rend possible l'utilisation de Gson pour la sérialisation/désérialisation
    GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
    gsonHttpMessageConverter.setGson(gson);
    converters.add(gsonHttpMessageConverter);
}
 
Example 21
Source Project: gemini   Source File: Config.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(0, new EntityRecordMessageConverter());
    converters.add(1, new EntityRecordListMessageConverter());
    converters.add(2, new EntityRecordApiTypeMessageConverter());
    converters.add(3, new EntityRecordListApiMessageConverter());
    converters.add(4, new CountRequestMessageConverter());
    converters.add(5, new CountRequestApiMessageConverter());
}
 
Example 22
Source Project: hygieia-core   Source File: WebMVCConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    MappingJackson2HttpMessageConverter jackson = new MappingJackson2HttpMessageConverter();

    jackson.setObjectMapper(new CustomObjectMapper());
    jackson.getObjectMapper()
            .disable(SerializationFeature.WRITE_NULL_MAP_VALUES)
            .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL);

    converters.add(jackson);
}
 
Example 23
Source Project: chassis   Source File: SpringMvcConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    for (MessageSerDe serDe : serDes) {
        converters.add(new SerDeHttpMessageConverter(serDe));
    }

    addDefaultHttpMessageConverters(converters);
}
 
Example 24
/**
 * Provides access to the shared {@link HttpMessageConverter}s used by the
 * {@link RequestMappingHandlerAdapter} and the
 * {@link ExceptionHandlerExceptionResolver}.
 * This method cannot be overridden.
 * Use {@link #configureMessageConverters(List)} instead.
 * Also see {@link #addDefaultHttpMessageConverters(List)} that can be
 * used to add default message converters.
 */
protected final List<HttpMessageConverter<?>> getMessageConverters() {
	if (this.messageConverters == null) {
		this.messageConverters = new ArrayList<HttpMessageConverter<?>>();
		configureMessageConverters(this.messageConverters);
		if (this.messageConverters.isEmpty()) {
			addDefaultHttpMessageConverters(this.messageConverters);
		}
		extendMessageConverters(this.messageConverters);
	}
	return this.messageConverters;
}
 
Example 25
@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
private ModelAndView handleResponseBody(Object returnValue, ServletWebRequest webRequest)
		throws ServletException, IOException {

	HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());
	List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
	if (acceptedMediaTypes.isEmpty()) {
		acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
	}
	MediaType.sortByQualityValue(acceptedMediaTypes);
	HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());
	Class<?> returnValueType = returnValue.getClass();
	if (this.messageConverters != null) {
		for (MediaType acceptedMediaType : acceptedMediaTypes) {
			for (HttpMessageConverter messageConverter : this.messageConverters) {
				if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
					messageConverter.write(returnValue, acceptedMediaType, outputMessage);
					return new ModelAndView();
				}
			}
		}
	}
	if (logger.isWarnEnabled()) {
		logger.warn("Could not find HttpMessageConverter that supports return type [" + returnValueType + "] and " +
				acceptedMediaTypes);
	}
	return null;
}
 
Example 26
@Before
public void setup() throws Exception {

	List<HttpMessageConverter<?>> converters = Arrays.asList(
			new StringHttpMessageConverter(), new MappingJackson2HttpMessageConverter());

	this.handler = new ResponseBodyEmitterReturnValueHandler(converters);
	this.request = new MockHttpServletRequest();
	this.response = new MockHttpServletResponse();
	this.webRequest = new ServletWebRequest(this.request, this.response);

	AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response);
	WebAsyncUtils.getAsyncManager(this.webRequest).setAsyncWebRequest(asyncWebRequest);
	this.request.setAsyncSupported(true);
}
 
Example 27
@Test
public void wrapConcurrentResult_ResponseEntity() throws Exception {
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new StringHttpMessageConverter());
	this.returnValueHandlers.addHandler(new HttpEntityMethodProcessor(converters));
	ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handleDeferred");
	handlerMethod = handlerMethod.wrapConcurrentResult(new ResponseEntity<>("bar", HttpStatus.OK));
	handlerMethod.invokeAndHandle(this.webRequest, this.mavContainer);

	assertEquals("bar", this.response.getContentAsString());
}
 
Example 28
/**
 * Return the media types supported by all provided message converters sorted by
 * specificity via {@link MediaType#sortBySpecificity(List)}.
 * @param messageConverters list of converters
 * @return list of MediaTypes
 */
private List<MediaType> getAllSupportedMediaTypes(
		List<HttpMessageConverter<?>> messageConverters) {
	Set<MediaType> allSupportedMediaTypes = new LinkedHashSet<MediaType>();
	for (HttpMessageConverter<?> messageConverter : messageConverters) {
		allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
	}
	List<MediaType> result = new ArrayList<MediaType>(allSupportedMediaTypes);
	MediaType.sortBySpecificity(result);
	return unmodifiableList(result);
}
 
Example 29
Source Project: telekom-workflow-engine   Source File: RestController.java    License: MIT License 5 votes vote down vote up
@PostConstruct
public void init(){
    for (HttpMessageConverter converter : adapter.getMessageConverters()) {
        if (converter instanceof GsonHttpMessageConverter) {
            Gson gson = new GsonBuilder().serializeNulls().create();
            ((GsonHttpMessageConverter)converter).setGson(gson);
        }
    }
}
 
Example 30
private List<HttpMessageConverter<?>> converters() {
  List<HttpMessageConverter<?>> result = Lists.newArrayList();
  result.add(new ByteArrayHttpMessageConverter());
  result.add(new StringHttpMessageConverter());
  result.add(new ResourceHttpMessageConverter());
  result.add(new SourceHttpMessageConverter<>());
  result.add(new AllEncompassingFormHttpMessageConverter());
  result.add(new Jaxb2RootElementHttpMessageConverter());
  result.add(gsonHttpMessageConverter);
  return result;
}