List of usage examples for org.springframework.http.client ClientHttpResponse getRawStatusCode
int getRawStatusCode() throws IOException;
From source file:org.zalando.zmon.actuator.metrics.MetricsWrapper.java
public void recordBackendRoundTripMetrics(final HttpRequest request, final ClientHttpResponse response, final StopWatch stopwatch) { try {/*from w w w . j a v a 2 s. c o m*/ recordBackendRoundTripMetrics(request.getMethod().name(), getHost(request), response.getRawStatusCode(), stopwatch.getTotalTimeMillis()); } catch (IOException e) { logger.warn("Could not detect status for " + response); } }
From source file:org.bremersee.common.web.client.ResponseErrorHandlerImpl.java
/** * Find a throwable instance by calling the {@link ExceptionRegistry}. * * @param response the HTTP response as JSON * @return the throwable//from w w w. j a v a 2s. c om * @throws IOException if the response cannot be parsed */ protected RuntimeException findThrowableByStatusCode(final ClientHttpResponse response) throws IOException { return ExceptionRegistry.getExceptionByHttpStatusCode(response.getRawStatusCode(), response.getStatusText()); }
From source file:org.cloudfoundry.identity.uaa.oauth.RemoteTokenServices.java
public RemoteTokenServices() { restTemplate = new RestTemplate(); ((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() { @Override//from www . j a va 2 s . c om // Ignore 400 public void handleError(ClientHttpResponse response) throws IOException { if (response.getRawStatusCode() != 400) { super.handleError(response); } } }); }
From source file:com.netflix.genie.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
/** * Constructor./* www . j av a2 s . co m*/ * * @param serverProperties The properties of the resource server (Genie) * @param converter The access token converter to use * @param registry The metrics registry to use */ public PingFederateRemoteTokenServices(@NotNull final ResourceServerProperties serverProperties, @NotNull final AccessTokenConverter converter, @NotNull final MeterRegistry registry) { super(); this.authenticationTimer = registry.timer(AUTHENTICATION_TIMER_NAME); this.pingFederateAPITimer = registry.timer(API_TIMER_NAME); final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(2000); factory.setReadTimeout(10000); final RestTemplate restTemplate = new RestTemplate(factory); final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors .add((final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) -> { final long start = System.nanoTime(); try { return execution.execute(request, body); } finally { pingFederateAPITimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }); restTemplate.setInterceptors(interceptors); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { // Ignore 400 @Override public void handleError(final ClientHttpResponse response) throws IOException { final int errorCode = response.getRawStatusCode(); registry.counter(TOKEN_VALIDATION_ERROR_COUNTER_NAME, Sets.newHashSet(Tag.of(MetricsConstants.TagKeys.STATUS, Integer.toString(errorCode)))) .increment(); if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) { super.handleError(response); } } }); this.setRestTemplate(restTemplate); this.checkTokenEndpointUrl = serverProperties.getTokenInfoUri(); this.clientId = serverProperties.getClientId(); this.clientSecret = serverProperties.getClientSecret(); Assert.state(StringUtils.isNotBlank(this.checkTokenEndpointUrl), "Check Endpoint URL is required"); Assert.state(StringUtils.isNotBlank(this.clientId), "Client ID is required"); Assert.state(StringUtils.isNotBlank(this.clientSecret), "Client secret is required"); log.debug("checkTokenEndpointUrl = {}", this.checkTokenEndpointUrl); log.debug("clientId = {}", this.clientId); log.debug("clientSecret = {}", this.clientSecret); this.converter = converter; }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
/** * Constructor.//from w w w . ja v a 2s . com * * @param serverProperties The properties of the resource server (Genie) * @param converter The access token converter to use * @param registry The metrics registry to use */ public PingFederateRemoteTokenServices(@NotNull final ResourceServerProperties serverProperties, @NotNull final AccessTokenConverter converter, @NotNull final Registry registry) { super(); this.tokenValidationError = registry .createId("genie.security.oauth2.pingFederate.tokenValidation.error.rate"); this.authenticationTimer = registry.timer(AUTHENTICATION_TIMER_NAME); this.pingFederateAPITimer = registry.timer(API_TIMER_NAME); final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(2000); factory.setReadTimeout(10000); final RestTemplate restTemplate = new RestTemplate(factory); final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors .add((final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) -> { final long start = System.nanoTime(); try { return execution.execute(request, body); } finally { pingFederateAPITimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }); restTemplate.setInterceptors(interceptors); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { // Ignore 400 @Override public void handleError(final ClientHttpResponse response) throws IOException { final int errorCode = response.getRawStatusCode(); registry.counter(tokenValidationError.withTag("status", Integer.toString(errorCode))).increment(); if (response.getRawStatusCode() != HttpStatus.BAD_REQUEST.value()) { super.handleError(response); } } }); this.setRestTemplate(restTemplate); this.checkTokenEndpointUrl = serverProperties.getTokenInfoUri(); this.clientId = serverProperties.getClientId(); this.clientSecret = serverProperties.getClientSecret(); Assert.state(StringUtils.isNotBlank(this.checkTokenEndpointUrl), "Check Endpoint URL is required"); Assert.state(StringUtils.isNotBlank(this.clientId), "Client ID is required"); Assert.state(StringUtils.isNotBlank(this.clientSecret), "Client secret is required"); log.debug("checkTokenEndpointUrl = {}", this.checkTokenEndpointUrl); log.debug("clientId = {}", this.clientId); log.debug("clientSecret = {}", this.clientSecret); this.converter = converter; }
From source file:com.springsource.insight.plugin.springweb.http.SimpleClientHttpRequestFactoryCollectionAspectTest.java
@Test public void testConnectionFactory() throws Exception { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setBufferRequestBody(false); factory.setConnectTimeout(15 * 1000); factory.setReadTimeout(15 * 1000);//w w w.ja va 2 s .co m URI uri = new URI("http://localhost:" + TEST_PORT + "/testConnectionFactory"); HttpMethod method = HttpMethod.GET; ClientHttpRequest request = factory.createRequest(uri, method); ClientHttpResponse response = request.execute(); assertEquals("Mismatched response code", HttpStatus.OK.value(), response.getRawStatusCode()); BufferedReader rdr = new BufferedReader(new InputStreamReader(response.getBody())); try { for (String line = rdr.readLine(); line != null; line = rdr.readLine()) { logger.info(line); } } finally { rdr.close(); } Operation op = assertConnectionOperation(uri, method); assertExternalResource(op, uri); }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandler.java
private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException { HttpStatus statusCode;//from w w w.j a v a 2 s . c o m try { statusCode = response.getStatusCode(); } catch (IllegalArgumentException ex) { throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); } return statusCode; }
From source file:io.github.microcks.util.openapi.OpenAPITestRunner.java
@Override protected int extractTestReturnCode(Service service, Operation operation, Request request, ClientHttpResponse httpResponse, String responseContent) { int code = TestReturn.SUCCESS_CODE; int responseCode = 0; try {/*from w w w. j av a 2s. c o m*/ responseCode = httpResponse.getRawStatusCode(); } catch (IOException ioe) { log.debug("IOException while getting raw status code in response", ioe); return TestReturn.FAILURE_CODE; } // If required, compare response code to expected one. if (validateResponseCode) { Response expectedResponse = responseRepository.findOne(request.getResponseId()); if (String.valueOf(responseCode).equals(expectedResponse.getStatus())) { log.debug("Response HttpStatus does not match expected one, returning failure"); return TestReturn.FAILURE_CODE; } } // Retrieve the resource corresponding to OpenAPI specification if any. Resource openapiSpecResource = null; List<Resource> resources = resourceRepository.findByServiceId(service.getId()); for (Resource resource : resources) { if (ResourceType.OPEN_API_SPEC.equals(resource.getType())) { openapiSpecResource = resource; break; } } if (openapiSpecResource == null) { log.debug("Do not found any OpenAPI specification resource for service {0}, so failing validating", service.getId()); return TestReturn.FAILURE_CODE; } JsonNode openapiSpec = null; try { openapiSpec = OpenAPISchemaValidator.getJsonNodeForSchema(openapiSpecResource.getContent()); } catch (IOException ioe) { log.debug("OpenAPI specification cannot be transformed into valid JsonNode schema, so failing"); return TestReturn.FAILURE_CODE; } // Extract JsonNode corresponding to response. String verb = operation.getName().split(" ")[0].toLowerCase(); String path = operation.getName().split(" ")[1].trim(); MediaType mediaType = httpResponse.getHeaders().getContentType(); log.debug("Response media-type is {}", mediaType.toString()); String pointer = "/paths/" + path.replace("/", "~1") + "/" + verb + "/responses/" + responseCode + "/content/" + mediaType.toString().replace("/", "~1"); JsonNode responseNode = openapiSpec.at(pointer); log.debug("responseNode: " + responseNode); // Is there a specified responseNode for this type ?? if (responseNode != null && !responseNode.isMissingNode()) { // Get body content as a string. JsonNode contentNode = null; try { contentNode = OpenAPISchemaValidator.getJsonNode(responseContent); } catch (IOException ioe) { log.debug("Response body cannot be accessed or transformed as Json, returning failure"); return TestReturn.FAILURE_CODE; } // Build a schema object with responseNode schema as root and by importing // all the common parts that may be referenced by references. JsonNode schemaNode = responseNode.path("schema").deepCopy(); ((ObjectNode) schemaNode).set("components", openapiSpec.path("components").deepCopy()); lastValidationErrors = OpenAPISchemaValidator.validateJson(schemaNode, contentNode); if (!lastValidationErrors.isEmpty()) { log.debug("OpenAPI schema validation errors found " + lastValidationErrors.size() + ", marking test as failed."); return TestReturn.FAILURE_CODE; } log.debug("OpenAPI schema validation of response is successful !"); } else { // Do we still have a response body ?? if (httpResponse.getHeaders().getContentLength() > 0) { log.debug("No response expected or defined but response has content, failing"); code = TestReturn.FAILURE_CODE; } } return code; }
From source file:cz.jirutka.spring.http.client.cache.DefaultCachingPolicy.java
protected boolean isResponseCacheable(ClientHttpResponse response) { boolean cacheable = false; HttpHeaders headers = response.getHeaders(); try {/*from w ww .j a v a 2 s. c o m*/ int status = response.getRawStatusCode(); if (isImplicitlyCacheableStatus(status)) { cacheable = true; //MAY be cached } else if (isUncacheableStatus(status)) { log.trace("Response with status code {} is not cacheable", status); return false; } } catch (IOException ex) { throw new IllegalStateException(ex); } if (isExplicitlyNonCacheable(response)) { log.trace("Response with Cache-Control: '{}' is not cacheable", headers.getCacheControl()); return false; } if (headers.getContentLength() > maxBodySizeBytes) { log.debug("Response with Content-Lenght {} > {} is not cacheable", headers.getContentLength(), maxBodySizeBytes); return false; } try { if (response.getHeaders().getDate() < 0) { log.debug("Response without a valid Date header is not cacheable"); return false; } } catch (IllegalArgumentException ex) { return false; } // dunno how to properly handle Vary if (headers.containsKey("Vary")) { log.trace("Response with Vary header is not cacheable"); return false; } return (cacheable || isExplicitlyCacheable(response)); }