Java Code Examples for org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

The following examples show how to use org.springframework.http.converter.json.MappingJackson2HttpMessageConverter. 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: data-highway   Source File: SchemaControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  road = new RoadModel("road1", RoadType.NORMAL, "my road description", "my team", "[email protected]", true, null, null,
      of("foo", "bar"), true, Road.DEFAULT_COMPATIBILITY_MODE, emptyMap());

  objectMapper.registerModule(new SchemaSerializationModule());

  schemaJson = objectMapper.writeValueAsString(schema);
  mockMvc = standaloneSetup(schemaController)
      .setControllerAdvice(paverExceptionHandler, globalExceptionHandler)
      .setMessageConverters(new MappingJackson2HttpMessageConverter(objectMapper))
      .build();

  when(paverService.getActiveSchema(any(String.class), anyInt())).thenReturn(schemaVersion);
  when(paverService.getRoad(ROAD_NAME)).thenReturn(road);
}
 
Example 2
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.
            json().
            //propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).
            propertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE).
            //featuresToEnable(SerializationFeature.INDENT_OUTPUT).
            //featuresToEnable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY).
            build();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Set.class,
            new StdDelegatingSerializer(Set.class, new StdConverter<Set, List>() {
                @Override
                public List convert(Set value) {
                    LinkedList list = new LinkedList(value);
                    Collections.sort(list);
                    return list;
                }
            })
    );
    objectMapper.registerModule(module);
    HttpMessageConverter c = new MappingJackson2HttpMessageConverter(
            objectMapper
    );
    converters.add(c);
}
 
Example 3
Source Project: spring-boot-chatbot   Source File: RestTemplateFactory.java    License: MIT License 6 votes vote down vote up
public static RestOperations getRestOperations(HttpComponentsClientHttpRequestFactory factory) {
    RestTemplate restTemplate = new RestTemplate(factory);

    StringHttpMessageConverter stringMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    MappingJackson2HttpMessageConverter jackson2Converter = new MappingJackson2HttpMessageConverter();
    ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    formHttpMessageConverter.setCharset(Charset.forName("UTF-8"));

    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(jackson2Converter);
    converters.add(stringMessageConverter);
    converters.add(byteArrayHttpMessageConverter);
    converters.add(formHttpMessageConverter);

    restTemplate.setMessageConverters(converters);
    return restTemplate;
}
 
Example 4
@Test  // SPR-12501
public void resolveArgumentWithJacksonJsonView() throws Exception {
	String content = "{\"withView1\" : \"with\", \"withView2\" : \"with\", \"withoutView\" : \"without\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_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 MappingJackson2HttpMessageConverter());

	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 5
Source Project: wetech-admin   Source File: WebConfig.java    License: MIT License 6 votes vote down vote up
@Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();

        //不显示为null的字段
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //序列化枚举是以ordinal()来输出
//        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, true);
        SimpleModule simpleModule = new SimpleModule();
//        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
//        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        //放到第一个
        converters.add(0, jackson2HttpMessageConverter);
    }
 
Example 6
@Test
public void resolveArgumentClassJson() throws Exception {
	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType("application/json");

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(
			paramSimpleBean, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
Example 7
@Test  // SPR-11225
public void resolveArgumentTypeVariableWithNonGenericConverter() throws Exception {
	Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	HttpMessageConverter<Object> target = new MappingJackson2HttpMessageConverter();
	HttpMessageConverter<?> proxy = ProxyFactory.getProxy(HttpMessageConverter.class, new SingletonTargetSource(target));
	converters.add(proxy);
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
Example 8
@Test
public void jacksonJsonViewWithResponseBodyAndJsonMessageConverter() 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 MappingJackson2HttpMessageConverter());

	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\""));
	assertTrue(content.contains("\"withView2\":\"with\""));
	assertFalse(content.contains("\"withoutView\":\"without\""));
}
 
Example 9
Source Project: spring-cloud-dataflow   Source File: ConfigCommandTests.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	MockitoAnnotations.initMocks(this);

	final CommandLine commandLine = Mockito.mock(CommandLine.class);

	when(commandLine.getArgs()).thenReturn(null);

	final List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
	messageConverters.add(new MappingJackson2HttpMessageConverter());

	when(restTemplate.getMessageConverters()).thenReturn(messageConverters);

	TargetHolder targetHolder = new TargetHolder();
	targetHolder.setTarget(new Target("http://localhost:9393"));
	configCommands.setTargetHolder(targetHolder);
	configCommands.setRestTemplate(restTemplate);
	configCommands.setDataFlowShell(dataFlowShell);
	configCommands.setServerUri("http://localhost:9393");
}
 
Example 10
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 11
@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 12
@Test // SPR-15478
public void wrapConcurrentResult_CollectedValuesListWithResponseEntity() throws Exception {
	List<HttpMessageConverter<?>> converters = Collections.singletonList(new MappingJackson2HttpMessageConverter());
	ResolvableType elementType = ResolvableType.forClass(Bar.class);
	ReactiveTypeHandler.CollectedValuesList result = new ReactiveTypeHandler.CollectedValuesList(elementType);
	result.add(new Bar("foo"));
	result.add(new Bar("bar"));

	ContentNegotiationManager manager = new ContentNegotiationManager();
	this.returnValueHandlers.addHandler(new RequestResponseBodyMethodProcessor(converters, manager));
	ServletInvocableHandlerMethod hm = getHandlerMethod(new ResponseEntityHandler(), "handleFlux");
	hm = hm.wrapConcurrentResult(result);
	hm.invokeAndHandle(this.webRequest, this.mavContainer);

	assertEquals(200, this.response.getStatus());
	assertEquals("[{\"value\":\"foo\"},{\"value\":\"bar\"}]", this.response.getContentAsString());
}
 
Example 13
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.
            json().
            //propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).
            propertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE).
            //featuresToEnable(SerializationFeature.INDENT_OUTPUT).
            //featuresToEnable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY).
            build();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Set.class,
            new StdDelegatingSerializer(Set.class, new StdConverter<Set, List>() {
                @Override
                public List convert(Set value) {
                    LinkedList list = new LinkedList(value);
                    Collections.sort(list);
                    return list;
                }
            })
    );
    objectMapper.registerModule(module);
    HttpMessageConverter c = new MappingJackson2HttpMessageConverter(
            objectMapper
    );
    converters.add(c);
}
 
Example 14
Source Project: taskana   Source File: RestHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return a REST template which is capable of dealing with responses in HAL format.
 *
 * @return RestTemplate
 */
private static RestTemplate getRestTemplate() {
  ObjectMapper mapper = new ObjectMapper();
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  mapper.registerModule(new Jackson2HalModule());
  mapper
      .registerModule(new ParameterNamesModule())
      .registerModule(new Jdk8Module())
      .registerModule(new JavaTimeModule());
  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
  converter.setSupportedMediaTypes(Collections.singletonList(MediaTypes.HAL_JSON));
  converter.setObjectMapper(mapper);

  RestTemplate template = new RestTemplate();
  // important to add first to ensure priority
  template.getMessageConverters().add(0, converter);
  return template;
}
 
Example 15
public CustomRestTemplate(Gson gson, UriTemplateHandler uriTemplateHandler, CloseableHttpClient httpClient) {
    super();
    this.gson = gson;
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    if (httpClient != null) {
        requestFactory.setHttpClient(httpClient);
    }
    requestFactory.setBufferRequestBody(false);
    setRequestFactory(requestFactory);
    setUriTemplateHandler(uriTemplateHandler);
    setErrorHandler(new NoOpResponseErrorHandler());
    // On vire Jackson:
    List<HttpMessageConverter<?>> converters = getMessageConverters().stream()
            .filter(httpMessageConverter -> !(httpMessageConverter instanceof MappingJackson2HttpMessageConverter))
            .collect(Collectors.toList());
    configureMessageConverters(converters, gson);
    setMessageConverters(converters);
}
 
Example 16
private DataFlowTemplate getMockedDataFlowTemplate(boolean isLinksActive) throws Exception{
	RestTemplate restTemplate = mock(RestTemplate.class);
	RootResource rootResource = mock(RootResource.class);
	Link link = mock(Link.class);
	when(link.getHref()).thenReturn("https://whereever");
	when(rootResource.getApiRevision()).thenReturn(Version.REVISION);
	when(rootResource.getLink(any(LinkRelation.class))).thenReturn(Optional.of(link));
	when(rootResource.hasLink(any(LinkRelation.class))).thenReturn(isLinksActive);
	when(rootResource.getLink(anyString())).thenReturn(Optional.of(link));
	when(rootResource.hasLink(anyString())).thenReturn(isLinksActive);
	when(restTemplate.getForObject(any(),any())).thenReturn(rootResource);
	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	when(restTemplate.getMessageConverters()).thenReturn(converters);
	URI uri = new URI("foo");
	return new DataFlowTemplate(uri, restTemplate);
}
 
Example 17
@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 18
@Test
public void resolveArgument() throws Exception {
	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType("application/json");

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters);

	@SuppressWarnings("unchecked")
	HttpEntity<SimpleBean> result = (HttpEntity<SimpleBean>) processor.resolveArgument(
			paramSimpleBean, mavContainer, webRequest, binderFactory);

	assertNotNull(result);
	assertEquals("Jad", result.getBody().getName());
}
 
Example 19
@Test
public void resolveGenericArgument() throws Exception {
	String content = "[{\"name\" : \"Jad\"}, {\"name\" : \"Robert\"}]";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType("application/json");

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters);

	@SuppressWarnings("unchecked")
	HttpEntity<List<SimpleBean>> result = (HttpEntity<List<SimpleBean>>) processor.resolveArgument(
			paramList, mavContainer, webRequest, binderFactory);

	assertNotNull(result);
	assertEquals("Jad", result.getBody().get(0).getName());
	assertEquals("Robert", result.getBody().get(1).getName());
}
 
Example 20
@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 21
@Test
public void resolveArgumentParameterizedType() throws Exception {
	String content = "[{\"name\" : \"Jad\"}, {\"name\" : \"Robert\"}]";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	@SuppressWarnings("unchecked")
	List<SimpleBean> result = (List<SimpleBean>) processor.resolveArgument(
			paramGenericList, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.get(0).getName());
	assertEquals("Robert", result.get(1).getName());
}
 
Example 22
@Test  // SPR-9964
public void resolveArgumentTypeVariable() throws Exception {
	Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
Example 23
@Test
public void jacksonJsonViewWithResponseEntityAndJsonMessageConverter() 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 MappingJackson2HttpMessageConverter());

	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\""));
	assertTrue(content.contains("\"withView2\":\"with\""));
	assertFalse(content.contains("\"withoutView\":\"without\""));
}
 
Example 24
@Test
public void resolveGenericArgument() throws Exception {
	String content = "[{\"name\" : \"Jad\"}, {\"name\" : \"Robert\"}]";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType("application/json");

	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new MappingJackson2HttpMessageConverter());
	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters);

	@SuppressWarnings("unchecked")
	HttpEntity<List<SimpleBean>> result = (HttpEntity<List<SimpleBean>>) processor.resolveArgument(
			paramList, mavContainer, webRequest, binderFactory);

	assertNotNull(result);
	assertEquals("Jad", result.getBody().get(0).getName());
	assertEquals("Robert", result.getBody().get(1).getName());
}
 
Example 25
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonView() throws Exception {
	String content = "{\"withView1\" : \"with\", \"withView2\" : \"with\", \"withoutView\" : \"without\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_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 MappingJackson2HttpMessageConverter());

	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 26
@Test  // SPR-12811
public void jacksonTypeInfoList() throws Exception {
	Method method = JacksonController.class.getMethod("handleTypeInfoList");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

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

	String content = this.servletResponse.getContentAsString();
	assertTrue(content.contains("\"type\":\"foo\""));
	assertTrue(content.contains("\"type\":\"bar\""));
}
 
Example 27
@Test
public void testPrepareRestTemplateWithRestTemplateThatMissesJacksonConverter() {
	final RestTemplate providedRestTemplate = new RestTemplate();
	final Iterator<HttpMessageConverter<?>> iterator = providedRestTemplate.getMessageConverters().iterator();

	while(iterator.hasNext()){
		if(iterator.next() instanceof MappingJackson2HttpMessageConverter) {
			iterator.remove();
		}
	}

	try {
		DataFlowTemplate.prepareRestTemplate(providedRestTemplate);
	}
	catch(IllegalArgumentException e) {
		assertEquals("The RestTemplate does not contain a required MappingJackson2HttpMessageConverter.", e.getMessage());
		return;
	}

	fail("Expected an IllegalArgumentException to be thrown.");
}
 
Example 28
Source Project: myfeed   Source File: MyfeedAutoConfig.java    License: Apache License 2.0 6 votes vote down vote up
private List<HttpMessageConverter<?>> getHttpMessageConverters() {
	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));

	ObjectMapper mapper = new ObjectMapper();
	mapper.registerModule(new Jackson2HalModule());
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

	MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

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

	converters.add(converter);
	return converters;
}
 
Example 29
Source Project: carina   Source File: RestTemplateBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public RestTemplateBuilder withSpecificJsonMessageConverter() {
    isUseDefaultJsonMessageConverter = false;

    AbstractHttpMessageConverter<?> jsonMessageConverter = new MappingJackson2HttpMessageConverter(
            Jackson2ObjectMapperBuilder
                    .json()
                    .featuresToEnable(
                            DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
                            DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
                    .build());
    jsonMessageConverter.setSupportedMediaTypes(Lists.newArrayList(
            MediaType.TEXT_HTML, MediaType.TEXT_PLAIN,
            MediaType.APPLICATION_JSON));

    withMessageConverter(jsonMessageConverter);

    return this;
}
 
Example 30
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    addDefaultHttpMessageConverters(converters);
    for (HttpMessageConverter<?> converter : converters) {
        if (converter instanceof MappingJackson2HttpMessageConverter) {
            MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = (MappingJackson2HttpMessageConverter) converter;
            jackson2HttpMessageConverter.setObjectMapper(objectMapper);
            break;
        }
    }
}