@Override public Iterable<Tag> getTags(String urlTemplate, HttpRequest request, ClientHttpResponse response) { Tag uriTag = StringUtils.hasText(urlTemplate)? RestTemplateExchangeTags.uri(urlTemplate): RestTemplateExchangeTags.uri(request); return Arrays.asList(RestTemplateExchangeTags.method(request), uriTag, RestTemplateExchangeTags.status(response), RestTemplateExchangeTags.clientName(request), modelName(request), modelImage(request), modelVersion(request), projectName(), deploymentName(), deploymentVersion(), predictorName(), predictorVersion()); }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { if (log.isDebugEnabled()) { log.debug(String.format("Request: %s %s %s", request.getMethod(), request.getURI(), new String(body, getCharset(request)))); } ClientHttpResponse response = execution.execute(request, body); if (log.isDebugEnabled()) { log.debug(String.format("Response: %s %s", response.getStatusCode().value(), copyToString(response.getBody(), getCharset(response)))); } return response; }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { if (omegaContext.globalTxId() != null) { request.getHeaders().add(GLOBAL_TX_ID_KEY, omegaContext.globalTxId()); request.getHeaders().add(LOCAL_TX_ID_KEY, omegaContext.localTxId()); LOG.debug("Added {} {} and {} {} to request header", GLOBAL_TX_ID_KEY, omegaContext.globalTxId(), LOCAL_TX_ID_KEY, omegaContext.localTxId()); } return execution.execute(request, body); }
/** * Execute the given method on the provided URI. The * {@link org.springframework.http.client.ClientHttpRequest} * is processed using the {@link RequestCallback}; the response with * the {@link ResponseExtractor}. * @param url the fully-expanded URL to connect to * @param method the HTTP method to execute (GET, POST, etc.) * @param requestCallback object that prepares the request (can be {@code null}) * @param responseExtractor object that extracts the return value from the response (can * be {@code null}) * @return an arbitrary object, as returned by the {@link ResponseExtractor} */ protected <T> ListenableFuture<T> doExecute(URI url, HttpMethod method, AsyncRequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { Assert.notNull(url, "'url' must not be null"); Assert.notNull(method, "'method' must not be null"); try { AsyncClientHttpRequest request = createAsyncRequest(url, method); if (requestCallback != null) { requestCallback.doWithRequest(request); } ListenableFuture<ClientHttpResponse> responseFuture = request.executeAsync(); return new ResponseExtractorFuture<T>(method, url, responseFuture, responseExtractor); } catch (IOException ex) { throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + url + "\":" + ex.getMessage(), ex); } }
@Override protected final T adapt(ClientHttpResponse response) throws ExecutionException { try { if (!getErrorHandler().hasError(response)) { logResponseStatus(this.method, this.url, response); } else { handleResponseError(this.method, this.url, response); } return convertResponse(response); } catch (IOException ex) { throw new ExecutionException(ex); } finally { if (response != null) { response.close(); } } }
private void traceResponse(ClientHttpResponse response) throws IOException { StringBuilder inputStringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8")); String line = bufferedReader.readLine(); while (line != null) { inputStringBuilder.append(line); inputStringBuilder.append('\n'); line = bufferedReader.readLine(); } log.debug("============================response begin=========================================="); log.debug("Status code : {}", response.getStatusCode()); log.debug("Status text : {}", response.getStatusText()); log.debug("Headers : {}", response.getHeaders()); log.debug("Response body: {}", inputStringBuilder.toString()); log.debug("=======================response end================================================="); }
@Test public void testPerformDiagnosis() throws IOException, URISyntaxException { Identifier<Jvm> aJvmId = new Identifier<>(11L); Jvm jvm = mock(Jvm.class); when(jvm.getId()).thenReturn(aJvmId); final URI uri = new URI("http://test.com"); when(jvm.getStatusUri()).thenReturn(new URI("http://test.com")); when(Config.mockJvmPersistenceService.getJvm(aJvmId)).thenReturn(jvm); ClientHttpResponse mockResponse = mock(ClientHttpResponse.class); when(mockResponse.getStatusCode()).thenReturn(HttpStatus.OK); when(Config.mockClientFactoryHelper.requestGet(any(URI.class))).thenReturn(mockResponse); jvmService.performDiagnosis(aJvmId, new User("user")); verify(Config.mockClientFactoryHelper).requestGet(eq(uri)); reset(Config.mockClientFactoryHelper); when(mockResponse.getStatusCode()).thenReturn(HttpStatus.REQUEST_TIMEOUT); when(Config.mockClientFactoryHelper.requestGet(any(URI.class))).thenReturn(mockResponse); jvmService.performDiagnosis(aJvmId, new User("user")); verify(Config.mockClientFactoryHelper).requestGet(eq(uri)); }
@Override public void handleError(ClientHttpResponse response) throws IOException { String seyrenResponseBody; LOGGER.debug("Response : {} {}", response.getStatusCode(), response.getStatusText()); if (response.getBody() != null) { seyrenResponseBody = CharStreams.toString(new InputStreamReader(response.getBody(), "UTF-8")); } else { seyrenResponseBody = "Response whithout body"; } CerebroException exception = new CerebroException(ErrorCode.SEYREN_ERROR, seyrenResponseBody); throw exception; }
private static void handleClientErrors(ClientHttpResponse response) throws IOException { HttpStatus statusCode = response.getStatusCode(); Map<String, Object> errorMap = extractErrorDetailsFromResponse(response); String errorText = ""; if (errorMap.containsKey("error")) { errorText = (String) errorMap.get("error"); } else if (errorMap.containsKey("errors")) { Object errors = errorMap.get("errors"); if (errors instanceof List) { @SuppressWarnings("unchecked") List<Map<String, String>> errorsList = (List<Map<String, String>>) errors; errorText = errorsList.get(0).get("message"); } else if (errors instanceof String) { errorText = (String) errors; } } if (statusCode == HttpStatus.BAD_REQUEST) { if (errorText.contains("Rate limit exceeded.")) { throw new RateLimitExceededException(TWITTER); } } else if (statusCode == HttpStatus.UNAUTHORIZED) { if (errorText == null) { throw new NotAuthorizedException(TWITTER, response.getStatusText()); } else if ("Could not authenticate you.".equals(errorText)) { throw new MissingAuthorizationException(TWITTER); } else if ("Could not authenticate with OAuth.".equals(errorText)) { // revoked token throw new RevokedAuthorizationException(TWITTER); } else if ("Invalid / expired Token".equals(errorText)) { // Note that Twitter doesn't actually expire tokens throw new InvalidAuthorizationException(TWITTER, errorText); } else { throw new NotAuthorizedException(TWITTER, errorText); } } else if (statusCode == HttpStatus.FORBIDDEN) { if (errorText.equals(DUPLICATE_STATUS_TEXT) || errorText.contains("You already said that")) { throw new DuplicateStatusException(TWITTER, errorText); } else if (errorText.equals(STATUS_TOO_LONG_TEXT) || errorText.contains(MESSAGE_TOO_LONG_TEXT)) { throw new MessageTooLongException(errorText); } else if (errorText.equals(INVALID_MESSAGE_RECIPIENT_TEXT)) { throw new InvalidMessageRecipientException(errorText); } else if (errorText.equals(DAILY_RATE_LIMIT_TEXT)) { throw new RateLimitExceededException(TWITTER); } else { throw new OperationNotPermittedException(TWITTER, errorText); } } else if (statusCode == HttpStatus.NOT_FOUND) { throw new ResourceNotFoundException(TWITTER, errorText); } else if (statusCode == HttpStatus.valueOf(ENHANCE_YOUR_CALM) || statusCode == HttpStatus .valueOf(TOO_MANY_REQUESTS)) { throw new RateLimitExceededException(TWITTER); } }
private static Map<String, Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(new JsonFactory()); try { return mapper.readValue(response.getBody(), new TypeReference<Map<String, Object>>() { }); } catch (JsonParseException e) { log.error("Can not parse error details from response", e); return Collections.emptyMap(); } }
@Override public ClientHttpResponse execute() throws IOException { path = findUriPath(uri); requestMeta = createRequestMeta(method.name(), uri); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri.getRawSchemeSpecificPart()); queryParams = queryStringDecoder.parameters(); Object[] args = this.collectArguments(); // 异常流程,直接抛异常出去 return this.invoke(args); }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { logRequest(request, body); ClientHttpResponse response = execution.execute(request, body); logResponse(response); return response; }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { traceRequest(request, body); ClientHttpResponse response = execution.execute(request, body); traceResponse(response); return response; }
@Override public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); headers.add("X-Auth-Token", tokenManager.getTokenHolder().getScopedToken(projectId)); if (LOG.isInfoEnabled()) { LOG.info("X-Auth-Token: " + tokenManager.getTokenHolder().getScopedToken(projectId)); } return execution.execute(request, body); }
private void assertNetworkCallFails(RestTemplate restTemplate, ClientHttpRequestFactory requestFactory) { restTemplate.setRequestFactory(requestFactory); try { HttpStatus status = restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, new ResponseExtractor<HttpStatus>() { public HttpStatus extractData(ClientHttpResponse response) throws IOException { return response.getStatusCode(); } }); Assert.fail("Expected byteman rules to detect direct socket connections, status is:" + status); } catch (Exception e) { // good, byteman rejected it as expected // e.printStackTrace(); } assertEquals("Not expecting Jetty to receive requests since we asked direct connections", 0, nbInJvmProxyRcvReqs.get()); }
@Test public void canBufferResponses() throws IOException { MockClientHttpRequest request = new MockClientHttpRequest(); MockClientHttpResponse response = new MockClientHttpResponse(singleUseStream("hello".getBytes()), OK); request.setResponse(response); when(requestFactory.createRequest(URI.create("http://example.com"), GET)).thenReturn(request); loggingCustomizer.customize(restTemplate); ClientHttpResponse actualResponse = restTemplate.getRequestFactory() .createRequest(URI.create("http://example.com"), GET) .execute(); assertThat(copyToByteArray(actualResponse.getBody()), equalTo("hello".getBytes())); }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { TxTransactionLocal txTransactionLocal = TxTransactionLocal.current(); String groupId = txTransactionLocal==null?null:txTransactionLocal.getGroupId(); request.getHeaders().add("tx-group",groupId); if (txTransactionLocal != null) { if (txTransactionLocal.isHasCompensate()) { request.getHeaders().add("tx-group", CompensateService.COMPENSATE_KEY); } else { request.getHeaders().add("tx-group",groupId); } } return execution.execute(request,body); }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); headers.add(AUTHORIZATION_HEADER, gitHubToken); headers.add(USER_AGENT_HEADER, USER_AGENT_VALUE); headers.setContentType(MediaType.APPLICATION_JSON); return execution.execute(request, body); }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); headers.add(AUTHORIZATION_HEADER, keycloakToken); headers.add(REQUEST_ID_HEADER, getRequestId()); return execution.execute(request, body); }
@Override public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); headers.add("X-Subject-Token", currentToken); headers.add("X-Auth-Token", currentToken); return execution.execute(request, body); }
@Test public void testInject() { String url = "http://localhost:4000/foo"; mockServer.expect(MockRestRequestMatchers.requestTo(url)) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(new ResponseCreator() { @Override public ClientHttpResponse createResponse(ClientHttpRequest request) throws IOException { MockClientHttpResponse response = new MockClientHttpResponse(new byte[1], HttpStatus.OK); response.getHeaders().add("traceId", request.getHeaders() .getFirst("traceId")); response.getHeaders().add("spanId", request.getHeaders() .getFirst("spanId")); return response; } }); ResponseEntity<String> responseEntity = client.getForEntity(url, String.class); List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); Assert.assertEquals(mockSpans.get(0).context().traceId(), Long.parseLong(responseEntity.getHeaders().getFirst("traceId"))); Assert.assertEquals(mockSpans.get(0).context().spanId(), Long.parseLong(responseEntity.getHeaders().getFirst("spanId"))); }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { long startTime = System.nanoTime(); ClientHttpResponse response = null; try { response = execution.execute(request, body); return response; } finally { getTimeBuilder(request, response).register(this.meterRegistry) .record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); urlTemplate.remove(); } }
@Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = getHttpStatusCode(response); switch (statusCode.series()) { case CLIENT_ERROR: throw new WxApiResponseException(new String(getResponseBody(response), StandardCharsets.UTF_8), response, statusCode); case SERVER_ERROR: throw new WxApiResponseException(new String(getResponseBody(response), StandardCharsets.UTF_8), response, statusCode); default: throw new WxApiResultException(new String(getResponseBody(response), StandardCharsets.UTF_8)); } }
@Override public Iterable<Tag> getTags(String urlTemplate, HttpRequest request, ClientHttpResponse response) { Tag uriTag = StringUtils.hasText(urlTemplate) ? RestTemplateExchangeTags.uri(urlTemplate) : RestTemplateExchangeTags.uri(request); return Arrays.asList(RestTemplateExchangeTags.method(request), uriTag, RestTemplateExchangeTags.status(response), RestTemplateExchangeTags.clientName(request)); }
private static String getStatusMessage(ClientHttpResponse response) { try { if (response == null) { return "CLIENT_ERROR"; } return String.valueOf(response.getRawStatusCode()); } catch (IOException ex) { return "IO_ERROR"; } }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { OAuth2ClientContext clientContext = applicationContext.getBean(OAuth2ClientContext.class); OAuth2AccessToken accessToken = clientContext.getAccessToken(); request.getHeaders().set("Authorization", "Bearer " + accessToken.getValue()); request.getHeaders().set("nonce", keyPairManager.getSignedContent(UUID.randomUUID().toString())); return execution.execute(request, body); }
protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() { return new ResponseExtractor<ResponseEntity<Void>>() { public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException { return new ResponseEntity(response.getHeaders(), response.getStatusCode()); } }; }
protected OAuth2AccessToken retrieveToken(final AccessTokenRequest request, OAuth2ProtectedResourceDetails resource, MultiValueMap<String, String> form, HttpHeaders headers) throws OAuth2AccessDeniedException { try { this.authenticationHandler.authenticateTokenRequest(resource, form, headers); this.tokenRequestEnhancer.enhance(request, resource, form, headers); final ResponseExtractor<OAuth2AccessToken> delegate = this.getResponseExtractor(); ResponseExtractor<OAuth2AccessToken> extractor = new ResponseExtractor<OAuth2AccessToken>() { public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException { if(response.getHeaders().containsKey("Set-Cookie")) { request.setCookie(response.getHeaders().getFirst("Set-Cookie")); } return (OAuth2AccessToken)delegate.extractData(response); } }; System.out.println("URI == " + this.getAccessTokenUri(resource, form)); return (OAuth2AccessToken)this.getRestTemplate().execute(this.getAccessTokenUri(resource, form), this.getHttpMethod(), this.getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap()); } catch (OAuth2Exception var8) { System.out.println(var8.toString()); throw new OAuth2AccessDeniedException("Access token denied.", resource, var8); } catch (RestClientException var9) { System.out.println(var9.toString()); throw new OAuth2AccessDeniedException("Error requesting access token.", resource, var9); } }
/** * @param response * @return le charset du header */ private static Charset getCharset(ClientHttpResponse response) { HttpHeaders headers = response.getHeaders(); MediaType contentType = headers.getContentType(); Charset charset = contentType != null ? contentType.getCharset() : null; if (charset == null){ charset = Charset.forName(ConstanteUtils.WS_APOGEE_DEFAULT_CHARSET); } return charset; }
@Override public void handleError(ClientHttpResponse response) throws IOException { try{ String jsonInString = IOUtils.toString(response.getBody(), getCharset(response)); SiScolRestException erreur = new ObjectMapper().readValue(jsonInString, SiScolRestException.class); throw erreur; }catch(SiScolRestException e){ throw e; }catch (Exception ex){} errorHandler.handleError(response); }
@Override public void handleError(ClientHttpResponse clienthttpresponse) throws IOException { if (clienthttpresponse.getStatusCode() == HttpStatus.FORBIDDEN) { Logger.debug(this, HttpStatus.FORBIDDEN + " response. Throwing authentication exception"); // throw new AuthenticationException(); } }
@Override public boolean hasError(ClientHttpResponse clienthttpresponse) throws IOException { if (clienthttpresponse.getStatusCode() != HttpStatus.OK) { String content = IOUtils.toString(clienthttpresponse.getBody(), "UTF-8"); // The server has successfully fulfilled the request and that there is no additional content to send in the response payload body. if(clienthttpresponse.getStatusCode() == HttpStatus.NO_CONTENT) { return false; } // JSON String to RestError try { // REST Error ObjectMapper mapper = new ObjectMapper(); RestError restError = mapper.readValue(content, RestError.class); // Add HTTP Status Code to Error if (restError.getStatus() == null) { restError.setStatus(clienthttpresponse.getStatusCode().ordinal()); } throw new RestException(restError); } catch (RestException restException) { // Rethrow throw restException; } catch (Exception ex) { // No REST Error Logger.trace(this, "Status code: " + clienthttpresponse.getStatusCode()); Logger.trace(this, "Response" + clienthttpresponse.getStatusText()); Logger.trace(this, "Content: " + content); if (clienthttpresponse.getStatusCode() == HttpStatus.FORBIDDEN) { if (content.contains("used Cloudflare to restrict access")) { Logger.warn(this, "Your current ip is banned by cloudflare, so you can't reach the target."); } else { Logger.debug(this, "Call returned a error 403 forbidden resposne "); } return true; } } } return false; }
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpRequestDecorator httpRequest = new HttpRequestDecorator(request); if(name != null && value != null) { httpRequest.addParameter(name, value); } return execution.execute(httpRequest, body); }
private void getOrCreateWorkflowAndAddInteraction(Pact pact, ClientHttpRequest clientRequest, ClientHttpResponse response) throws IOException { String bodyString = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()); response.getBody().reset(); Pact.Interaction interaction = new Pact.Interaction( null, new Pact.InteractionRequest(restRequestDescriptor.getMethod(), urlencode(restRequestDescriptor.getUrl()), clientRequest.getHeaders(), extractBodyContent(restRequestDescriptor.getRequest())), new Pact.InteractionResponse(response.getRawStatusCode(), response.getHeaders(), bodyString, schema), objectConverter); Pact.Workflow workflow = pact.getWorkflow(this.workflowId, this.providerStates); workflow.addInteraction(interaction); }
/** * Execute the given method on the provided URI. * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback}; * the response with the {@link ResponseExtractor}. * @param url the fully-expanded URL to connect to * @param method the HTTP method to execute (GET, POST, etc.) * @param requestCallback object that prepares the request (can be {@code null}) * @param responseExtractor object that extracts the return value from the response (can be {@code null}) * @return an arbitrary object, as returned by the {@link ResponseExtractor} */ protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { Assert.notNull(url, "'url' must not be null"); Assert.notNull(method, "'method' must not be null"); ClientHttpResponse response = null; try { ClientHttpRequest request = createRequest(url, method); if (requestCallback != null) { requestCallback.doWithRequest(request); } response = request.execute(); if (!getErrorHandler().hasError(response)) { logResponseStatus(method, url, response); } else { handleResponseError(method, url, response); } if (responseExtractor != null) { return responseExtractor.extractData(response); } else { return null; } } catch (IOException ex) { throw new ResourceAccessException("I/O error on " + method.name() + " request for \"" + url + "\":" + ex.getMessage(), ex); } finally { if (response != null) { response.close(); } } }
private void logResponseStatus(HttpMethod method, URI url, ClientHttpResponse response) { if (logger.isDebugEnabled()) { try { logger.debug(method.name() + " request for \"" + url + "\" resulted in " + response.getStatusCode() + " (" + response.getStatusText() + ")"); } catch (IOException e) { // ignore } } }
private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse response) throws IOException { if (logger.isWarnEnabled()) { try { logger.warn(method.name() + " request for \"" + url + "\" resulted in " + response.getStatusCode() + " (" + response.getStatusText() + "); invoking error handler"); } catch (IOException e) { // ignore } } getErrorHandler().handleError(response); }
protected byte[] getResponseBody(ClientHttpResponse response) { try { InputStream responseBody = response.getBody(); if (responseBody != null) { return FileCopyUtils.copyToByteArray(responseBody); } } catch (IOException ex) { // ignore } return new byte[0]; }
@Override public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); headers.add("X-Auth-Token", tokenManager.getTokenHolder().getUnscoped()); if (LOG.isInfoEnabled()) { LOG.info("X-Auth-Token: " + tokenManager.getTokenHolder().getUnscoped()); } return execution.execute(request, body); }
private void logResponseStatus(HttpMethod method, URI url, ClientHttpResponse response) { if (logger.isDebugEnabled()) { try { logger.debug("Async " + method.name() + " request for \"" + url + "\" resulted in " + response.getStatusCode() + " (" + response.getStatusText() + ")"); } catch (IOException ex) { // ignore } } }