@Test public void accessServiceUsingRestTemplate() { // Access root resource URI uri = URI.create(String.format(SERVICE_URI, port)); RequestEntity<Void> request = RequestEntity.get(uri).accept(HAL_JSON).build(); Resource<Object> rootLinks = restOperations.exchange(request, new ResourceType<Object>() {}).getBody(); Links links = new Links(rootLinks.getLinks()); // Follow stores link Link storesLink = links.getLink("stores").expand(); request = RequestEntity.get(URI.create(storesLink.getHref())).accept(HAL_JSON).build(); Resources<Store> stores = restOperations.exchange(request, new ResourcesType<Store>() {}).getBody(); stores.getContent().forEach(store -> log.info("{} - {}", store.name, store.address)); }
public Map<String, String> getUserInfoFor(OAuth2AccessToken accessToken) { RestTemplate restTemplate = new RestTemplate(); RequestEntity<Void> requestEntity = new RequestEntity<>( getHeader(accessToken.getValue()), HttpMethod.GET, URI.create(properties.getUserInfoUri()) ); ParameterizedTypeReference<Map<String, String>> typeRef = new ParameterizedTypeReference<Map<String, String>>() {}; ResponseEntity<Map<String, String>> result = restTemplate.exchange( requestEntity, typeRef); if (result.getStatusCode().is2xxSuccessful()) { return result.getBody(); } throw new RuntimeException("It wasn't possible to retrieve userInfo"); }
public Map<String, String> getUserInfoFor(OAuth2AccessToken accessToken) { RestTemplate restTemplate = new RestTemplate(); RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>( getHeader(accessToken), HttpMethod.GET, URI.create("https://www.googleapis.com/oauth2/v3/userinfo") ); ResponseEntity<Map> result = restTemplate.exchange( requestEntity, Map.class); if (result.getStatusCode().is2xxSuccessful()) { return result.getBody(); } throw new RuntimeException("It wasn't possible to retrieve userInfo"); }
private void tryToGetUserProfile(ModelAndView mv, String token) { RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("Authorization", "Bearer " + token); String endpoint = "http://localhost:8080/api/profile"; try { RequestEntity<Object> request = new RequestEntity<>( headers, HttpMethod.GET, URI.create(endpoint)); ResponseEntity<UserProfile> userProfile = restTemplate.exchange(request, UserProfile.class); if (userProfile.getStatusCode().is2xxSuccessful()) { mv.addObject("profile", userProfile.getBody()); } else { throw new RuntimeException("it was not possible to retrieve user profile"); } } catch (HttpClientErrorException e) { throw new RuntimeException("it was not possible to retrieve user profile"); } }
public OAuth2Token getToken(String authorizationCode) { RestTemplate rest = new RestTemplate(); String authBase64 = configuration.encodeCredentials("clientapp", "123456"); RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>( configuration.getBody(authorizationCode), configuration.getHeader(authBase64), HttpMethod.POST, URI.create("http://localhost:8080/oauth/token")); ResponseEntity<OAuth2Token> responseEntity = rest.exchange( requestEntity, OAuth2Token.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity.getBody(); } throw new RuntimeException("error trying to retrieve access token"); }
@Test public void testSimple() throws Exception { final Map<String, Object> body = new HashMap<>(); body.put("foo", "Hello, world!"); body.put("bar", 12345); body.put("baz", "2017-02-10"); body.put("qux", Collections.emptyList()); final RequestEntity<Map<String, Object>> requestEntity = RequestEntity .post(new UriTemplate(url).expand(port)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .body(body); final ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() { }; final ResponseEntity<Map<String, Object>> response = restTemplate.exchange(requestEntity, responseType); assertThat(response.getBody(), is(body)); }
@Test public void testPushTaupageLog() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD); stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201))); final URI url = URI.create("http://localhost:" + port + "/instance-logs"); final ResponseEntity<String> response = restOperations.exchange( RequestEntity.post(url).contentType(APPLICATION_JSON).body( instanceLogsPayload), String.class); assertThat(response.getStatusCode()).isEqualTo(CREATED); log.debug("Waiting for async tasks to finish"); TimeUnit.SECONDS.sleep(1); verify(postRequestedFor(urlPathEqualTo("/api/instance-logs")) .withRequestBody(equalToJson(intanceLogsJsonPayload)) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); verify(putRequestedFor(urlPathEqualTo("/events/" + eventID)) .withRequestBody(equalToJson(new String(auditTrailJsonPayload))) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); log.info("METRICS:\n{}", restOperations.getForObject("http://localhost:" + managementPort + "/metrics", String.class)); }
public static void main(String[] args) throws Exception { RestTemplate template = new RestTemplate(); template.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("X-Tenant-Name", "default"); RequestEntity<String> requestEntity = new RequestEntity<String>(headers, HttpMethod.GET, new URI("http://127.0.0.1:9980/registry/v3/microservices")); ResponseEntity<String> stringResponseEntity = template.exchange(requestEntity, String.class); System.out.println(stringResponseEntity.getBody()); ResponseEntity<MicroserviceArray> microseriveResponseEntity = template .exchange(requestEntity, MicroserviceArray.class); MicroserviceArray microserives = microseriveResponseEntity.getBody(); System.out.println(microserives.getServices().get(1).getServiceId()); // instance headers.add("X-ConsumerId", microserives.getServices().get(1).getServiceId()); requestEntity = new RequestEntity<String>(headers, HttpMethod.GET, new URI("http://127.0.0.1:9980/registry/v3/microservices/" + microserives.getServices().get(1).getServiceId() + "/instances")); ResponseEntity<String> microserviceInstanceResponseEntity = template.exchange(requestEntity, String.class); System.out.println(microserviceInstanceResponseEntity.getBody()); }
@Test public void exchangeUsingParameterizedTypeWithUnderlyingRestTemplate() { ParameterizedTypeReference<List<String>> typeReference = new ParameterizedTypeReference<List<String>>() { }; ResponseEntity<List<String>> actual; for (HttpMethod method : httpMethods) { when(underlying.exchange(url, method, requestEntity, typeReference, param1, param2)).thenReturn(typedResponse); actual = wrapper.exchange(url, method, requestEntity, typeReference, param1, param2); assertThat(actual, is(typedResponse)); verify(underlying).exchange(url, method, requestEntity, typeReference, param1, param2); when(underlying.exchange(url, method, requestEntity, typeReference, paramsMap)).thenReturn(typedResponse); actual = wrapper.exchange(url, method, requestEntity, typeReference, paramsMap); assertThat(actual, is(typedResponse)); verify(underlying).exchange(url, method, requestEntity, typeReference, paramsMap); when(underlying.exchange(uri, method, requestEntity, typeReference)).thenReturn(typedResponse); actual = wrapper.exchange(uri, method, requestEntity, typeReference); assertThat(actual, is(typedResponse)); verify(underlying).exchange(uri, method, requestEntity, typeReference); RequestEntity<String> request = new RequestEntity<>(method, uri); when(underlying.exchange(request, typeReference)).thenReturn(typedResponse); actual = wrapper.exchange(request, typeReference); assertThat(actual, is(typedResponse)); verify(underlying).exchange(request, typeReference); } }
/** * Invoke API by sending HTTP request with the given options. * * @param <T> the return type to use * @param path The sub-path of the HTTP URL * @param method The request method * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters * @param formParams The form parameters * @param accept The request's Accept header * @param contentType The request's Content-Type header * @param authNames The authentications to apply * @param returnType The return type into which to deserialize the response * @return The response body in chosen type */ public <T> T invokeAPI(String path, HttpMethod method, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException { updateParamsForAuth(authNames, queryParams, headerParams); final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path); if (queryParams != null) { builder.queryParams(queryParams); } final BodyBuilder requestBuilder = RequestEntity.method(method, builder.build().toUri()); if(accept != null) { requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); } if(contentType != null) { requestBuilder.contentType(contentType); } addHeadersToRequest(headerParams, requestBuilder); addHeadersToRequest(defaultHeaders, requestBuilder); RequestEntity<Object> requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); ResponseEntity<T> responseEntity = restTemplate.exchange(requestEntity, returnType); statusCode = responseEntity.getStatusCode(); responseHeaders = responseEntity.getHeaders(); if (responseEntity.getStatusCode() == HttpStatus.NO_CONTENT) { return null; } else if (responseEntity.getStatusCode().is2xxSuccessful()) { if (returnType == null) { return null; } return responseEntity.getBody(); } else { // The error handler built into the RestTemplate should handle 400 and 500 series errors. throw new RestClientException("API returned " + statusCode + " and it wasn't handled by the RestTemplate error handler"); } }
@PostMapping(value= {"/{dicId}/entries", "/{dicId}/entries/{fieldId}"}) public String saveEntry(@PathVariable("dicId") Long dicId , RequestEntity<DictionaryEntry> data , Map<String, Object> model) { Dictionary dictionaryEntity = null; DictionaryEntry entry = data.getBody(); if (entry.getId() != null) { dictionaryEntity = this.dictionaryService.updateEntry(dicId, entry); } else { dictionaryEntity = this.dictionaryService.addEntry(dicId, entry); } model.put("dictionaryEntity", dictionaryEntity); return "tool/dictionary_entries"; }
@PostMapping(value = "/") public ResponseEntity<Tables> save(RequestEntity<Tables> data) { Tables tableEntity = null; if (data.getBody().getId() != null) { tableEntity = this.tableService.update(data.getBody()); } else { tableEntity = this.tableService.save(data.getBody()); } return ResponseEntity.accepted().body(tableEntity); }
@PostMapping(value= {"/{tableId}/fields", "/{tableId}/fields/{fieldId}"}) public String saveField(@PathVariable("tableId") Long tableId , RequestEntity<TableField> data , Map<String, Object> model) { Tables tableEntity = null; TableField field = data.getBody(); if (field.getId() != null) { tableEntity = this.tableService.updateField(tableId, field); } else { tableEntity = this.tableService.addField(tableId, field); } model.put("tableEntity", tableEntity); return "tool/table_fields"; }
@Override public Project updateRelease(String projectName, List<ReleaseUpdate> releaseUpdates) { RequestEntity<List<ReleaseUpdate>> request = RequestEntity .put(URI.create(this.baseUrl +"/project_metadata/" + projectName + "/releases")) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE) .body(releaseUpdates); ResponseEntity<Project> entity = this.restTemplate .exchange(request, Project.class); Project project = entity.getBody(); log.info("Response from Sagan\n\n[{}] \n with body [{}]", entity, project); return project; }
public void delete(T taskId) { RequestEntity<Object> request = new RequestEntity<>(HttpMethod.DELETE, taskUrl(taskId)); ResponseEntity<Object> response = httpClient.exchange(request, Object.class); assert204(response); }
@Test public void testNest() throws Exception { final Map<String, Object> grandchild = new HashMap<>(); grandchild.put("foo", "grandchild"); grandchild.put("bar", 1); grandchild.put("baz", "2017-02-01"); grandchild.put("qux", Collections.emptyList()); final Map<String, Object> child1 = new HashMap<>(); child1.put("foo", "child1"); child1.put("bar", 2); child1.put("baz", "2017-02-02"); child1.put("qux", Collections.singletonList(grandchild)); final Map<String, Object> child2 = new HashMap<>(); child2.put("foo", "child2"); child2.put("bar", 3); child2.put("baz", "2017-02-03"); child2.put("qux", Collections.emptyList()); final Map<String, Object> root = new HashMap<>(); root.put("foo", "root"); root.put("bar", 4); root.put("baz", "2017-02-04"); root.put("qux", Arrays.asList(child1, child2)); final RequestEntity<Map<String, Object>> requestEntity = RequestEntity .post(new UriTemplate(url).expand(port)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .body(root); final ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() { }; final ResponseEntity<Map<String, Object>> response = restTemplate.exchange(requestEntity, responseType); assertThat(response.getBody(), is(root)); }
private ResponseEntity<Map<String, Object>> doRequest(final Map<String, Object> body) { final RequestEntity<Map<String, Object>> requestEntity = RequestEntity .post(new UriTemplate(url).expand(port)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .body(body); final ParameterizedTypeReference<Map<String, Object>> responseType = new ParameterizedTypeReference<Map<String, Object>>() { }; return restTemplate.exchange(requestEntity, responseType); }
private void add(BuildInfo buildInfo) { URI uri = UriComponentsBuilder.fromUriString(this.uri).path("api/build") .buildAndExpand(NO_VARIABLES).encode().toUri(); RequestEntity<BuildInfo> request = RequestEntity.put(uri) .contentType(MediaType.APPLICATION_JSON).body(buildInfo); ResponseEntity<Void> exchange = this.restTemplate.exchange(request, Void.class); exchange.getBody(); }
@Override public List<DeployedArtifact> getDeployedArtifacts(String buildNumber) { Assert.notNull(buildNumber, "Build number must not be null"); URI uri = UriComponentsBuilder.fromUriString(this.uri).path("/api/search/aql") .buildAndExpand(NO_VARIABLES).encode().toUri(); RequestEntity<String> request = RequestEntity.post(uri) .contentType(MediaType.TEXT_PLAIN) .body(buildFetchQuery(this.buildName, buildNumber)); return this.restTemplate.exchange(request, DeployedArtifactQueryResponse.class) .getBody().getResults(); }
@Test public void testCors() throws Exception { String origin = "http://openmrs.org/news"; ResponseEntity<String> entity = testRestTemplate.exchange(RequestEntity.get( uri("http://localhost:" + port + "/api/v1/addon?q=report")) .header(HttpHeaders.ORIGIN, origin).build(), String.class); assertThat(entity.getHeaders().getAccessControlAllowOrigin(), is(origin)); }
@Test public void helloShouldBeProtected() throws Exception { final RequestEntity<Void> hello = get(URI.create("/hello")).accept(MediaType.APPLICATION_JSON).build(); assertThat(restTemplate.exchange(hello, String.class).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(restTemplate.withBasicAuth("user", "something").exchange(hello, String.class).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); assertThat(restTemplate.withBasicAuth("peter", "parker").exchange(hello, String.class).getBody()).isEqualTo("Hello, peter\n"); }
@SuppressWarnings("rawtypes") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @RequestMapping(value = "/{pluginToken}/**") @ResponseStatus(value = HttpStatus.OK) public DeferredResult<ResponseEntity> processRequest( @PathVariable("pluginToken") String pluginToken, RequestEntity<byte[]> requestEntity, HttpServletRequest request) throws IoTPException { log.debug("[{}] Going to process requst uri: {}", pluginToken, requestEntity.getUrl()); DeferredResult<ResponseEntity> result = new DeferredResult<ResponseEntity>(); PluginMetaData pluginMd = pluginService.findPluginByApiToken(pluginToken); if (pluginMd == null) { result.setErrorResult(new PluginNotFoundException("Plugin with token: " + pluginToken + " not found!")); } else { TenantId tenantId = getCurrentUser().getTenantId(); CustomerId customerId = getCurrentUser().getCustomerId(); if (validatePluginAccess(pluginMd, tenantId, customerId)) { if(ModelConstants.NULL_UUID.equals(tenantId.getId())){ tenantId = null; } PluginApiCallSecurityContext securityCtx = new PluginApiCallSecurityContext(pluginMd.getTenantId(), pluginMd.getId(), tenantId, customerId); actorService.process(new BasicPluginRestMsg(securityCtx, new RestRequest(requestEntity, request), result)); } else { result.setResult(new ResponseEntity<>(HttpStatus.FORBIDDEN)); } } return result; }
@Test public void testPushTaupageLogWithRetry() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD); stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201).withFixedDelay(100))); stubFor(put(urlEqualTo("/events/" + eventID)).willReturn(aResponse().withStatus(429).withFixedDelay(100))); final URI url = URI.create("http://localhost:" + port + "/instance-logs"); final ResponseEntity<String> response = restOperations.exchange( RequestEntity.post(url).contentType(APPLICATION_JSON).body( instanceLogsPayload), String.class); assertThat(response.getStatusCode()).isEqualTo(CREATED); log.debug("Waiting for async tasks to finish"); TimeUnit.MILLISECONDS.sleep(7500); verify(postRequestedFor(urlPathEqualTo("/api/instance-logs")) .withRequestBody(equalToJson(intanceLogsJsonPayload)) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); verify(3, putRequestedFor(urlPathEqualTo("/events/" + eventID)) .withRequestBody(equalToJson(new String(auditTrailJsonPayload))) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); }
@Test public void testPushStandardLog() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD); stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201))); //change the log type to something different than 'USER_DATA' to avoid sending an audit trail event instanceLogsPayload.put("log_type", "SOMETHING_DIFFERENT"); final URI url = URI.create("http://localhost:" + port + "/instance-logs"); final ResponseEntity<String> response = restOperations.exchange( RequestEntity.post(url).contentType(APPLICATION_JSON).body( instanceLogsPayload), String.class); assertThat(response.getStatusCode()).isEqualTo(CREATED); log.debug("Waiting for async tasks to finish"); TimeUnit.SECONDS.sleep(1); final String standardLogsPayload = objectMapper.writeValueAsString(instanceLogsPayload); verify(postRequestedFor(urlPathEqualTo("/api/instance-logs")) .withRequestBody(equalToJson(standardLogsPayload)) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); verify(0, putRequestedFor(urlPathMatching("/events/.*"))); }
@Test public void testPushLogsUnauthenticated() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(); stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201))); final URI url = URI.create("http://localhost:" + port + "/instance-logs"); final ResponseEntity<String> response = restOperations.exchange( RequestEntity.post(url).contentType(APPLICATION_JSON).body( instanceLogsPayload), String.class); assertThat(response.getStatusCode()).isEqualTo(UNAUTHORIZED); }
@Test public void testPushLogsWrongPassword() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, "wrong-password"); stubFor(post(urlPathEqualTo("/api/instance-logs")).willReturn(aResponse().withStatus(201))); final URI url = URI.create("http://localhost:" + port + "/instance-logs"); final ResponseEntity<String> response = restOperations.exchange( RequestEntity.post(url).contentType(APPLICATION_JSON).body( instanceLogsPayload), String.class); assertThat(response.getStatusCode()).isEqualTo(UNAUTHORIZED); }
@Test public void testPushLogsUpstreamFailsOnce() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(CORRECT_USER, CORRECT_PASSWORD); // first calls fails stubFor(post(urlPathEqualTo("/api/instance-logs")).inScenario("Test Retry") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500)) .willSetStateTo("retry")); // second one succeeds stubFor(post(urlPathEqualTo("/api/instance-logs")).inScenario("Test Retry") .whenScenarioStateIs("retry") .willReturn(aResponse().withStatus(201))); final URI url = URI.create("http://localhost:" + port + "/instance-logs"); final ResponseEntity<String> response = restOperations.exchange( RequestEntity.post(url).contentType(APPLICATION_JSON).body( instanceLogsPayload), String.class); // even if upstream request fails, due to async processing this endpoint should return a success message assertThat(response.getStatusCode()).isEqualTo(CREATED); log.debug("Waiting for async tasks to finish"); TimeUnit.SECONDS.sleep(2); // endpoint should have been called twice verify(2, postRequestedFor(urlPathEqualTo("/api/instance-logs")) .withRequestBody(equalToJson(intanceLogsJsonPayload)) .withHeader(AUTHORIZATION, equalTo("Bearer 1234567890"))); }
@Test public void testInvokeRootEndpoint() throws Exception { final TestRestTemplate restOperations = new TestRestTemplate(); final URI url = URI.create("http://localhost:" + port); final ResponseEntity<String> response = restOperations.exchange(RequestEntity.get(url).build(), String.class); assertThat(response.getStatusCode()).isEqualTo(UNAUTHORIZED); }
@Test public void foos() throws Exception { ResponseEntity<String> result = rest .exchange(RequestEntity.get(new URI("/foos")).build(), String.class); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getBody()) .isEqualTo("[{\"value\":\"foo\"},{\"value\":\"bar\"}]"); }
@Test public void postMore() throws Exception { ResponseEntity<String> result = rest.exchange(RequestEntity .post(new URI("/post/more")).contentType(MediaType.APPLICATION_JSON) .body("[\"foo\",\"bar\"]"), String.class); assertThat(result.getBody()).isEqualTo("[\"(FOO)\",\"(BAR)\"]"); }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws IOException, HttpMediaTypeNotSupportedException { ServletServerHttpRequest inputMessage = createInputMessage(webRequest); Type paramType = getHttpEntityType(parameter); Object body = readWithMessageConverters(webRequest, parameter, paramType); if (RequestEntity.class == parameter.getParameterType()) { return new RequestEntity<Object>(body, inputMessage.getHeaders(), inputMessage.getMethod(), inputMessage.getURI()); } else { return new HttpEntity<Object>(body, inputMessage.getHeaders()); } }
@SuppressWarnings("unchecked") @Before public void setup() { endpointUri = URI.create("http:/my.api.com/api"); requestEntity = new RequestEntity<>(HttpMethod.GET, endpointUri); when(requestEntityConverterMock.convert(notNull(EndpointRequest.class))) .thenReturn(requestEntity); responseEntity = new ResponseEntity<>("expected result", HttpStatus.OK); when(restOperationsMock.exchange(same(requestEntity), notNull(ParameterizedTypeReference.class))) .thenReturn(responseEntity); when(responseEntityConverterMock.convert(notNull(ResponseEntity.class))) .thenReturn(new EndpointResponse<>(StatusCode.ok(), null, responseEntity.getBody())); }
@RequestMapping(method = RequestMethod.POST, value = "/beer", consumes = MediaType.APPLICATION_JSON_VALUE) public String gimmeABeer(@RequestBody Person person) throws MalformedURLException { //remove::start[] //tag::controller[] ResponseEntity<Response> response = this.restTemplate.exchange( RequestEntity .post(URI.create("http://localhost:" + port + "/check")) .contentType(MediaType.APPLICATION_JSON) .body(person), Response.class); switch (response.getBody().status) { case OK: return "THERE YOU GO"; default: return "GET LOST"; } //end::controller[] //remove::end[return] }
@PostMapping(value = "/grumpy", produces = MediaType.APPLICATION_JSON_VALUE) GrumpyResponse grumpy(@RequestBody GrumpyPerson person) { //remove::start[] //tag::controller[] ResponseEntity<GrumpyBartenderResponse> response = this.restTemplate.exchange( RequestEntity .post(URI.create("http://localhost:" + port + "/buy")) .contentType(MediaType.APPLICATION_JSON) .body(person), GrumpyBartenderResponse.class); switch (response.getBody().status) { case OK: return new GrumpyResponse(response.getBody().message, "Enjoy!"); default: return new GrumpyResponse(response.getBody().message, "Go to another bar"); } //end::controller[] //remove::end[return] }
@RequestMapping(method = RequestMethod.POST, value = "/beer", consumes = MediaType.APPLICATION_JSON_VALUE) public String gimmeABeer(@RequestBody Person person) throws MalformedURLException { //remove::start[] //tag::controller[] ResponseEntity<Response> response = this.restTemplate.exchange( RequestEntity .post(URI.create("http://somenameforproducer/check")) .contentType(MediaType.APPLICATION_JSON) .body(person), Response.class); switch (response.getBody().status) { case OK: return "THERE YOU GO"; default: return "GET LOST"; } //end::controller[] //remove::end[return] }
@RequestMapping(method = RequestMethod.POST, value = "/beer", consumes = MediaType.APPLICATION_JSON_VALUE) public String gimmeABeer(@RequestBody Person person) throws MalformedURLException { //remove::start[] ResponseEntity<Response> response = this.restTemplate.exchange( RequestEntity .post(URI.create("http://localhost:" + this.port + "/check")) .contentType(MediaType.APPLICATION_JSON) .body(person), Response.class); switch (response.getBody().status) { case OK: return "THERE YOU GO"; default: return "GET LOST"; } //remove::end[return] }
@Test @SuppressWarnings("unchecked") public void should_create_a_valid_span_from_custom_headers() { long spanId = this.random.nextLong(); long traceId = this.random.nextLong(); RequestEntity<?> requestEntity = RequestEntity .get(URI.create("http://localhost:" + this.config.port + "/headers")) .header("correlationId", Span.idToHex(traceId)) .header("mySpanId", Span.idToHex(spanId)).build(); @SuppressWarnings("rawtypes") ResponseEntity<Map> requestHeaders = this.restTemplate.exchange(requestEntity, Map.class); then(this.customRestController.span).hasTraceIdEqualTo(traceId); then(requestHeaders.getBody()) .containsEntry("correlationid", Span.idToHex(traceId)) .containsEntry("myspanid", Span.idToHex(spanId)) .as("input request headers"); then(requestHeaders.getHeaders()) .containsEntry("correlationId", Collections.singletonList(Span.idToHex(traceId))) .containsKey("mySpanId").as("response headers"); }
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) { String baseUrl = "http://localhost:" + this.context.getWebServer().getPort(); TestRestTemplate rest = new TestRestTemplate(); // First, verify the web endpoint can't be reached assertEndpointUnauthorized(baseUrl, rest); // Since we can't reach it, need to collect an authorization token HttpHeaders headers = getHeaders(config); String url = baseUrl + "/oauth/token"; JsonNode tokenResponse = rest.postForObject(url, new HttpEntity<>(getBody(), headers), JsonNode.class); String authorizationToken = tokenResponse.findValue("access_token").asText(); String tokenType = tokenResponse.findValue("token_type").asText(); String scope = tokenResponse.findValues("scope").get(0).toString(); assertThat(tokenType).isEqualTo("bearer"); assertThat(scope).isEqualTo("\"read\""); // Now we should be able to see that endpoint. headers.set("Authorization", "BEARER " + authorizationToken); ResponseEntity<String> securedResponse = rest .exchange(new RequestEntity<Void>(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")), String.class); assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(securedResponse.getBody()).isEqualTo( "You reached an endpoint " + "secured by Spring Security OAuth2"); ResponseEntity<String> entity = rest.exchange(new RequestEntity<Void>(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class); assertThat(entity.getStatusCode()).isEqualTo(finalStatus); }
@Test public void exchangeWithUnderlyingRestTemplate() { ResponseEntity<String> actual; for (HttpMethod method : httpMethods) { when(underlying.exchange(url, method, requestEntity, String.class, param1, param2)).thenReturn(responseEntity); actual = wrapper.exchange(url, method, requestEntity, String.class, param1, param2); assertThat(actual, is(responseEntity)); verify(underlying).exchange(url, method, requestEntity, String.class, param1, param2); when(underlying.exchange(url, method, requestEntity, String.class, paramsMap)).thenReturn(responseEntity); actual = wrapper.exchange(url, method, requestEntity, String.class, paramsMap); assertThat(actual, is(responseEntity)); verify(underlying).exchange(url, method, requestEntity, String.class, paramsMap); when(underlying.exchange(uri, method, requestEntity, String.class)).thenReturn(responseEntity); actual = wrapper.exchange(uri, method, requestEntity, String.class); assertThat(actual, is(responseEntity)); verify(underlying).exchange(uri, method, requestEntity, String.class); RequestEntity<String> request = new RequestEntity<>(method, uri); when(underlying.exchange(request, String.class)).thenReturn(responseEntity); actual = wrapper.exchange(request, String.class); assertThat(actual, is(responseEntity)); verify(underlying).exchange(request, String.class); } }