List of usage examples for org.springframework.web.client ResponseErrorHandler ResponseErrorHandler
ResponseErrorHandler
From source file:org.zalando.zmon.actuator.ZmonMetricsFilterTest.java
@Before public void setUp() { ConsoleReporter reporter = ConsoleReporter.forRegistry(metricRegistry).convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS).build(); reporter.start(2, TimeUnit.SECONDS); restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new ResponseErrorHandler() { @Override/*from w w w . ja v a 2s. c o m*/ public boolean hasError(final ClientHttpResponse response) throws IOException { // we want them all to pass return false; } @Override public void handleError(final ClientHttpResponse response) throws IOException { } }); }
From source file:com.art4ul.jcoonsample.client.service.TestService.java
public void doTest() { restClient.setBaseUrl("http://localhost:8080"); LOG.info("Example #1: Send GET request"); ResultModel result = restClient.exampleGetRequest("world"); LOG.info("simpleGetRequestTest return: {} \n", result.getResult()); LOG.info("Example #2: Send POST request with custom base URL"); UserModel userModel = new UserModel("Tester", "sam", "123456"); result = restClient.examplePostRequest("http://localhost:8080", userModel); LOG.info("simpleGetRequestTest return: {} \n", result.getResult()); LOG.info("Example #3: Send POST request with custom HTTP header"); result = restClient.examplePostRequestWithHeader(userModel, "test value"); LOG.info("simpleGetRequestTest return: {} \n", result.getResult()); LOG.info("Example #4: Send Get request with path variable"); result = restClient.exampleGetRequestWithPathVariable("test"); LOG.info("simpleGetRequestTest return: {} \n", result.getResult()); LOG.info("Example #5: Handle HTTP exception"); ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() { @Override//w ww . j a va2s. c o m public boolean hasError(ClientHttpResponse response) throws IOException { return true; } @Override public void handleError(ClientHttpResponse response) throws IOException { throw new CustomException( "HTTP code: " + response.getStatusCode() + " text: " + response.getStatusText()); } }; try { result = restClient.exampleException("test", responseErrorHandler); } catch (CustomException ex) { LOG.info("Exception: " + ex.getMessage()); } }
From source file:co.mafiagame.telegraminterface.inputhandler.UpdateController.java
private void setErrorHandler(RestTemplate restTemplate) { restTemplate.setErrorHandler(new ResponseErrorHandler() { @Override/* w w w .j a va 2 s . c om*/ public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException { return !clientHttpResponse.getStatusCode().equals(HttpStatus.OK); } @Override public void handleError(ClientHttpResponse clientHttpResponse) throws IOException { logger.error("error calling telegram getUpdate\n code:{}\n{}", clientHttpResponse.getStatusCode(), IOUtils.toString(clientHttpResponse.getBody())); } }); }
From source file:com.insys.cfclient.nozzle.InfluxDBSender.java
@Async public void sendBatch(List<String> messages) { log.debug("ENTER sendBatch"); httpClient.setErrorHandler(new ResponseErrorHandler() { @Override//from w w w .j a v a 2 s. c o m public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException { return clientHttpResponse.getRawStatusCode() > 399; } @Override public void handleError(ClientHttpResponse clientHttpResponse) throws IOException { } }); RetryTemplate retryable = new RetryTemplate(); retryable.setBackOffPolicy(getBackOffPolicy()); retryable.setRetryPolicy(new SimpleRetryPolicy(properties.getMaxRetries(), Collections.singletonMap(ResourceAccessException.class, true))); final AtomicInteger counter = new AtomicInteger(0); retryable.execute(retryContext -> { int count = counter.incrementAndGet(); log.trace("Attempt {} to deliver this batch", count); final StringBuilder builder = new StringBuilder(); messages.forEach(s -> builder.append(s).append("\n")); String body = builder.toString(); RequestEntity<String> entity = new RequestEntity<>(body, HttpMethod.POST, getUri()); ResponseEntity<String> response; response = httpClient.exchange(entity, String.class); if (response.getStatusCode() != HttpStatus.NO_CONTENT) { log.error("Failed to write logs to InfluxDB! Expected error code 204, got {}", response.getStatusCodeValue()); log.trace("Request Body: {}", body); log.trace("Response Body: {}", response.getBody()); } else { log.debug("batch sent successfully!"); } log.debug("EXIT sendBatch"); return null; }, recoveryContext -> { log.trace("Failed after {} attempts!", counter.get()); return null; }); }
From source file:org.mitreid.multiparty.web.ClientController.java
public ClientController() { restTemplate.setErrorHandler(new ResponseErrorHandler() { @Override/*from w w w .ja va 2 s. com*/ public boolean hasError(ClientHttpResponse response) throws IOException { // TODO Auto-generated method stub return false; } @Override public void handleError(ClientHttpResponse response) throws IOException { // TODO Auto-generated method stub logger.error("HTTP Error"); } }); }
From source file:org.springframework.cloud.dataflow.shell.command.HttpCommands.java
private RestTemplate createRestTemplate(final StringBuilder buffer) { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new ResponseErrorHandler() { @Override//from ww w .jav a2s . c o m public boolean hasError(ClientHttpResponse response) throws IOException { HttpStatus status = response.getStatusCode(); return (status == HttpStatus.BAD_GATEWAY || status == HttpStatus.GATEWAY_TIMEOUT || status == HttpStatus.INTERNAL_SERVER_ERROR); } @Override public void handleError(ClientHttpResponse response) throws IOException { outputError(response.getStatusCode(), buffer); } }); return restTemplate; }
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 ava2s.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(); } }
From source file:org.cloudfoundry.identity.uaa.integration.TestAccountSetup.java
private OAuth2RestTemplate createRestTemplate(OAuth2ProtectedResourceDetails resource, AccessTokenRequest accessTokenRequest) { OAuth2ClientContext context = new DefaultOAuth2ClientContext(accessTokenRequest); OAuth2RestTemplate client = new OAuth2RestTemplate(resource, context); client.setRequestFactory(new SimpleClientHttpRequestFactory() { @Override/*w w w .ja v a 2s . com*/ protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { super.prepareConnection(connection, httpMethod); connection.setInstanceFollowRedirects(false); } }); client.setErrorHandler(new ResponseErrorHandler() { // Pass errors through in response entity for status code analysis public boolean hasError(ClientHttpResponse response) throws IOException { return false; } public void handleError(ClientHttpResponse response) throws IOException { } }); List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>(); list.add(new StringHttpMessageConverter()); list.add(new MappingJacksonHttpMessageConverter()); client.setMessageConverters(list); return client; }
From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java
@SuppressWarnings("deprecation") private RestTemplate setErrorHandler(final RestTemplate restTemplate) { restTemplate.setErrorHandler(new ResponseErrorHandler() { private final Set<HttpStatus> errorStatuses = new HashSet<>(); /* non-static */ { errorStatuses.add(HttpStatus.BAD_REQUEST); errorStatuses.add(HttpStatus.UNAUTHORIZED); errorStatuses.add(HttpStatus.FORBIDDEN); errorStatuses.add(HttpStatus.NOT_FOUND); errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED); errorStatuses.add(HttpStatus.NOT_ACCEPTABLE); errorStatuses.add(HttpStatus.REQUEST_TIMEOUT); errorStatuses.add(HttpStatus.CONFLICT); errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE); errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG); errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE); errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS); errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR); errorStatuses.add(HttpStatus.NOT_IMPLEMENTED); errorStatuses.add(HttpStatus.BAD_GATEWAY); errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE); }/*from ww w .j a v a2 s . c o m*/ @Override public boolean hasError(final ClientHttpResponse response) throws IOException { return errorStatuses.contains(response.getStatusCode()); } @Override public void handleError(final ClientHttpResponse response) throws IOException { System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText()); System.err.println(readBody(response)); } private String readBody(final ClientHttpResponse response) throws IOException { BufferedReader responseBodyReader = null; try { responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody())); StringBuilder buffer = new StringBuilder(); String line; while ((line = responseBodyReader.readLine()) != null) { buffer.append(line).append(System.getProperty("line.separator")); } return buffer.toString().trim(); } finally { FileSystemUtils.close(responseBodyReader); } } }); return restTemplate; }