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

The following examples show how to use org.springframework.http.converter.json.MappingJackson2HttpMessageConverter. 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: RequestMappingHandlerAdapterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: WebConfig.java    From wetech-admin with 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 #3
Source File: HttpEntityMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #5
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #6
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #7
Source File: RequestResponseBodyMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: MyfeedAutoConfig.java    From myfeed with 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 #9
Source File: RestTemplateFactory.java    From spring-boot-chatbot with 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 #10
Source File: ManagementConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
@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 #11
Source File: RestTemplateBuilder.java    From carina with 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 #12
Source File: DataflowTemplateTests.java    From spring-cloud-dashboard with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #14
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #15
Source File: RequestResponseBodyMethodProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #16
Source File: ConfigCommandTests.java    From spring-cloud-dataflow with 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 #17
Source File: WebConfig.java    From cf-SpringBootTrader with 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 #18
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #19
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #20
Source File: RequestMappingHandlerAdapterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #21
Source File: RequestPartIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #22
Source File: ServletInvocableHandlerMethodTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #23
Source File: ManagementConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
@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 #24
Source File: RestHelper.java    From taskana with 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 #25
Source File: CustomRestTemplate.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
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 #26
Source File: HttpEntityMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #27
Source File: HttpEntityMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #28
Source File: DataflowTemplateTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
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 #29
Source File: SchemaControllerTest.java    From data-highway with 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 #30
Source File: NonBindableServiceInstanceBindingControllerIntegrationTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp() {
	ServiceInstanceBindingService serviceInstanceBindingService = new NonBindableServiceInstanceBindingService();
	ServiceInstanceBindingController controller =
			new ServiceInstanceBindingController(catalogService, serviceInstanceBindingService);

	this.mockMvc = MockMvcBuilders.standaloneSetup(controller)
			.setControllerAdvice(ServiceBrokerWebMvcExceptionHandler.class)
			.setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
}