Example usage for org.springframework.web.client RestTemplate setMessageConverters

List of usage examples for org.springframework.web.client RestTemplate setMessageConverters

Introduction

In this page you can find the example usage for org.springframework.web.client RestTemplate setMessageConverters.

Prototype

public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) 

Source Link

Document

Set the message body converters to use.

Usage

From source file:fr.itldev.koya.services.impl.UserServiceImpl.java

/**
 * Authenticated RestTemplate Factory.//from ww  w.j ava2 s  . co  m
 *
 * @return
 */
private RestTemplate getAuthenticatedRestTemplate(String login, String password) throws MalformedURLException {
    URL url = new URL(getAlfrescoServerUrl());

    RestTemplate userRestTemplate = new RestClient(login, password, url.getHost(), url.getPort(),
            url.getProtocol());
    List<HttpMessageConverter<?>> msgConverters = new ArrayList<>();
    msgConverters.add((HttpMessageConverter<?>) beanFactory.getBean("stringHttpMessageConverter"));
    msgConverters.add((HttpMessageConverter<?>) beanFactory.getBean("jsonHttpMessageConverter"));
    msgConverters.add((HttpMessageConverter<?>) beanFactory.getBean("formHttpMessageConverter"));
    userRestTemplate.setMessageConverters(msgConverters);
    userRestTemplate.setErrorHandler((ResponseErrorHandler) beanFactory.getBean("alfrescoRestErrorHandler"));

    return userRestTemplate;
}

From source file:org.jnrain.mobile.service.JNRainSpiceService.java

@Override
public RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new GzipRestTemplate();
    // find more complete examples in RoboSpice Motivation app
    // to enable Gzip compression and setting request timeouts.

    // web services support json responses
    MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
    final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();

    listHttpMessageConverters.add(jsonConverter);
    listHttpMessageConverters.add(formHttpMessageConverter);
    listHttpMessageConverters.add(stringHttpMessageConverter);
    restTemplate.setMessageConverters(listHttpMessageConverters);

    // timeout//from   ww w.  java2  s. c o m
    manageTimeOuts(restTemplate);

    // session interceptor
    restTemplate.setInterceptors(_interceptors);

    return restTemplate;
}

From source file:org.springframework.boot.test.web.client.TestRestTemplate.java

/**
 * Creates a new {@code TestRestTemplate} with the same configuration as this one,
 * except that it will send basic authorization headers using the given
 * {@code username} and {@code password}.
 * @param username the username// www  .jav  a 2 s. c o  m
 * @param password the password
 * @return the new template
 * @since 1.4.1
 */
public TestRestTemplate withBasicAuth(String username, String password) {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getRestTemplate().getMessageConverters());
    restTemplate.setInterceptors(getRestTemplate().getInterceptors());
    restTemplate.setRequestFactory(getRestTemplate().getRequestFactory());
    restTemplate.setUriTemplateHandler(getRestTemplate().getUriTemplateHandler());
    TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username, password,
            this.httpClientOptions);
    testRestTemplate.getRestTemplate().setErrorHandler(getRestTemplate().getErrorHandler());
    return testRestTemplate;
}

From source file:com.kixeye.chassis.transport.HybridServiceTest.java

@Test
public void testHybridService() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestCombinedService.class);

    WebSocketClient wsClient = new WebSocketClient();

    RestTemplate httpClient = new RestTemplate();

    try {// www  . jav a  2s  . co  m
        context.refresh();

        final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
            messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
        }
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        httpClient.setMessageConverters(messageConverters);

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, null);

        Session session = wsClient
                .connect(webSocket, new URI("ws://localhost:" + properties.get("websocket.port") + "/protobuf"))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        session.getRemote().sendBytes(ByteBuffer.wrap(serDe.serialize(envelope)));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("even more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("even more stuff", response.value);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}

From source file:net.gplatform.spring.social.weibo.connect.WeiboOAuth2Template.java

@Override
protected RestTemplate createRestTemplate() {
    RestTemplate restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory());
    HttpMessageConverter<?> messageConverter = new FormHttpMessageConverter() {

        private final ObjectMapper objectMapper = new ObjectMapper();

        @Override//from ww w  . ja  v a  2 s  . c  o m
        public boolean canRead(Class<?> clazz, MediaType mediaType) {
            return true;
        }

        @Override
        public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz,
                HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

            TypeReference<Map<String, ?>> mapType = new TypeReference<Map<String, ?>>() {
            };
            LinkedHashMap<String, ?> readValue = objectMapper.readValue(inputMessage.getBody(), mapType);
            LinkedMultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>();
            for (Entry<String, ?> currentEntry : readValue.entrySet()) {
                result.add(currentEntry.getKey(), currentEntry.getValue().toString());
            }
            return result;
        }
    };

    restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
    return restTemplate;
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithXml() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "false");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {//from www  .  j  a v a2 s.c  o m
        context.refresh();

        final MessageSerDe serDe = context.getBean(XmlMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithYaml() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "false");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {/*from   ww  w .  j av  a  2  s . com*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(YamlJacksonMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithProtobuf() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {/* w w  w .j  a  va  2s  . co  m*/
        context.refresh();

        final MessageSerDe serDe = context.getBean(ProtobufMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);

        error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/headerRequired"), null,
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.taxamo.example.ec.ApplicationController.java

/**
 * This method is invoked after Taxamo has successfully verified tax location evidence and
 * created a transaction.//ww  w.  jav a  2  s  .c om
 *
 * Two things happen then:
 * - first, the express checkout token is used to capture payment in PayPal
 * - next, transaction is confirmed with Taxamo
 *
 * After that, confirmation page is displayed to the customer.
 *
 * @param payerId
 * @param token
 * @param transactionKey
 * @param model
 * @return
 */
@RequestMapping(value = "/confirm")
public String confirm(@RequestParam("PayerID") String payerId, @RequestParam("token") String token,
        @RequestParam("taxamo_transaction_key") String transactionKey, Model model) {

    RestTemplate template = new RestTemplate();

    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("USER", ppUser);
    map.add("PWD", ppPass);
    map.add("SIGNATURE", ppSign);
    map.add("VERSION", "117");
    map.add("METHOD", "DoExpressCheckoutPayment");
    map.add("PAYERID", payerId);
    map.add("TOKEN", token);

    GetTransactionOut transaction; //more transaction details should be verified in real-life implementation
    try {
        transaction = taxamoApi.getTransaction(transactionKey);
    } catch (ApiException e) {
        e.printStackTrace();
        model.addAttribute("error", "ERROR result: " + e.getMessage());
        return "error";
    }

    map.add("PAYMENTREQUEST_0_CURRENCYCODE", "EUR");
    map.add("PAYMENTREQUEST_0_AMT", transaction.getTransaction().getTotalAmount().toString());
    map.add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale");

    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new StringHttpMessageConverter());
    template.setMessageConverters(messageConverters);

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map,
            requestHeaders);
    ResponseEntity<String> res = template.exchange(
            URI.create(properties.get(PropertiesConstants.PAYPAL_NVP).toString()), HttpMethod.POST, request,
            String.class);

    Map<String, List<String>> params = parseQueryParams(res.getBody());

    String ack = params.get("ACK").get(0);
    if (!ack.equals("Success")) {
        model.addAttribute("error", params.get("L_LONGMESSAGE0").get(0));
        return "error";
    } else {
        try {
            ConfirmTransactionOut transactionOut = taxamoApi.confirmTransaction(transactionKey,
                    new ConfirmTransactionIn());
            model.addAttribute("status", transactionOut.getTransaction().getStatus());
        } catch (ApiException ae) {
            ae.printStackTrace();
            model.addAttribute("error", "ERROR result: " + ae.getMessage());
            return "error";
        }
        model.addAttribute("taxamo_transaction_key", transactionKey);

        return "redirect:/success-checkout";
    }
}

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJson() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.enabled", "false");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {//from ww  w. j  av  a  2s  .co  m
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        RestTemplate httpClient = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}