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); } }
@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); }
@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)); }
@Test public void testNormal(@Mocked RequestCallback callback) throws IOException { CseClientHttpRequest request = new CseClientHttpRequest(); CseRequestCallback cb = new CseRequestCallback(null, callback); cb.doWithRequest(request); Assert.assertEquals(null, request.getContext()); }
@Test public void testCseEntity(@Injectable CseHttpEntity<?> entity, @Mocked RequestCallback callback) throws IOException { CseClientHttpRequest request = new CseClientHttpRequest(); entity.addContext("c1", "c2"); CseRequestCallback cb = new CseRequestCallback(entity, callback); cb.doWithRequest(request); Assert.assertEquals(entity.getContext(), request.getContext()); }
@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); }
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; }
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); } }
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"); } }
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 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)); }
@Test public void testGetForObjectReturnsEmptyList() throws Exception { JsonNode mockResponse = new ObjectMapper().readTree("{\"apiVersion\":\"1.0\",\"data\":{\"items\":[]}}"); 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, nullValue()); verify(mockRestTemplate).execute(eq(uri), eq(HttpMethod.GET), any(RequestCallback.class), any(ResponseExtractor.class)); }
@Test public void testGetForList() 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); List<Foo> items = t.getForList(Foo.class, "/vpr/34/find/foo"); assertThat(items.size(), equalTo(2)); assertThat(items.get(0).getBar(), is("fred")); assertThat(items.get(0).isBaz(), is(true)); assertThat(items.get(1).getBar(), is("wilma")); assertThat(items.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 public void run() { RequestCallback requestCallback = new NoOpRequestCallback(); ResponseExtractor<?> responseExtractor = new EventResponseExtractor(); while (true) { try { restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor); } catch (Exception e) { logger.warn("Exception while reading event stream.", e); } } }
/** * Generates an SDK for the specified target platform from the SDK profile . * * @param sdkProfileId the sdk profile id * @param targetPlatform the target platform */ public void downloadSdk(String sdkProfileId, SdkPlatform targetPlatform, String destination) { FileResponseExtractor extractor = new FileResponseExtractor(new File(destination)); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("sdkProfileId", sdkProfileId); parameters.add("targetPlatform", targetPlatform.toString()); RequestCallback request = new DataRequestCallback<>(parameters); restTemplate.execute(restTemplate.getUrl() + "sdk", HttpMethod.POST, request, extractor); }
/** * Generates an SDK for the specified target platform from specified SDK profile. * * @param sdkProfileId the sdk profile id * @param targetPlatform the target platform */ public FileData downloadSdk(String sdkProfileId, SdkPlatform targetPlatform) { FileDataResponseExtractor extractor = new FileDataResponseExtractor(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("sdkProfileId", sdkProfileId); parameters.add("targetPlatform", targetPlatform.toString()); RequestCallback request = new DataRequestCallback<>(parameters); return restTemplate.execute(restTemplate.getUrl() + "sdk", HttpMethod.POST, request, extractor); }
/** * Generates a new SDK from specified SDK profile. */ public void downloadSdk(SdkProfileDto key, String destination) throws Exception { FileResponseExtractor extractor = new FileResponseExtractor(new File(destination)); RequestCallback request = new DataRequestCallback<>(key); restTemplate.execute(restTemplate.getUrl() + "sdk", HttpMethod.POST, request, extractor); LOG.info("Downloaded sdk to file '{}'", extractor.getDestFile()); }
/** * Generates a new SDK from specified SDK profile. */ public FileData downloadSdk(SdkProfileDto key) throws Exception { FileDataResponseExtractor extractor = new FileDataResponseExtractor(); RequestCallback request = new DataRequestCallback<>(key); FileData data = restTemplate.execute(restTemplate.getUrl() + "sdk", HttpMethod.POST, request, extractor); return data; }
/** * Generate log library by record key. * * @param key the record key */ public FileData downloadLogRecordLibrary(RecordKey key) throws Exception { FileDataResponseExtractor extractor = new FileDataResponseExtractor(); RequestCallback request = new DataRequestCallback<>(key); FileData data = restTemplate.execute(restTemplate.getUrl() + "logLibrary", HttpMethod.POST, request, extractor); return data; }
/** * Get log record schema with header and log schema inside by record key. * * @param key the record key */ public FileData downloadLogRecordSchema(RecordKey key) throws Exception { FileDataResponseExtractor extractor = new FileDataResponseExtractor(); RequestCallback request = new DataRequestCallback<>(key); FileData data = restTemplate.execute(restTemplate.getUrl() + "logRecordSchema", HttpMethod.POST, request, extractor); return data; }
/** * Exports a CTL schema and all of its dependencies depending on the export method specified. */ public FileData downloadCtlSchemaByAppToken(CTLSchemaDto ctlSchemaDto, CTLSchemaExportMethod method, String appToken) { final FileDataResponseExtractor extractor = new FileDataResponseExtractor(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("fqn", ctlSchemaDto.getMetaInfo().getFqn()); parameters.add("version", Integer.toString(ctlSchemaDto.getVersion())); if (ctlSchemaDto.getMetaInfo().getApplicationId() != null) { parameters.add("applicationToken", appToken); } parameters.add("method", method.name()); RequestCallback request = new DataRequestCallback<>(parameters); return restTemplate.execute(restTemplate.getUrl() + "CTL/exportSchema", HttpMethod.POST, request, extractor); }