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

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

Introduction

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

Prototype

public void setInterceptors(List<ClientHttpRequestInterceptor> interceptors) 

Source Link

Document

Set the request interceptors that this accessor should use.

Usage

From source file:de.hska.ld.core.AbstractIntegrationTest.java

@SuppressWarnings("unchecked")
protected <T> T getForObject(String resource, User user, Class<T> responseType, Map<String, ?> urlVariables) {
    resource = BASE_URL + resource;
    if (user == null) {
        if (urlVariables == null) {
            return template.getForObject(resource, responseType);
        } else {//from w  ww . java2  s  .  c o m
            return template.getForObject(resource, responseType, urlVariables);
        }
    } else {
        String usernameAndPassword = user.getUsername() + ":" + PASSWORD;
        byte[] auth = usernameAndPassword.getBytes();
        RestTemplate objectTemplate = new LDRestTemplate();
        ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
            byte[] encodedAuthorisation = Base64.encode(auth);
            request.getHeaders().add("Authorization", "Basic " + new String(encodedAuthorisation));
            return execution.execute(request, body);
        };
        List<ClientHttpRequestInterceptor> list = new ArrayList<>();
        list.add(interceptor);
        objectTemplate.setInterceptors(list);
        if (urlVariables == null) {
            return objectTemplate.getForObject(resource, responseType);
        } else {
            return objectTemplate.getForObject(resource, responseType, urlVariables);
        }
    }
}

From source file:com.feedeo.rest.client.AbstractRestClient.java

protected RestOperations createRestOperations(ObjectMapper objectMapper,
        ClientHttpRequestFactory clientHttpRequestFactory) {
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);

    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(mappingJackson2HttpMessageConverter);
    restTemplate.setMessageConverters(messageConverters);

    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new ClientHttpRequestInterceptor() {
        @Override/*from   ww w . j  a  v a  2s . c  om*/
        public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes,
                ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
            return clientHttpRequestExecution.execute(httpRequest, bytes);
        }
    });
    restTemplate.setInterceptors(interceptors);

    return restTemplate;
}

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//w w  w . j a va 2s.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/*from   w w w  . j ava2  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.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 w  w w .j a  v  a2  s.  co  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 {//w w w  .  j  a  va  2 s  .  co m
        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 ww .j a  v a 2 s .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.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 a  v a  2 s .c om
        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();
    }
}