private static void loginAndSaveJsessionIdCookie(final String user, final String password, final HttpHeaders headersToUpdate) { String url = "http://localhost:" + port + "/"; new RestTemplate().execute(url, HttpMethod.POST, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest request) throws IOException { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("username", user); map.add("password", password); new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request); } }, new ResponseExtractor<Object>() { @Override public Object extractData(ClientHttpResponse response) throws IOException { headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie")); return null; } }); }
@Test public void executeWithUnderlyingRestTemplate() { RequestCallback requestCallback = clientHttpRequest -> { }; ResponseExtractor<ResponseEntity<String>> responseExtractor = clientHttpResponse -> responseEntity; ResponseEntity<String> actual; for (HttpMethod method : httpMethods) { when(underlying.execute(url, method, requestCallback, responseExtractor, param1, param2)) .thenReturn(responseEntity); actual = wrapper.execute(url, method, requestCallback, responseExtractor, param1, param2); assertThat(actual, is(responseEntity)); verify(underlying).execute(url, method, requestCallback, responseExtractor, param1, param2); when(underlying.execute(url, method, requestCallback, responseExtractor, paramsMap)).thenReturn(responseEntity); actual = wrapper.execute(url, method, requestCallback, responseExtractor, paramsMap); assertThat(actual, is(responseEntity)); verify(underlying).execute(url, method, requestCallback, responseExtractor, paramsMap); when(underlying.execute(uri, method, requestCallback, responseExtractor)).thenReturn(responseEntity); actual = wrapper.execute(uri, method, requestCallback, responseExtractor); assertThat(actual, is(responseEntity)); verify(underlying).execute(uri, method, requestCallback, responseExtractor); } }
@SuppressWarnings("unchecked") private <E> Optional<E> readResponse(ResponseType<E> type) { final Type responseType = type.getType(); try { // check InputStream if (InputStream.class == responseType) { return (Optional<E>) Optional.ofNullable(response.getBody().getInputStream()); } if (Void.class != responseType) { ResponseExtractor<E> extractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters()); return Optional.ofNullable(extractor.extractData(httpResponse)); } } catch (Exception e) { throw new HttpEntityProcessingException("Failed to read HTTP entity as [" + type + "]", e); } return Optional.empty(); }
@Override @Nullable protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback, @Nullable ResponseExtractor<T> responseExtractor) throws RestClientException { String from = name; String to = url. toString(). replace("http://", ""). replace("http:// www.", ""). replace("www.", ""). replace("/", "%20"). toLowerCase(); System.out.println(from); System.out.println(to); try { restTemplate.postForObject("http://trace-callback-service/" + from + "/" + to, null, Object.class); } catch (Exception exception) { } return super.doExecute(url, method, requestCallback, responseExtractor); }
private final Observable<File> getGzip(Consumer<UriComponentsBuilder> builderCallback) { // For responses that have a Content-Type of application/x-gzip, we need to // decompress them. The RestTemplate and HttpClient don't handle this for // us return createObservable(() -> { UriComponentsBuilder builder = UriComponentsBuilder.fromUri(this.root); builderCallback.accept(builder); URI uri = builder.build().toUri(); return this.restOperations.execute(uri, HttpMethod.GET, null, new ResponseExtractor<File>() { @Override public File extractData(ClientHttpResponse response) throws IOException { return decompress(response.getBody()); } }); }); }
@Test public void testGetForJsonCWithConcreteItemType() throws Exception { JsonNode mockResponse = new ObjectMapper().readTree("{\"apiVersion\":\"2.3\",\"data\":{\"items\":[{\"bar\":\"fred\",\"baz\":true},{\"bar\":\"wilma\",\"baz\":false}]}}"); when(mockRestTemplate.execute(eq(URI.create(JDS_URL + "/vpr/34/find/foo")), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class))).thenReturn(mockResponse); JsonCCollection<Foo> r = t.getForJsonC(Foo.class, "/vpr/34/find/foo"); assertThat(r.apiVersion, is("2.3")); assertThat(r.getItems().size(), equalTo(2)); assertThat(r.getItems().get(0).getBar(), is("fred")); assertThat(r.getItems().get(0).isBaz(), is(true)); assertThat(r.getItems().get(1).getBar(), is("wilma")); assertThat(r.getItems().get(1).isBaz(), is(false)); verify(mockRestTemplate).execute(eq(URI.create(JDS_URL + "/vpr/34/find/foo")), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class)); }
@Override protected ResponseExtractor<OAuth2AccessToken> getResponseExtractor() { return new ResponseExtractor<OAuth2AccessToken>() { @Override public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException { JsonNode node = new ObjectMapper().readTree(response.getBody()); String token = Preconditions .checkNotNull(node.path("AccessToken").textValue(), "Missing access token: %s", node); String refreshToken = Preconditions .checkNotNull(node.path("RefreshToken").textValue(), "Missing refresh token: %s" + node); String userId = Preconditions.checkNotNull(node.path("UserID").textValue(), "Missing UserID: %s", node); long expiresIn = node.path("Expires").longValue() * 1000; Preconditions.checkArgument(expiresIn > 0, "Missing Expires: %s", node); DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(token); accessToken.setExpiration(new Date(System.currentTimeMillis() + expiresIn)); accessToken.setRefreshToken(new DefaultOAuth2RefreshToken(refreshToken)); accessToken.setAdditionalInformation(ImmutableMap.<String, Object>of("UserID", userId)); return accessToken; } }; }
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()); }
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); } }
@Override protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { RequestCallbackDecorator requestCallbackDecorator = new RequestCallbackDecorator( requestCallback); return super.doExecute(url, method, requestCallbackDecorator, responseExtractor); }
@Override public void download(String path, File destination) { Assert.hasLength(path, "Path must not be empty"); URI uri = UriComponentsBuilder.fromUriString(this.uri).path(this.repositoryName) .path("/" + path).buildAndExpand(NO_VARIABLES).encode().toUri(); ResponseExtractor<Void> responseExtractor = (response) -> { Path fullPath = destination.toPath().resolve(path); Files.createDirectories(fullPath.getParent()); Files.copy(response.getBody(), fullPath); return null; }; this.restTemplate.execute(uri, HttpMethod.GET, null, responseExtractor); }
private Path getForObjectPrivate(String serviceUrl, String tmpFilePath) { final Map singleValueMap = getFilesStreamingOperationsHttpHeaders().toSingleValueMap(); final Path temp = Paths.get(tmpFilePath); RequestCallback requestCallback = (ClientHttpRequest request) -> { request.getHeaders().setAll(singleValueMap); }; ResponseExtractor<Void> responseExtractor = (ClientHttpResponse response) -> { Files.copy(response.getBody(), temp, StandardCopyOption.REPLACE_EXISTING); return null; }; this.execute(serviceUrl, HttpMethod.GET, requestCallback, responseExtractor); return temp; }
@Override protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { try { return super.doExecute(url, method, requestCallback, responseExtractor); } catch (HttpStatusCodeException ex) { throw createExternalHttpRequestException(method, url, ex); } }
@Override public <T> T execute(URI url, HttpMethod method, RequestCallback callback, ResponseExtractor<T> extractor) throws RestClientException { try { extractor.extractData(this.responses.remove()); } catch (Throwable t) { throw new RestClientException("Failed to invoke extractor", t); } return null; }
@Test public void testGetBaiduHomepage() throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(35); for (int i = 0; i < 150; i++) { executorService.execute(() -> { tcHttpxService.getRestTemplate().execute("http://www.baidu.com", HttpMethod.GET, null, (ResponseExtractor<Void>) response -> null); System.out.println(okHttpClient.connectionPool().connectionCount()); }); } executorService.awaitTermination(3000, TimeUnit.MILLISECONDS); }
private ResponseEntity<T> exchange(RequestEntity<?> requestEntity) { Type type = this.responseType; if (type instanceof TypeVariable || type instanceof WildcardType) { type = Object.class; } RequestCallback requestCallback = rest.httpEntityCallback((Object) requestEntity, type); ResponseExtractor<ResponseEntity<T>> responseExtractor = rest .responseEntityExtractor(type); return rest.execute(requestEntity.getUrl(), requestEntity.getMethod(), requestCallback, responseExtractor); }
@Override public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException { LOG.trace("Injecting execute(String, HttpMethod, RequestCallback, ResponseExtractor, Map) method. Applying retry template."); final long start = System.currentTimeMillis(); T t = retryTemplate.execute(retryContext -> super.execute(url, method, requestCallback, responseExtractor, urlVariables)); LOG.info("[API]:" + url + " took\t" + (System.currentTimeMillis() - start) + "ms"); return t; }
@Override public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { LOG.trace("Injecting execute(URI, HttpMethod, RequestCallback, ResponseExtractor) method. Applying retry template."); final long start = System.currentTimeMillis(); T t = retryTemplate.execute(retryContext -> super.execute(url, method, requestCallback, responseExtractor)); LOG.info("[API]:" + url + " took\t" + (System.currentTimeMillis() - start) + "ms"); return t; }
@Override public <T> T execute(String url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException { LOG.trace("Injecting execute(String, HttpMethod, RequestCallback, ResponseExtractor, Object) method. Applying retry template."); final long start = System.currentTimeMillis(); T t = retryTemplate.execute(retryContext -> super.execute(url, method, requestCallback, responseExtractor, urlVariables)); LOG.info("[API]:" + url + " took\t" + (System.currentTimeMillis() - start) + "ms"); return t; }
@Override protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { try { return super.doExecute(url, method, requestCallback, responseExtractor); } catch (Exception e) { log.error("Exception occurred while sending the message to uri [" + url +"]. Exception [" + e.getCause() + "]"); throw new AssertionError(e); } }
@Override protected <T> ListenableFuture<T> doExecute(URI url, HttpMethod method, AsyncRequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { try { return super.doExecute(url, method, requestCallback, responseExtractor); } finally { finish(); } }
private void readStream(RestTemplate restTemplate) { restTemplate.execute(buildUri(), HttpMethod.GET, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest request) throws IOException { } }, new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse response) throws IOException { InputStream inputStream = response.getBody(); LineNumberReader reader = null; try { reader = new LineNumberReader(new InputStreamReader(inputStream)); resetBackOffs(); while (running.get()) { String line = reader.readLine(); if (!StringUtils.hasText(line)) { break; } doSendLine(line); } } finally { if (reader != null) { reader.close(); } } return null; } } ); }
@SuppressWarnings("unchecked") @Bean public TwitterTemplate twitterTemplate() { TwitterTemplate mockTemplate = mock(TwitterTemplate.class); RestTemplate restTemplate = mock(RestTemplate.class); final ClientHttpResponse response = mock(ClientHttpResponse.class); ByteArrayInputStream bais = new ByteArrayInputStream("foo".getBytes()); try { when(response.getBody()).thenReturn(bais); } catch (IOException e) { } doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { uri().set(invocation.getArgumentAt(0, URI.class)); ResponseExtractor<?> extractor = invocation.getArgumentAt(3, ResponseExtractor.class); extractor.extractData(response); return null; } }).when(restTemplate).execute(any(URI.class), any(HttpMethod.class), any(RequestCallback.class), any(ResponseExtractor.class)); when(mockTemplate.getRestTemplate()).thenReturn(restTemplate); return mockTemplate; }
@SuppressWarnings("unchecked") @Bean @ConditionalOnClass(TwitterTemplate.class) public TwitterTemplate twitterTemplate() { TwitterTemplate mockTemplate = mock(TwitterTemplate.class); RestTemplate restTemplate = mock(RestTemplate.class); final ClientHttpResponse response = mock(ClientHttpResponse.class); ByteArrayInputStream bais = new ByteArrayInputStream("foo".getBytes()); try { when(response.getBody()).thenReturn(bais); } catch (IOException e) { } doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { ResponseExtractor<?> extractor = invocation.getArgumentAt(3, ResponseExtractor.class); extractor.extractData(response); return null; } }).when(restTemplate).execute(any(URI.class), any(HttpMethod.class), any(RequestCallback.class), any(ResponseExtractor.class)); when(mockTemplate.getRestTemplate()).thenReturn(restTemplate); return mockTemplate; }
/** Put for Entity. */ private <T> ResponseEntity<T> putForEntity(final String url, final Object request, final Class<T> responseType, final Object... urlVariables) { try { final Class<?> superclass = restTemplate.getClass().getSuperclass(); final Method method = superclass.getDeclaredMethod("httpEntityCallback", Object.class); method.setAccessible(true); final RequestCallback requestCallback = (RequestCallback) method.invoke(superclass.newInstance(), request); ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(responseType); return restTemplate.execute(url, HttpMethod.PUT, requestCallback, responseExtractor, urlVariables); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { throw new IllegalArgumentException("Something went terribly wrong"); } }
/** @see org.springframework.web.client.RestTemplate#responseEntityExtractor(java.lang.reflect.Type). */ private <T> ResponseExtractor<ResponseEntity<T>> responseEntityExtractor(final Type responseType) { try { final Class<?> superclass = restTemplate.getClass().getSuperclass(); final Method method = superclass.getDeclaredMethod("responseEntityExtractor", Type.class); method.setAccessible(true); return (ResponseExtractor<ResponseEntity<T>>) method.invoke(superclass.newInstance(), responseType); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { throw new IllegalArgumentException("Something went terribly wrong"); } }
public <T> CompletableFuture<T> execute(String url, HttpMethod method, AsyncRequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Object... urlVariables) throws RestClientException { return toCompletableFuture(template.execute(url, method, requestCallback, responseExtractor, urlVariables)); }
public <T> CompletableFuture<T> execute(String url, HttpMethod method, AsyncRequestCallback requestCallback, ResponseExtractor<T> responseExtractor, Map<String, ?> urlVariables) throws RestClientException { return toCompletableFuture(template.execute(url, method, requestCallback, responseExtractor, urlVariables)); }
protected <T> ResponseEntity<T> doExecute(RequestContextData context) { RequestCallback rc = null; HttpMethod method = context.getHttpMethod(); ResponseExtractor<ResponseEntity<T>> responseExtractor = null; HttpHeaders headers = null; HttpEntity<?> requestEntity = null; if(method==HttpMethod.GET) { // rc = super.acceptHeaderRequestCallback(context.getResponseType()); // responseExtractor = responseEntityExtractor(context.getResponseType()); //根据consumers 设置header,以指定messageConvertor headers = new HttpHeaders(); context.getHeaderCallback().accept(headers); requestEntity = new HttpEntity<>(headers); rc = super.httpEntityCallback(requestEntity, context.getResponseType()); responseExtractor = responseEntityExtractor(context.getResponseType()); }else if(RestUtils.isRequestBodySupportedMethod(method)){ headers = new HttpHeaders(); context.getHeaderCallback().accept(headers); //根据consumers 设置header,以指定messageConvertor // Object requestBody = context.getRequestBodySupplier().get(); Object requestBody = context.getRequestBodySupplier().getRequestBody(context); requestEntity = new HttpEntity<>(requestBody, headers); rc = super.httpEntityCallback(requestEntity, context.getResponseType()); responseExtractor = responseEntityExtractor(context.getResponseType()); }else{ throw new RestClientException("unsupported method: " + method); } if(context.getHeaderCallback()!=null){ rc = wrapRequestCallback(context, rc); } return execute(context.getRequestUrl(), method, rc, responseExtractor, context.getUriVariables()); }
@Override protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { RequestContextData ctx = contextThreadLocal.get(); if(logger.isDebugEnabled()){ logger.debug("rest requestId[{}] : {} - {}", ctx.getRequestId(), method, url); } return super.doExecute(url, method, requestCallback, responseExtractor); }
@Override public void handleError(ClientHttpResponse response) throws IOException { ResponseExtractor<ResponseEntity<Object>> responseExtractor = null; if(extErrorResultType!=null){ responseExtractor = responseEntityExtractor(extErrorResultType); } if (responseExtractor != null) { ResponseEntity<?> errorData = responseExtractor.extractData(response); extErrorHandler.onError(errorData.getBody()); }else{ super.handleError(response); } }
@Override protected <T> T doExecute(URI originalUrl, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { URI uri = this.extractor.zipkinUrl(this.zipkinProperties); URI newUri = resolvedZipkinUri(originalUrl, uri); return super.doExecute(newUri, method, requestCallback, responseExtractor); }
@Test public void testGetForJsonC() throws Exception { JsonNode mockResponse = new ObjectMapper().readTree("{\"apiVersion\":\"4.2\",\"data\":{\"items\":[{\"foo\":\"bar\"}]}}"); when(mockRestTemplate.execute(eq(uri), eq(HttpMethod.GET), (RequestCallback) any(), (ResponseExtractor<Object>) any())).thenReturn(mockResponse); JsonCCollection r = t.getForJsonC("/vpr/34"); assertThat(r.apiVersion, is("4.2")); assertThat(r.getItems().size(), equalTo(1)); verify(mockRestTemplate).execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class)); }
@Test public void testGetForJsonCNotFound() throws Exception { when(mockRestTemplate.execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class))).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); JsonCCollection r = t.getForJsonC("/vpr/34"); assertThat(r, nullValue()); verify(mockRestTemplate).execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class)); }
@Test public void testGetForJsonNode() throws Exception { JsonNode mockResponse = new ObjectMapper().readTree("{\"apiVersion\":\"1.0\",\"data\":{\"items\":[{\"icn\":\"foo\"}]}}"); when(mockRestTemplate.execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class))).thenReturn(mockResponse); JsonNode json = t.getForJsonNode("/vpr/34"); assertThat(json.path("apiVersion").asText(), is("1.0")); verify(mockRestTemplate).execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class)); }
@Test public void testGetForObject() throws Exception { JsonNode mockResponse = new ObjectMapper().readTree("{\"apiVersion\":\"1.0\",\"data\":{\"items\":[{\"icn\":\"foo\"}]}}"); when(mockRestTemplate.execute(eq(uri), eq(HttpMethod.GET), (RequestCallback) any(), (ResponseExtractor<Object>) any())).thenReturn(mockResponse); PatientDemographics pt = t.getForObject(PatientDemographics.class, "/vpr/34"); assertThat(pt.getIcn(), equalTo("foo")); verify(mockRestTemplate).execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class)); }
@Test public void testGetForObjectNotFound() throws Exception { when(mockRestTemplate.execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class))).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); PatientDemographics pt = t.getForObject(PatientDemographics.class, "/vpr/34"); assertThat(pt, nullValue()); verify(mockRestTemplate).execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class)); }