org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter Java Examples

The following examples show how to use org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter. 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 File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-12149
public void jacksonJsonViewWithResponseEntityAndXmlMessageConverter() throws Exception {
	Method method = JacksonController.class.getMethod("handleResponseEntity");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

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

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));

	Object returnValue = new JacksonController().handleResponseEntity();
	processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);

	String content = this.servletResponse.getContentAsString();
	assertFalse(content.contains("<withView1>with</withView1>"));
	assertTrue(content.contains("<withView2>with</withView2>"));
	assertFalse(content.contains("<withoutView>without</withoutView>"));
}
 
Example #2
Source File: MvcConfig.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
    final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.indentOutput(true)
        .dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm"));
    messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true)
        .build()));

    messageConverters.add(createXmlHttpMessageConverter());
    // messageConverters.add(new MappingJackson2HttpMessageConverter());

    messageConverters.add(new ProtobufHttpMessageConverter());
    messageConverters.add(new KryoHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
}
 
Example #3
Source File: AllEncompassingFormHttpMessageConverter.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public AllEncompassingFormHttpMessageConverter() {
	addPartConverter(new SourceHttpMessageConverter<>());

	if (jaxb2Present && !jackson2XmlPresent) {
		addPartConverter(new Jaxb2RootElementHttpMessageConverter());
	}

	if (jackson2Present) {
		addPartConverter(new MappingJackson2HttpMessageConverter());
	}
	else if (gsonPresent) {
		addPartConverter(new GsonHttpMessageConverter());
	}
	/*else if (jsonbPresent) {
		addPartConverter(new JsonbHttpMessageConverter());
	}*/

	if (jackson2XmlPresent) {
		addPartConverter(new MappingJackson2XmlHttpMessageConverter());
	}

	/*if (jackson2SmilePresent) {
		addPartConverter(new MappingJackson2SmileHttpMessageConverter());
	}*/
}
 
Example #4
Source File: ExtRestTemplate.java    From onetwo with Apache License 2.0 6 votes vote down vote up
public ExtRestTemplate(ClientHttpRequestFactory requestFactory){
		super();
		/*CUtils.findByClass(this.getMessageConverters(), MappingJackson2HttpMessageConverter.class)
				.ifPresent(p->{
					MappingJackson2HttpMessageConverter convertor = p.getValue();
					convertor.setObjectMapper(JsonMapper.IGNORE_NULL.getObjectMapper());
					convertor.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, 
																	MediaType.APPLICATION_JSON_UTF8,
																	MediaType.TEXT_PLAIN));
				});*/
		CUtils.replaceOrAdd(getMessageConverters(), MappingJackson2HttpMessageConverter.class, new ApiclientJackson2HttpMessageConverter());
		CUtils.replaceOrAdd(getMessageConverters(), MappingJackson2XmlHttpMessageConverter.class, new ApiclientJackson2XmlMessageConverter());
		
		applyDefaultCharset();
		
		if(requestFactory!=null){
			this.setRequestFactory(requestFactory);
//			this.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
		}
		this.setErrorHandler(new OnExtRestErrorHandler());
	}
 
Example #5
Source File: RestSpringModuleConfig.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * This is called from requestMappingHandlerAdapter to configure the message converters. We override it to configure our own converter in addition to the
 * default converters.
 *
 * @param converters the converter list we configure.
 */
@Override
@SuppressWarnings("rawtypes")
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters)
{
    // Add in our custom converter first.
    converters.add(marshallingMessageConverter());

    // Add in the default converters (e.g. standard JAXB, Jackson, etc.).
    addDefaultHttpMessageConverters(converters);

    // Remove the Jackson2Xml converter since we want to use JAXB instead when we encounter "application/xml". Otherwise, the XSD auto-generated
    // classes with JAXB annotations won't get used.
    // Set jackson mapper to include only properties with non-null values.
    for (HttpMessageConverter httpMessageConverter : converters)
    {
        if (httpMessageConverter instanceof MappingJackson2XmlHttpMessageConverter)
        {
            converters.remove(httpMessageConverter);
            break;
        }
    }
}
 
Example #6
Source File: AllEncompassingFormHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public AllEncompassingFormHttpMessageConverter() {
	addPartConverter(new SourceHttpMessageConverter<Source>());

	if (jaxb2Present && !jackson2Present) {
		addPartConverter(new Jaxb2RootElementHttpMessageConverter());
	}

	if (jackson2Present) {
		addPartConverter(new MappingJackson2HttpMessageConverter());
	}
	else if (gsonPresent) {
		addPartConverter(new GsonHttpMessageConverter());
	}

	if (jackson2XmlPresent) {
		addPartConverter(new MappingJackson2XmlHttpMessageConverter());
	}
}
 
Example #7
Source File: RequestResponseBodyMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root><withView1>with</withView1><withView2>with</withView2><withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

	Method method = JacksonController.class.getMethod("handleHttpEntity", HttpEntity.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

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

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	HttpEntity<JacksonViewBean> result = (HttpEntity<JacksonViewBean>)processor.resolveArgument(methodParameter,
			this.mavContainer, this.webRequest, this.binderFactory);

	assertNotNull(result);
	assertNotNull(result.getBody());
	assertEquals("with", result.getBody().getWithView1());
	assertNull(result.getBody().getWithView2());
	assertNull(result.getBody().getWithoutView());
}
 
Example #8
Source File: RequestResponseBodyMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test  // SPR-12501
public void resolveArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root><withView1>with</withView1><withView2>with</withView2><withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

	Method method = JacksonController.class.getMethod("handleRequestBody", JacksonViewBean.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

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

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	JacksonViewBean result = (JacksonViewBean)processor.resolveArgument(methodParameter,
			this.mavContainer, this.webRequest, this.binderFactory);

	assertNotNull(result);
	assertEquals("with", result.getWithView1());
	assertNull(result.getWithView2());
	assertNull(result.getWithoutView());
}
 
Example #9
Source File: RequestResponseBodyMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test  // SPR-12149
public void jacksonJsonViewWithResponseEntityAndXmlMessageConverter() throws Exception {
	Method method = JacksonController.class.getMethod("handleResponseEntity");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

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

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));

	Object returnValue = new JacksonController().handleResponseEntity();
	processor.handleReturnValue(returnValue, methodReturnType, this.mavContainer, this.webRequest);

	String content = this.servletResponse.getContentAsString();
	assertFalse(content.contains("<withView1>with</withView1>"));
	assertTrue(content.contains("<withView2>with</withView2>"));
	assertFalse(content.contains("<withoutView>without</withoutView>"));
}
 
Example #10
Source File: RequestResponseBodyMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test  // SPR-12149
public void jacksonJsonViewWithResponseBodyAndXmlMessageConverter() throws Exception {
	Method method = JacksonController.class.getMethod("handleResponseBody");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

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

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));

	Object returnValue = new JacksonController().handleResponseBody();
	processor.handleReturnValue(returnValue, methodReturnType, this.mavContainer, this.webRequest);

	String content = this.servletResponse.getContentAsString();
	assertFalse(content.contains("<withView1>with</withView1>"));
	assertTrue(content.contains("<withView2>with</withView2>"));
	assertFalse(content.contains("<withoutView>without</withoutView>"));
}
 
Example #11
Source File: AllEncompassingFormHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public AllEncompassingFormHttpMessageConverter() {
	addPartConverter(new SourceHttpMessageConverter<Source>());

	if (jaxb2Present && !jackson2XmlPresent) {
		addPartConverter(new Jaxb2RootElementHttpMessageConverter());
	}

	if (jackson2Present) {
		addPartConverter(new MappingJackson2HttpMessageConverter());
	}
	else if (gsonPresent) {
		addPartConverter(new GsonHttpMessageConverter());
	}

	if (jackson2XmlPresent) {
		addPartConverter(new MappingJackson2XmlHttpMessageConverter());
	}
}
 
Example #12
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Build the RestTemplate used to make HTTP requests.
 * @return RestTemplate
 */
protected RestTemplate buildRestTemplate() {
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new MappingJackson2HttpMessageConverter());
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    xmlMapper.registerModule(new JsonNullableModule());
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter(xmlMapper));

    RestTemplate restTemplate = new RestTemplate(messageConverters);
    
    for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
        if(converter instanceof AbstractJackson2HttpMessageConverter){
            ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
            ThreeTenModule module = new ThreeTenModule();
            module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
            module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
            module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
            mapper.registerModule(module);
            mapper.registerModule(new JsonNullableModule());
        }
    }
    // This allows us to read the response more than once - Necessary for debugging.
    restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
    return restTemplate;
}
 
Example #13
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-12149
public void jacksonJsonViewWithResponseBodyAndXmlMessageConverter() throws Exception {
	Method method = JacksonController.class.getMethod("handleResponseBody");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

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

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));

	Object returnValue = new JacksonController().handleResponseBody();
	processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);

	String content = this.servletResponse.getContentAsString();
	assertFalse(content.contains("<withView1>with</withView1>"));
	assertTrue(content.contains("<withView2>with</withView2>"));
	assertFalse(content.contains("<withoutView>without</withoutView>"));
}
 
Example #14
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-12149
public void jacksonJsonViewWithResponseBodyAndXmlMessageConverter() throws Exception {
	Method method = JacksonController.class.getMethod("handleResponseBody");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

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

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));

	Object returnValue = new JacksonController().handleResponseBody();
	processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);

	String content = this.servletResponse.getContentAsString();
	assertFalse(content.contains("<withView1>with</withView1>"));
	assertTrue(content.contains("<withView2>with</withView2>"));
	assertFalse(content.contains("<withoutView>without</withoutView>"));
}
 
Example #15
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-12149
public void jacksonJsonViewWithResponseEntityAndXmlMessageConverter() throws Exception {
	Method method = JacksonController.class.getMethod("handleResponseEntity");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

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

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));

	Object returnValue = new JacksonController().handleResponseEntity();
	processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);

	String content = this.servletResponse.getContentAsString();
	assertFalse(content.contains("<withView1>with</withView1>"));
	assertTrue(content.contains("<withView2>with</withView2>"));
	assertFalse(content.contains("<withoutView>without</withoutView>"));
}
 
Example #16
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-12501
public void resolveArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root>" +
			"<withView1>with</withView1>" +
			"<withView2>with</withView2>" +
			"<withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

	Method method = JacksonController.class.getMethod("handleRequestBody", JacksonViewBean.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

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

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	JacksonViewBean result = (JacksonViewBean)
			processor.resolveArgument(methodParameter, this.container, this.request, this.factory);

	assertNotNull(result);
	assertEquals("with", result.getWithView1());
	assertNull(result.getWithView2());
	assertNull(result.getWithoutView());
}
 
Example #17
Source File: AdviceTraitTesting.java    From problem-spring-web with MIT License 5 votes vote down vote up
default MockMvc mvc() {
    final ObjectMapper mapper = mapper();

    return MockMvcBuilders
            .standaloneSetup(new ExampleRestController())
            .setContentNegotiationManager(new ContentNegotiationManager(singletonList(
                    new FixedContentNegotiationStrategy(APPLICATION_JSON))))
            .setControllerAdvice(unit())
            .setMessageConverters(
                    new MappingJackson2HttpMessageConverter(mapper),
                    new MappingJackson2XmlHttpMessageConverter())
            .build();
}
 
Example #18
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-12501
public void resolveArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root>" +
			"<withView1>with</withView1>" +
			"<withView2>with</withView2>" +
			"<withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

	Method method = JacksonController.class.getMethod("handleRequestBody", JacksonViewBean.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

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

	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	JacksonViewBean result = (JacksonViewBean)
			processor.resolveArgument(methodParameter, this.container, this.request, this.factory);

	assertNotNull(result);
	assertEquals("with", result.getWithView1());
	assertNull(result.getWithView2());
	assertNull(result.getWithoutView());
}
 
Example #19
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root>" +
			"<withView1>with</withView1>" +
			"<withView2>with</withView2>" +
			"<withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

	Method method = JacksonController.class.getMethod("handleHttpEntity", HttpEntity.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

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

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	HttpEntity<JacksonViewBean> result = (HttpEntity<JacksonViewBean>)
			processor.resolveArgument(methodParameter, this.container, this.request, this.factory);

	assertNotNull(result);
	assertNotNull(result.getBody());
	assertEquals("with", result.getBody().getWithView1());
	assertNull(result.getBody().getWithView2());
	assertNull(result.getBody().getWithoutView());
}
 
Example #20
Source File: WebMvcConfigurationSupportTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(12, converters.size());
	converters.stream()
			.filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter)
			.forEach(converter -> {
				ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
				assertFalse(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));
				if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
					assertEquals(XmlMapper.class, mapper.getClass());
				}
			});

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	assertNotNull(initializer);

	ConversionService conversionService = initializer.getConversionService();
	assertNotNull(conversionService);
	assertTrue(conversionService instanceof FormattingConversionService);

	Validator validator = initializer.getValidator();
	assertNotNull(validator);
	assertTrue(validator instanceof LocalValidatorFactoryBean);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	@SuppressWarnings("unchecked")
	List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
	assertEquals(2, bodyAdvice.size());
	assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
	assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}
 
Example #21
Source File: RestTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance of the {@link RestTemplate} using default settings.
 * Default {@link HttpMessageConverter}s are initialized.
 */
public RestTemplate() {
	this.messageConverters.add(new ByteArrayHttpMessageConverter());
	this.messageConverters.add(new StringHttpMessageConverter());
	this.messageConverters.add(new ResourceHttpMessageConverter());
	this.messageConverters.add(new SourceHttpMessageConverter<Source>());
	this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

	if (romePresent) {
		this.messageConverters.add(new AtomFeedHttpMessageConverter());
		this.messageConverters.add(new RssChannelHttpMessageConverter());
	}

	if (jackson2XmlPresent) {
		this.messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
	}
	else if (jaxb2Present) {
		this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
	}

	if (jackson2Present) {
		this.messageConverters.add(new MappingJackson2HttpMessageConverter());
	}
	else if (gsonPresent) {
		this.messageConverters.add(new GsonHttpMessageConverter());
	}
}
 
Example #22
Source File: WebMvcConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(9, converters.size());
	for(HttpMessageConverter<?> converter : converters) {
		if (converter instanceof AbstractJackson2HttpMessageConverter) {
			ObjectMapper objectMapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
			assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
			assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
			assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
			if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
				assertEquals(XmlMapper.class, objectMapper.getClass());
			}
		}
	}

	ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	assertNotNull(initializer);

	ConversionService conversionService = initializer.getConversionService();
	assertNotNull(conversionService);
	assertTrue(conversionService instanceof FormattingConversionService);

	Validator validator = initializer.getValidator();
	assertNotNull(validator);
	assertTrue(validator instanceof LocalValidatorFactoryBean);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	@SuppressWarnings("unchecked")
	List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
	assertEquals(2, bodyAdvice.size());
	assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
	assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}
 
Example #23
Source File: AllEncompassingFormHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public AllEncompassingFormHttpMessageConverter() {
	try {
		addPartConverter(new SourceHttpMessageConverter<>());
	}
	catch (Error err) {
		// Ignore when no TransformerFactory implementation is available
	}

	if (jaxb2Present && !jackson2XmlPresent) {
		addPartConverter(new Jaxb2RootElementHttpMessageConverter());
	}

	if (jackson2Present) {
		addPartConverter(new MappingJackson2HttpMessageConverter());
	}
	else if (gsonPresent) {
		addPartConverter(new GsonHttpMessageConverter());
	}
	else if (jsonbPresent) {
		addPartConverter(new JsonbHttpMessageConverter());
	}

	if (jackson2XmlPresent) {
		addPartConverter(new MappingJackson2XmlHttpMessageConverter());
	}

	if (jackson2SmilePresent) {
		addPartConverter(new MappingJackson2SmileHttpMessageConverter());
	}
}
 
Example #24
Source File: GoogleSearchProviderImpl.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private GoogleMasterIndex readGoogleMasterIndex(int connectTimeout, int readTimeout) {
    try {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
        setTimeout(restTemplate, connectTimeout, readTimeout);
        ObjectMapper mapper = Jackson2ObjectMapperBuilder.xml().build();
        mapper = mapper.addHandler(new DeserializationProblemHandler() {
            @Override
            public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
                if (beanOrClass instanceof GoogleMasterIndex) {
                    ((GoogleMasterIndex) beanOrClass).getGroups().put(propertyName, BASE_URL + propertyName.replace(".", "/") + "/" + GROUP_INDEX);
                    return true;
                }
                return false;
            }

        });
        restTemplate.getMessageConverters().clear();
        restTemplate.getMessageConverters().add(new MappingJackson2XmlHttpMessageConverter(mapper));
        ResponseEntity<GoogleMasterIndex> response = restTemplate.exchange(BASE_URL + MASTER_INDEX, HttpMethod.GET, new HttpEntity<>(requestHeaders), GoogleMasterIndex.class);
        return response.getBody();
    } catch (Exception exception) {
        Exceptions.printStackTrace(exception);
    }
    return null;
}
 
Example #25
Source File: GoogleSearchProviderImpl.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private GoogleGroupIndex readGoogleGroupIndex(final String group, final String url, int connectTimeout, int readTimeout) {
    try {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
        setTimeout(restTemplate, connectTimeout, readTimeout);
        ObjectMapper mapper = Jackson2ObjectMapperBuilder.xml().build();
        mapper = mapper.addHandler(new DeserializationProblemHandler() {
            @Override
            public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
                if (beanOrClass instanceof GoogleGroupIndex) {
                    if ("versions".equals(propertyName)) {
                        if (((GoogleGroupIndex) beanOrClass).lastArtifactId != null) {
                            ((GoogleGroupIndex) beanOrClass).downloaded.put(((GoogleGroupIndex) beanOrClass).lastArtifactId, p.getText());
                            ((GoogleGroupIndex) beanOrClass).lastArtifactId = null;
                        }
                    } else {
                        ((GoogleGroupIndex) beanOrClass).lastArtifactId = propertyName;
                    }
                    return true;
                }
                return false;
            }

        });
        restTemplate.getMessageConverters().clear();
        restTemplate.getMessageConverters().add(new MappingJackson2XmlHttpMessageConverter(mapper));
        ResponseEntity<GoogleGroupIndex> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(requestHeaders), GoogleGroupIndex.class);
        GoogleGroupIndex groupIndex = response.getBody();
        groupIndex.group = group;
        groupIndex.url = url;
        return groupIndex.build();
    } catch (Exception exception) {
        Exceptions.printStackTrace(exception);
    }
    return null;
}
 
Example #26
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
	String content = "<root>" +
			"<withView1>with</withView1>" +
			"<withView2>with</withView2>" +
			"<withoutView>without</withoutView></root>";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

	Method method = JacksonController.class.getMethod("handleHttpEntity", HttpEntity.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

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

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	HttpEntity<JacksonViewBean> result = (HttpEntity<JacksonViewBean>)
			processor.resolveArgument(methodParameter, this.container, this.request, this.factory);

	assertNotNull(result);
	assertNotNull(result.getBody());
	assertEquals("with", result.getBody().getWithView1());
	assertNull(result.getBody().getWithView2());
	assertNull(result.getBody().getWithoutView());
}
 
Example #27
Source File: RestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new instance of the {@link RestTemplate} using default settings.
 * Default {@link HttpMessageConverter}s are initialized.
 */
public RestTemplate() {
	this.messageConverters.add(new ByteArrayHttpMessageConverter());
	this.messageConverters.add(new StringHttpMessageConverter());
	this.messageConverters.add(new ResourceHttpMessageConverter());
	this.messageConverters.add(new SourceHttpMessageConverter<Source>());
	this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

	if (romePresent) {
		this.messageConverters.add(new AtomFeedHttpMessageConverter());
		this.messageConverters.add(new RssChannelHttpMessageConverter());
	}

	if (jackson2XmlPresent) {
		this.messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
	}
	else if (jaxb2Present) {
		this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
	}

	if (jackson2Present) {
		this.messageConverters.add(new MappingJackson2HttpMessageConverter());
	}
	else if (gsonPresent) {
		this.messageConverters.add(new GsonHttpMessageConverter());
	}
}
 
Example #28
Source File: HttpMessageConvertersConfig.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  final Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
  builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
  converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
  converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true)
                                                                   .build()));
}
 
Example #29
Source File: WSConfigurationEnabled.java    From jfilter with Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    if (filterRegister != null)
        filterRegister.configureMessageConverters(converters);
    converters.add(new MappingJackson2HttpMessageConverter());
    converters.add(new MappingJackson2XmlHttpMessageConverter());
    super.configureMessageConverters(converters);
}
 
Example #30
Source File: MockUtils.java    From jfilter with Apache License 2.0 5 votes vote down vote up
public static boolean beanFilterConverterLoaded(List<Object> registeredConverters) {
    final AtomicBoolean result = new AtomicBoolean(false);
    registeredConverters.forEach(i -> {
        if (i instanceof FilterConverter) {
            result.set(true);
        } else if (i instanceof MappingJackson2HttpMessageConverter &&
                ((MappingJackson2HttpMessageConverter) i).getObjectMapper() instanceof FilterObjectMapper) {
            result.set(true);
        } else if (i instanceof MappingJackson2XmlHttpMessageConverter &&
                ((MappingJackson2XmlHttpMessageConverter) i).getObjectMapper() instanceof FilterXmlMapper) {
            result.set(true);
        }
    });
    return result.get();
}