@Before public void setup() { this.mockMvc = standaloneSetup(new PostController(postService, posts, comments)) .setCustomArgumentResolvers( new PageableHandlerMethodArgumentResolver() ) // .setViewResolvers(new ViewResolver() { // @Override // public org.springframework.web.servlet.View resolveViewName(String viewName, Locale locale) // throws Exception { // return new MappingJackson2JsonView(objectMapper); // } // }) .setMessageConverters( new MappingJackson2HttpMessageConverter(objectMapper) ) .alwaysDo(print()) .apply(springSecurity(springSecurityFilterChain)) .build(); }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { /*FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4(); FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,//保留空的字段 SerializerFeature.WriteNullStringAsEmpty,//String null -> "" SerializerFeature.WriteNullNumberAsZero);//Number null -> 0 converter.setFastJsonConfig(config); converter.setDefaultCharset(Charset.forName("UTF-8"));*/ MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(); List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.APPLICATION_JSON_UTF8); mediaTypes.add(MediaType.TEXT_HTML); jacksonConverter.setSupportedMediaTypes(mediaTypes); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); jacksonConverter.setObjectMapper(objectMapper); converters.add(jacksonConverter); //converters.add(responseBodyConverter()); }
EmailServiceImpl(Environment env, TextService text) { this.env = requireNonNull(env); this.text = requireNonNull(text); this.mailgun = new RestTemplate(); this.mailgun.setMessageConverters(asList( new FormHttpMessageConverter(), new StringHttpMessageConverter(), new MappingJackson2HttpMessageConverter() )); this.mailgun.getInterceptors().add(new BasicAuthorizationInterceptor( "api", env.getProperty("mailgun.apiKey") )); }
protected RestTemplate getRestTemplate() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new Jackson2HalModule()); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON)); converter.setObjectMapper(mapper); return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter)); }
@Test public void postsEndWithPathParam() { String result = restTemplate.postForObject( controllerUrl + "sayhello/{name}", null, String.class, "world"); assertThat(jsonOf(result, String.class), is("hello world")); List<HttpMessageConverter<?>> convertersOld = restTemplate.getMessageConverters(); List<HttpMessageConverter<?>> converters = new ArrayList<>(); converters.add(new MappingJackson2HttpMessageConverter()); restTemplate.setMessageConverters(converters); result = restTemplate.postForObject( controllerUrl + "sayhello/{name}", null, String.class, "中 国"); assertThat(result, is("hello 中 国")); restTemplate.setMessageConverters(convertersOld); }
public static void main(String[] args) throws Exception { RestTemplate template = new RestTemplate(); template.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("X-Tenant-Name", "default"); RequestEntity<String> requestEntity = new RequestEntity<String>(headers, HttpMethod.GET, new URI("http://127.0.0.1:9980/registry/v3/microservices")); ResponseEntity<String> stringResponseEntity = template.exchange(requestEntity, String.class); System.out.println(stringResponseEntity.getBody()); ResponseEntity<MicroserviceArray> microseriveResponseEntity = template .exchange(requestEntity, MicroserviceArray.class); MicroserviceArray microserives = microseriveResponseEntity.getBody(); System.out.println(microserives.getServices().get(1).getServiceId()); // instance headers.add("X-ConsumerId", microserives.getServices().get(1).getServiceId()); requestEntity = new RequestEntity<String>(headers, HttpMethod.GET, new URI("http://127.0.0.1:9980/registry/v3/microservices/" + microserives.getServices().get(1).getServiceId() + "/instances")); ResponseEntity<String> microserviceInstanceResponseEntity = template.exchange(requestEntity, String.class); System.out.println(microserviceInstanceResponseEntity.getBody()); }
@Bean public Filter ssoFilter(ClientResources client, String path) { MappingJackson2HttpMessageConverter customJsonMessageConverter = new MappingJackson2HttpMessageConverter(); customJsonMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN)); MyOAuth2ClientAuthenticationProcessingFilter filter = new MyOAuth2ClientAuthenticationProcessingFilter(path); filter.setAllowSessionCreation(true); MyOAuth2RestTemplate template = new MyOAuth2RestTemplate(client.getClient(), oauth2ClientContext); template.setMessageConverters(Arrays.asList(customJsonMessageConverter)); filter.setRestTemplate(template); MyUserInfoTokenServices tokenServices = new MyUserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId(), userService, userWechatService, userPrivilegeService, privilegeConfigService); tokenServices.setRestTemplate(template); filter.setTokenServices(tokenServices); return filter; }
/** * Create a new instance of the {@link RestTemplate} using default settings. * Default {@link HttpMessageConverter}s are initialized. */ @SuppressWarnings("deprecation") 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 (jaxb2Present) { this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); } if (jackson2Present) { this.messageConverters.add(new MappingJackson2HttpMessageConverter()); } else if (jacksonPresent) { this.messageConverters.add(new org.springframework.http.converter.json.MappingJacksonHttpMessageConverter()); } }
@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."); }
protected AbstractZg2proRestTemplate(SimpleModule sm) { super(); //converters List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new ByteArrayHttpMessageConverter()); messageConverters.add(new ResourceHttpMessageConverter()); ObjectMapper jsonMapper = camelToKebabObjectMapper(sm); messageConverters.add(new MappingJackson2HttpMessageConverter(jsonMapper)); this.setMessageConverters(messageConverters); //errors handling setErrorHandler(new RestTemplateErrorHandler()); /* //interceptors LoggingRequestInterceptor lri = new LoggingRequestInterceptor(); this.setInterceptors(new ArrayList<>()); this.getInterceptors().add(lri); this.setRequestFactory(LoggingRequestFactoryFactory.build(lri)); */ }
public RestTemplate validateRestTemplate(RestTemplate restTemplate) { boolean containsMappingJackson2HttpMessageConverter = false; for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) { if (converter instanceof MappingJackson2HttpMessageConverter) { containsMappingJackson2HttpMessageConverter = true; } } if (!containsMappingJackson2HttpMessageConverter) { throw new IllegalArgumentException( "The RestTemplate does not contain a required " + "MappingJackson2HttpMessageConverter."); } return restTemplate; }
@Override public RevokedLicenses call() { try { final String url = REMOTE_ADDRESS + "/ReaderBackend/GetRevokedLicenses"; RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); return restTemplate.getForObject(url, RevokedLicenses.class); } catch (Exception e) { Log.e("MainActivity", e.getMessage(), e); } return null; }
@Override public PartialDrivingLicense call() { try { final String url = REMOTE_ADDRESS+"/ReaderBackend/GetLicense/"+license; RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); return restTemplate.getForObject(url, PartialDrivingLicense.class); } catch (Exception e) { Log.e("MainActivity", e.getMessage(), e); } return null; }
@Override public CertificateList call() { try { final String url = REMOTE_ADDRESS+"/ReaderBackend/GetCSCACertificates"; RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); return restTemplate.getForObject(url, CertificateList.class); } catch (Exception e) { Log.e("MainActivity", e.getMessage(), e); } return null; }
@Override public Certificate call() { try { final String url = REMOTE_ADDRESS+"/ReaderBackend/GetCSCACertificate/"+certificate; RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); return restTemplate.getForObject(url, Certificate.class); } catch (Exception e) { Log.e("MainActivity", e.getMessage(), e); } return null; }
@Override public RevocationList call() { try { final String url = REMOTE_ADDRESS+"/ReaderBackend/GetRevocationList/"+certificate; RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); return restTemplate.getForObject(url, RevocationList.class); } catch (Exception e) { Log.e("MainActivity", e.getMessage(), e); } return null; }
@Test public void ableToPostObjectAsJsonWithRequestVariable() { Person input = new Person(); input.setName("world"); String result = restTemplate.postForObject( controllerUrl + "saysomething?prefix={prefix}", jsonRequest(input), String.class, "hello"); assertThat(jsonOf(result, String.class), is("hello world")); List<HttpMessageConverter<?>> convertersOld = restTemplate.getMessageConverters(); List<HttpMessageConverter<?>> converters = new ArrayList<>(); converters.add(new MappingJackson2HttpMessageConverter()); restTemplate.setMessageConverters(converters); input = new Person(); input.setName("中国"); result = restTemplate.postForObject( controllerUrl + "saysomething?prefix={prefix}", jsonRequest(input), String.class, "hello"); assertThat(result, is("hello 中国")); restTemplate.setMessageConverters(convertersOld); }
@Bean public RestTemplate createRestTemplate() { RestTemplate restTemplate = new RestTemplate(); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter(); jsonMessageConverter.setObjectMapper(objectMapper); messageConverters.add(jsonMessageConverter); restTemplate.setMessageConverters(messageConverters); return restTemplate; }
/** * Render model and view. * * @param model the model * @param response the response */ public static void render(final Object model, final HttpServletResponse response) { try { final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); jsonConverter.setPrettyPrint(true); final MediaType jsonMimeType = MediaType.APPLICATION_JSON; jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response)); } catch (final Exception e) { throw new RuntimeException(e); } }
public JsonDataProviderConnector(final Class<T> dtoType) { this.dtoType = dtoType; final ObjectMapper objectMapper = createObjectMapper(); final MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter(); mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper); // create message converters list httpMessageConverters = new ArrayList<>(); httpMessageConverters.add(mappingJacksonHttpMessageConverter); }
public ClickatellSmsSender(final String token, final String serverUrl) { this.token = token; this.serverUrl = serverUrl; mapper.findAndRegisterModules(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); }
/** * Render model and view. * * @param model the model * @param response the response */ public static void render(final Object model, final HttpServletResponse response) { try { final MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); jsonConverter.setPrettyPrint(true); final MediaType jsonMimeType = MediaType.APPLICATION_JSON; jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response)); } catch (final Exception e) { throw Throwables.propagate(e); } }
@Autowired void setMappingJackson2HttpMessageConverter(HttpMessageConverter<?>[] converters) { this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream() .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter) .findAny() .orElse(null); assertNotNull("JSON message converter must not be null.", this.mappingJackson2HttpMessageConverter); }
private List<HttpMessageConverter<?>> getHttpMessageConverters() { List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new ByteArrayHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new ResourceHttpMessageConverter()); messageConverters.add(new UploadApplicationPayloadHttpMessageConverter()); messageConverters.add(getFormHttpMessageConverter()); messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new LoggregatorHttpMessageConverter()); return messageConverters; }
@Override public Object postProcessBeforeInitialization(Object bean, String s) { if (bean instanceof RequestMappingHandlerAdapter) { ((RequestMappingHandlerAdapter) bean).getMessageConverters().stream() .filter(converter -> converter instanceof MappingJackson2HttpMessageConverter) .forEach(converter -> { MappingJackson2HttpMessageConverter halConverterCandidate = (MappingJackson2HttpMessageConverter) converter; ObjectMapper objectMapper = halConverterCandidate.getObjectMapper(); if (Jackson2HalModule.isAlreadyRegisteredIn(objectMapper)) { List<MediaType> vendorSpecificTypes = new ArrayList<>(halConverterCandidate.getSupportedMediaTypes()); vendorSpecificTypes.add(V1MediaType.V1_HAL_DOCUMENT_COLLECTION_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_HAL_DOCUMENT_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_HAL_FOLDER_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_HAL_DOCUMENT_CONTENT_VERSION_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_HAL_AUDIT_ENTRY_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_HAL_DOCUMENT_AND_METADATA_COLLECTION_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_DOCUMENT_COLLECTION_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_DOCUMENT_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_FOLDER_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_DOCUMENT_CONTENT_VERSION_MEDIA_TYPE); vendorSpecificTypes.add(V1MediaType.V1_AUDIT_ENTRY_MEDIA_TYPE); ((MappingJackson2HttpMessageConverter) converter).setSupportedMediaTypes(vendorSpecificTypes); } }); } return bean; }
/** * * /** sendPostCommand * * @param url * @param parameters * @return * @throws ClientProtocolException */ public Map<String, Object> sendPostForUpload(String url, Map<String, Object> parameters) { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setBufferRequestBody(false); RestTemplate restTemplate = new RestTemplate(requestFactory); List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters(); mc.add(new MappingJackson2HttpMessageConverter()); restTemplate.setMessageConverters(mc); MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>(); postParams.setAll(parameters); Map<String, Object> response = new HashMap<String, Object>(); HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "multipart/form-data"); headers.set("Accept", "application/json"); headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue()); HttpEntity<Object> request = new HttpEntity<Object>(postParams, headers); ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class); String body = result.getBody().toString(); MediaType contentType = result.getHeaders().getContentType(); HttpStatus statusCode = result.getStatusCode(); response.put(CONTENT_TYPE, contentType); response.put(STATUS_CODE, statusCode); response.put(BODY, body); return response; }
@Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); jsonConverter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json")); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); objectMapper.registerModule(new Jackson2HalModule()); jsonConverter.setObjectMapper(objectMapper); return jsonConverter; }
@Bean ( name = "csapEventsService" ) public RestTemplate csapEventsService ( CsapRestTemplateFactory factory ) { RestTemplate restTemplate = factory.buildDefaultTemplate( "csapEvents", false, 10, 10, 5, 5, 300 ); restTemplate.getMessageConverters().clear(); restTemplate.getMessageConverters().add( new FormHttpMessageConverter() ); restTemplate.getMessageConverters().add( new StringHttpMessageConverter() ); restTemplate.getMessageConverters().add( new MappingJackson2HttpMessageConverter() ); return restTemplate; }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(objectMapper()); converters.add(converter); super.configureMessageConverters(converters); }
@Override protected MappingJackson2HttpMessageConverter getJsonMessageConverter() { MappingJackson2HttpMessageConverter converter = super.getJsonMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new DiscordModule()); converter.setObjectMapper(objectMapper); return converter; }
public QQOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) { super(resource, context); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new StringHttpMessageConverter());//for https://graph.qq.com/oauth2.0/me messageConverters.add(new QQTokenHttpMessageConverter()); //for token messageConverters.add(new MappingJackson2HttpMessageConverter() { @Override protected boolean canRead(MediaType mediaType) { return true; } });//for userInfo need custom this.setMessageConverters(messageConverters); this.setAccessTokenProvider(new QQAuthorizationCodeAccessTokenProvider(messageConverters)); }
@Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.registerModule(new JavaTimeModule()); converter.setObjectMapper(objectMapper); converters.add(converter); super.configureMessageConverters(converters); }