@Test public void should_put_return_406_when_assigned_to_deleted_case() throws Exception { // given ResponseEntity<Void> postResponse = getCreateTreatmentResponse(); URI location = postResponse.getHeaders().getLocation(); String id = RestHelper.extractIdStringFromURI(location); Treatment savedTreatment = treatmentRepository.findOne(Long.parseLong(id)); theCase.setId(104243L); savedTreatment.setRelevantCase(theCase); // when ResponseEntity<Void> putResponse = testRestTemplate .withBasicAuth("1", "1") .exchange("/v1/treatments/" + id, HttpMethod.PUT, new HttpEntity<>(savedTreatment), Void.class); // then assertThat(putResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE); }
/** * Gets the HTTP request entity encapsulating the headers and body of the HTTP message. The body * of the HTTP request message will consist of an URL encoded application form (a mapping of * key-value pairs) for POST/PUT HTTP requests. * <p/> * * @return an HttpEntity with the headers and body for the HTTP request message. * @see #getParameters() * @see org.springframework.http.HttpEntity * @see org.springframework.http.HttpHeaders */ public HttpEntity<?> createRequestEntity() { if (isPost() || isPut()) { // NOTE HTTP request parameters take precedence over HTTP message body content/media if (!getParameters().isEmpty()) { getHeaders().setContentType(determineContentType(MediaType.APPLICATION_FORM_URLENCODED)); return new HttpEntity<MultiValueMap<String, Object>>(getParameters(), getHeaders()); } else { // NOTE the HTTP "Content-Type" header will be determined and set by the appropriate // HttpMessageConverter // based on the Class type of the "content". return new HttpEntity<Object>(getContent(), getHeaders()); } } else { return new HttpEntity<Object>(getHeaders()); } }
@CrossOrigin @RequestMapping(value = "/detectMeaningLanguageSpecific", method = RequestMethod.GET) HttpEntity<Object> detectMeaningLanguageSpecific(@RequestParam("inputAsJson") String inputAsJson) { try { Logger.getAnonymousLogger().log(Level.INFO, "Invoke: detectMeaningLanguageSpecific: " + inputAsJson); Gson gson = new Gson(); InputParameterdetectMeaningLanguageSpecific inputParameterdetectMeaningLanguageSpecific = gson .fromJson(inputAsJson, InputParameterdetectMeaningLanguageSpecific.class); List<Entity> concepts = sparqlDerivation.detectPossibleConceptsLanguageSpecific( inputParameterdetectMeaningLanguageSpecific.getKeyword(), inputParameterdetectMeaningLanguageSpecific.getLanguage()); MeaningResult meaningResult = new MeaningResult(); meaningResult.setConceptOverview(concepts); meaningResult.setSearchTyp("ExplorativeSearch"); Gson output = new Gson(); String result = ""; result = output.toJson(meaningResult); return new ResponseEntity<Object>(result, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
private String saveResultForClass(String sourcedId) { Map<String, String> resultMetadata = Collections.singletonMap(Vocabulary.TENANT, TestData.TENANT_1); Result result = new Result.Builder() .withResultstatus("Grade B") .withScore(70.0) .withComment("not bad") .withMetadata(resultMetadata) .withSourcedId(TestData.RESULT_SOURCED_ID) .withDate(LocalDateTime.now()) .withDateLastModified(LocalDateTime.now()) .withStatus(Status.active) .withLineitem(new Link.Builder().withSourcedId(TestData.LINEITEM_SOURCED_ID).build()) .withStudent(new Link.Builder().withSourcedId(TestData.USER_SOURCED_ID).build()) .build(); HttpHeaders headers1 = getHeaders(); HttpEntity<Object> entity = new HttpEntity<Object>(result, headers1); ResponseEntity<Result> responseEntity = restTemplate.exchange(String.format("/api/classes/%s/results",sourcedId), HttpMethod.POST, entity, Result.class); Result responseResult = responseEntity.getBody(); assertTrue(responseEntity.getStatusCode().is2xxSuccessful()); assertEquals(new Double(70.0), responseResult.getScore()); return responseEntity.getBody().getSourcedId(); }
@HystrixCommand(fallbackMethod = "defaultComments") public List<Comment> getComments(Image image, String sessionId) { ResponseEntity<List<Comment>> results = restTemplate.exchange( "http://COMMENTS/comments/{imageId}", HttpMethod.GET, new HttpEntity<>(new HttpHeaders() {{ String credentials = imagesConfiguration.getCommentsUser() + ":" + imagesConfiguration.getCommentsPassword(); String token = new String(Base64Utils.encode(credentials.getBytes())); set(AUTHORIZATION, "Basic " + token); set("SESSION", sessionId); }}), new ParameterizedTypeReference<List<Comment>>() {}, image.getId()); return results.getBody(); }
public Client build() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); //prepare ROPC request MultiValueMap<String, String> params = new LinkedMultiValueMap(); params.add(CLIENT_ID_PARAM, clientId); params.add(CLIENT_SECRET_PARAM, clientSecret); params.add(GRANT_TYPE_PARAM, "password"); params.add(USERNAME_PARAM, username); params.add(PASSWORD_PARAM, password); RestTemplate template = new RestTemplate(); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity(params, headers); String tokenUrl = String.format("%s/oauth2/v1/token", baseUrl); //obtain access token and return client instance Client client = template .exchange(tokenUrl, HttpMethod.POST, entity, Client.class) .getBody(); client.init(baseUrl); return client; }
public String classify(Tweet tweet) { MultiValueMap<String, String> allArguments= new LinkedMultiValueMap<>(); allArguments.add("Date", tweet.getCreatedAt().toString()); allArguments.add("Tweet_Text", tweet.getText()); allArguments.add("Tweet_Id", tweet.getIdStr()); allArguments.add("User_Id", Long.toString(tweet.getFromUserId())); allArguments.add("User_Name", tweet.getUser().getName()); allArguments.add("User_Screen_Name", tweet.getUser().getScreenName()); allArguments.add("Retweets", Integer.toString(tweet.getRetweetCount())); allArguments.add("Favorites", Integer.toString(tweet.getFavoriteCount())); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(allArguments, headers); ResponseEntity<String> response = restTemplate.postForEntity( requestURL, request , String.class ); return response.getBody(); }
@Test public void thisWeek() throws CalendarReadException { //given final PlainTextOutputSpeech speech = new PlainTextOutputSpeech(); speech.setText("<event-listing>"); List<Event> events = new ArrayList<>(); doReturn(events).when(toTestQuery.calendarService).getEvents(any(), any()); doReturn(speech).when(toTestQuery.speechService).readEvents(any(), anyString(), anyList()); //when HttpEntity<String> request = buildRequest("EventQueryThisWeek"); final SpeechletResponseEnvelope response = perform(request); //then verify(toTestQuery.speechService, times(1)).readEvents( eq(Locale.GERMANY), eq(Moment.THIS_WEEK.getName(Locale.GERMANY)), anyList()); assertNull(response.getResponse().getCard()); assertTrue(response.getResponse().getOutputSpeech() instanceof PlainTextOutputSpeech); assertEquals( speech.getText(), ((PlainTextOutputSpeech)response.getResponse().getOutputSpeech()).getText()); }
@Test public void ableToUploadFileFromConsumer() throws IOException { String file1Content = "hello world"; String file2Content = "bonjour"; String username = "mike"; Map<String, Object> map = new HashMap<>(); map.put("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath())); map.put("someFile", new FileSystemResource(newFile(file2Content).getAbsolutePath())); map.put("name", username); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); String result = RestTemplateBuilder.create().postForObject( "cse://springmvc-tests/codeFirstSpringmvc/upload", new HttpEntity<>(map, headers), String.class); assertThat(result, is(file1Content + file2Content + username)); }
@Test public void ableToPostWithHeaderWithIdentifier() { Person person = new Person(); person.setName("person name"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(APPLICATION_JSON); headers.add("prefix-test", "prefix prefix"); HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers); for (String url : urls) { ResponseEntity<String> responseEntity = restTemplate .postForEntity(url + "saysomething1", requestEntity, String.class); assertEquals("prefix prefix person name", jsonBodyOf(responseEntity, String.class)); } }
void verifyGenerate(ResponseEntity<CredentialDetails<T>> expectedResponse) { ParametersRequest<P> request = getGenerateRequest(); when(restTemplate.exchange(eq(BASE_URL_PATH), eq(POST), eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class))) .thenReturn(expectedResponse); if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) { try { credHubTemplate.generate(request); fail("Exception should have been thrown"); } catch (CredHubException e) { assertThat(e.getMessage(), containsString(expectedResponse.getStatusCode().toString())); } } else { CredentialDetails<T> response = credHubTemplate.generate(request); assertDetailsResponseContainsExpectedCredential(expectedResponse, response); } }
/** * Returns from a given concept the data properties and obejctproperties and * to each objecproperty a concept in the case the step range is greater 1 * * @param concept * @param step * range * @param * @return */ @CrossOrigin @RequestMapping(value = "/getPropertyValuesDiscretised", method = RequestMethod.GET) HttpEntity<Object> getPropertyValuesDiscretised(@RequestParam("inputAsJson") String inputAsJson) { try { Logger.getAnonymousLogger().log(Level.INFO, "Invoke: getPropertyValuesDiscretised: " + inputAsJson); Gson gson = new Gson(); InputParameterForgetPropertyValuesDiscretised paramterForGetLogicalView = gson.fromJson(inputAsJson, InputParameterForgetPropertyValuesDiscretised.class); Map<String, List<Group>> mapOfPropertyGroups = sparqlDerivation.generateGroup( paramterForGetLogicalView.getAmountOfGroups(), paramterForGetLogicalView.getConcept(), paramterForGetLogicalView.getProperty()); String result = ""; result = gson.toJson(mapOfPropertyGroups); return new ResponseEntity<Object>(result, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
@Test public void should_put_return_406__when_assigned_to_not_persisted_case() throws Exception { // given ResponseEntity<Void> postResponse = getCreateTreatmentResponse(); URI location = postResponse.getHeaders().getLocation(); String id = RestHelper.extractIdStringFromURI(location); Treatment savedTreatment = treatmentRepository.findOne(Long.parseLong(id)); theCase.setId(null); savedTreatment.setRelevantCase(theCase); // when ResponseEntity<Void> putResponse = testRestTemplate .withBasicAuth("1", "1") .exchange("/v1/treatments/" + id, HttpMethod.PUT, new HttpEntity<>(savedTreatment), Void.class); // then assertThat(putResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE); }
@SuppressWarnings("deprecation") void verifyGetByNameWithHistory(ResponseEntity<CredentialDetailsData<T>> expectedResponse) { when(restTemplate.exchange(eq(NAME_URL_QUERY), eq(GET), isNull(HttpEntity.class), isA(ParameterizedTypeReference.class), eq(NAME.getName()))) .thenReturn(expectedResponse); if (!expectedResponse.getStatusCode().equals(OK)) { try { credHubTemplate.getByNameWithHistory(NAME, String.class); fail("Exception should have been thrown"); } catch (CredHubException e) { assertThat(e.getMessage(), containsString(expectedResponse.getStatusCode().toString())); } } else { List<CredentialDetails<T>> response = credHubTemplate.getByNameWithHistory(NAME, getType()); assertDataResponseContainsExpectedCredentials(expectedResponse, response); } }
@Override public ExchangeConfig save(BotConfig botConfig, ExchangeConfig exchangeConfig) { try { LOG.info(() -> "About to save ExchangeConfig: " + exchangeConfig); restTemplate.getInterceptors().clear(); restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor( botConfig.getUsername(), botConfig.getPassword())); final String endpointUrl = botConfig.getBaseUrl() + EXCHANGE_RESOURCE_PATH; LOG.info(() -> "Sending ExchangeConfig to: " + endpointUrl); final HttpEntity<ExchangeConfig> requestUpdate = new HttpEntity<>(exchangeConfig); final ResponseEntity<ExchangeConfig> savedConfig = restTemplate.exchange( endpointUrl, HttpMethod.PUT, requestUpdate, ExchangeConfig.class); LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + savedConfig); return savedConfig.getBody(); } catch (RestClientException e) { LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e); return null; } }
@Bean public String getSignKey() { RestTemplate keyUriRestTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); String username = this.resource.getClientId(); String password = this.resource.getClientSecret(); if (username != null && password != null) { byte[] token = Base64.getEncoder().encode((username + ":" + password).getBytes()); headers.add("Authorization", "Basic " + new String(token)); } HttpEntity<Void> request = new HttpEntity<>(headers); String url = this.resource.getJwt().getKeyUri(); return (String) keyUriRestTemplate .exchange(url, HttpMethod.GET, request, Map.class).getBody() .get("value"); }
public void pollInternal() { HttpHeaders requestHeaders = new HttpHeaders(); if (lastModified != null) { requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified)); } HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); ResponseEntity<Feed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Feed.class); if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) { log.trace("data has been modified"); Feed feed = response.getBody(); for (Entry entry : feed.getEntries()) { if ((lastModified == null) || (entry.getUpdated().after(lastModified))) { Shipment shipping = restTemplate .getForEntity(entry.getContents().get(0).getSrc(), Shipment.class).getBody(); log.trace("saving shipping {}", shipping.getId()); shipmentService.ship(shipping); } } if (response.getHeaders().getFirst("Last-Modified") != null) { lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED)); log.trace("Last-Modified header {}", lastModified); } } else { log.trace("no new data"); } }
@Test(dataProvider = "subjectProvider") public void testPolicyEvalWithFirstMatchDeny(final BaseSubject subject, final PolicyEvaluationRequestV1 policyEvaluationRequest, final String endpoint) throws Exception { this.privilegeHelper.putSubject(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), subject, endpoint, this.acsitSetUpFactory.getZone1Headers(), this.privilegeHelper.getDefaultAttribute()); String policyFile = "src/test/resources/multiple-site-based-policy-set.json"; String testPolicyName = this.policyHelper.setTestPolicy(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), this.acsitSetUpFactory.getZone1Headers(), endpoint, policyFile); ResponseEntity<PolicyEvaluationResult> postForEntity = this.acsitSetUpFactory.getAcsZoneAdminRestTemplate() .postForEntity(endpoint + PolicyHelper.ACS_POLICY_EVAL_API_PATH, new HttpEntity<>(policyEvaluationRequest, this.acsitSetUpFactory.getZone1Headers()), PolicyEvaluationResult.class); Assert.assertEquals(postForEntity.getStatusCode(), HttpStatus.OK); PolicyEvaluationResult responseBody = postForEntity.getBody(); Assert.assertEquals(responseBody.getEffect(), Effect.DENY); this.policyHelper.deletePolicySet(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), this.acsitSetUpFactory.getAcsUrl(), testPolicyName, this.acsitSetUpFactory.getZone1Headers()); this.privilegeHelper.deleteSubject(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), this.acsitSetUpFactory.getAcsUrl(), subject.getSubjectIdentifier(), this.acsitSetUpFactory.getZone1Headers()); }
@Test public void requestWithLastModifiedReturns304() { Order order = new Order(); order.setCustomer(customerRepository.findAll().iterator().next()); orderRepository.save(order); ResponseEntity<Feed> response = restTemplate.exchange(feedUrl(), HttpMethod.GET, new HttpEntity(null), Feed.class); Date lastModified = DateUtils.parseDate(response.getHeaders().getFirst("Last-Modified")); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("If-Modified-Since", DateUtils.formatDate(lastModified)); HttpEntity requestEntity = new HttpEntity(requestHeaders); response = restTemplate.exchange(feedUrl(), HttpMethod.GET, requestEntity, Feed.class); assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); }
@Override public String findEmail(final String username) { final PasswordManagementProperties.Rest rest = passwordManagementProperties.getRest(); if (StringUtils.isBlank(rest.getEndpointUrlEmail())) { return null; } final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.put("username", Arrays.asList(username)); final HttpEntity<String> entity = new HttpEntity<>(headers); final ResponseEntity<String> result = restTemplate.exchange(rest.getEndpointUrlEmail(), HttpMethod.GET, entity, String.class); if (result.getStatusCodeValue() == HttpStatus.OK.value() && result.hasBody()) { return result.getBody(); } return null; }
@PostMapping public HttpEntity<FooResource> create(@RequestBody FooResource fooResource) { HttpHeaders headers = new HttpHeaders(); Foo entity = new Foo(fooResource.getUuid(), "Foo"); // ... headers.setLocation(entityLinks.linkForSingleResource(FooResource.class, encode(entity.getId())).toUri()); return new ResponseEntity<>(headers, HttpStatus.CREATED); }
private HttpEntity<MultiValueMap<String, String>> buildResponseEntity( Submission submission, HttpHeaders headers) { logger.debug("Building response entity"); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); try { map.add("test_output", new ObjectMapper().writeValueAsString( submission.getTestOutput())); } catch (JsonProcessingException ex) { logger.debug("POJO deserialization failed"); } map.add("stdout", submission.getStdout()); map.add("stderr", submission.getStderr()); map.add("validations", submission.getValidations()); map.add("vm_log", submission.getVmLog()); map.add("token", submission.getId().toString()); map.add("status", submission.getStatus().toString()); map.add("exit_code", submission.getExitCode().toString()); return new HttpEntity<>(map, headers); }
private HttpEntity<Void> getAuthorizedRequest() throws IOException { HttpHeaders headers = new HttpHeaders(); Map<String, List<String>> credentialHeaders = this.credentials.getRequestMetadata(); Assert.notNull(credentialHeaders, "No valid credential header(s) found"); for (Map.Entry<String, List<String>> entry : credentialHeaders.entrySet()) { for (String value : entry.getValue()) { headers.add(entry.getKey(), value); } } Assert.isTrue(headers.containsKey(AUTHORIZATION_HEADER), "Authorization header required"); return new HttpEntity<>(headers); }
public BigInteger getBalance(String address) throws IOException { String s = "https://"+url+"/api" + "?module=account" + "&action=balance" + "&address=" + address + "&tag=latest" + "&apikey="+apiKey; HttpHeaders headers = new HttpHeaders(); headers.set("User-Agent", options.getUserAgent()); ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); ObjectMapper objectMapper = new ObjectMapper(); ReturnSingleValue retVal = objectMapper.readValue(res.getBody(), ReturnSingleValue.class); return new BigInteger(retVal.result); }
private static QueryResponse q(Query query, Token token) throws QueryExecutionBotException{ final String ENTITY_URI_RESOURCE = String.format(QUERY_RESOURCE, Bot.API_URL); QueryResponseParser parser = new QueryResponseParser(); QueryResponse response = null; HttpHeaders headers = HttpClient.getDevHeaders(token); HttpEntity<Query> request = new HttpEntity<>(query, headers); if(isValidQuery(query)) { initializeQueryDefaults(query); try { ResponseEntity<String> entityResponse = HttpClient.post(ENTITY_URI_RESOURCE, request); log.debug("Entity response -> {}", entityResponse); if(entityResponse.getStatusCode().is2xxSuccessful()){ log.info("Query executed suscessfull"); response = parser.parse(entityResponse); } } catch (EntityParserException e) { throw new QueryExecutionBotException("Error on execute query", e); } } return response; }
@Override public void subscribe(String localServerName, String graphName, String groupName, String externalUrl, String localUrl, String localUser, String localPassword) throws RestClientException { Map<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("servername", localServerName); requestParams.put("graph", graphName); requestParams.put("groupname", groupName); requestParams.put("url", localUrl); requestParams.put("user", localUser); requestParams.put("password", localPassword); String subscriptionUrl = createSubscriptionUrl(externalUrl); HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String,Object>>(new HashMap<String, Object>()); // HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String,Object>>(requestParams, // getHeaders(subscriptionUrl, user, password)); restTemplate.postForLocation(subscriptionUrl + SUBSCRIPTION, request, requestParams); }
@Override public EmailAlertsConfig save(BotConfig botConfig, EmailAlertsConfig emailAlertsConfig) { try { LOG.info(() -> "About to save EmailAlertsConfig: " + emailAlertsConfig); restTemplate.getInterceptors().clear(); restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor( botConfig.getUsername(), botConfig.getPassword())); final String endpointUrl = botConfig.getBaseUrl() + EMAIL_ALERTS_RESOURCE_PATH; LOG.info(() -> "Sending EmailAlertsConfig to: " + endpointUrl); final HttpEntity<EmailAlertsConfig> requestUpdate = new HttpEntity<>(emailAlertsConfig); final ResponseEntity<EmailAlertsConfig> savedConfig = restTemplate.exchange( endpointUrl, HttpMethod.PUT, requestUpdate, EmailAlertsConfig.class); LOG.info(() -> REMOTE_RESPONSE_RECEIVED_LOG_MSG + savedConfig); final EmailAlertsConfig savedConfigBody = savedConfig.getBody(); savedConfigBody.setId(botConfig.getId()); return savedConfigBody; } catch (RestClientException e) { LOG.error(FAILED_TO_INVOKE_REMOTE_BOT_LOG_MSG + e.getMessage(), e); return null; } }
/** Execute un WS sur LimeSurvey * @param obj * @return la ResponseEntity */ private ResponseEntity<String> executeWS(LimeSurveyRestObject obj){ try { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); String serialized; ObjectMapper mapper = new ObjectMapper(); serialized = mapper.writeValueAsString(obj); HttpEntity<String> requestEntity=new HttpEntity<String>(serialized,headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.exchange(URL,HttpMethod.POST,requestEntity,String.class); return response; } catch (Exception e) { logger.error("Erreur d'appel du web service "+obj.getMethod()+" sur LimeSurvey",e); return null; } }
@Override public RestTemplateResponse execute() throws IOException { HttpEntity<String> entityReq = new HttpEntity<>(requestBody, headers); try { ResponseEntity<String> response = template.exchange(url, HttpMethod.resolve(method.name()), entityReq, String.class); return new RestTemplateResponse(response); } catch (HttpClientErrorException e) { return new RestTemplateResponse(e.getRawStatusCode(), e.getStatusCode().getReasonPhrase(), e.getResponseBodyAsString (), e.getResponseHeaders()); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public <P extends EasyTransRequest<R, ?>, R extends Serializable> R call(String appId, String busCode, String innerMethod, Map<String,Object> header, P params) { String context = properties.getConsumer().get(appId).getContext(); if(context == null){ context = ""; } Class<? extends EasyTransRequest> paramsClass = params.getClass(); Class<?> resultClass = ReflectUtil.getResultClass(paramsClass); MultiValueMap<String, String> headers = new HttpHeaders(); headers.set(RestRibbonEasyTransConstants.HttpHeaderKey.EASYTRANS_HEADER_KEY, encodeEasyTransHeader(header)); HttpEntity<P> requestEntity = new HttpEntity<>(params, headers); ResponseEntity<?> exchangeResult = loadBalancedRestTemplate.exchange("http://" + appId + "/" + context + "/" + busCode + "/" + innerMethod, HttpMethod.POST, requestEntity, resultClass); if(!exchangeResult.getStatusCode().is2xxSuccessful()){ throw new RuntimeException("远程请求发生错误:" + exchangeResult); } return (R) exchangeResult.getBody(); }
/** * Verify sms code. * * @param phone The phone number to receive sms code * @param code The sms code * @return True if sms code is verified successfully */ public boolean verifySmsCode(String phone, String code) { try { String url = URL_VRF_SMS + "/" + code + "?mobilePhoneNumber=" + phone; Log.info("verifySmsCode() url: " + url); HttpEntity<String> reqEntity = new HttpEntity<String>(headers); String res = restTemplate.postForObject(url, reqEntity, String.class); Log.info("verifySmsCode() res: " + res); return true; } catch (HttpClientErrorException e) { Log.error("verifySmsCode() res: " + e.getMessage()); Log.error("verifySmsCode() res: " + e.getResponseBodyAsString()); return false; } }
public BaseResource putResource(final OAuth2RestTemplate acsTemplate, final BaseResource resource, final String endpoint, final HttpHeaders headers, final Attribute... attributes) throws Exception { resource.setAttributes(new HashSet<>(Arrays.asList(attributes))); String value = URLEncoder.encode(resource.getResourceIdentifier(), "UTF-8"); URI uri = new URI(endpoint + ACS_RESOURCE_API_PATH + value); acsTemplate.put(uri, new HttpEntity<>(resource, headers)); return resource; }
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); }
/** * This test makes sure that cached policy evaluation results are properly invalidated when a policy set changes. * Policy set name that is used to derive part of cache key does not change. */ @Test public void testPolicyEvalCacheWhenPolicySetChanges() throws Exception { BaseSubject subject = MARISSA_V1; PolicyEvaluationRequestV1 policyEvaluationRequest = this.policyHelper .createEvalRequest(MARISSA_V1.getSubjectIdentifier(), "sanramon"); String endpoint = this.acsUrl; this.privilegeHelper.putSubject(this.acsAdminRestTemplate, subject, endpoint, this.acsZone1Headers, this.privilegeHelper.getDefaultAttribute()); String policyFile = "src/test/resources/policies/single-site-based.json"; this.policyHelper.setTestPolicy(this.acsAdminRestTemplate, this.acsZone1Headers, endpoint, policyFile); ResponseEntity<PolicyEvaluationResult> postForEntity = this.acsAdminRestTemplate .postForEntity(endpoint + PolicyHelper.ACS_POLICY_EVAL_API_PATH, new HttpEntity<>(policyEvaluationRequest, this.acsZone1Headers), PolicyEvaluationResult.class); Assert.assertEquals(postForEntity.getStatusCode(), HttpStatus.OK); PolicyEvaluationResult responseBody = postForEntity.getBody(); Assert.assertEquals(responseBody.getEffect(), Effect.PERMIT); policyFile = "src/test/resources/policies/deny-all.json"; this.policyHelper.setTestPolicy(this.acsAdminRestTemplate, this.acsZone1Headers, endpoint, policyFile); postForEntity = this.acsAdminRestTemplate.postForEntity(endpoint + PolicyHelper.ACS_POLICY_EVAL_API_PATH, new HttpEntity<>(policyEvaluationRequest, this.acsZone1Headers), PolicyEvaluationResult.class); Assert.assertEquals(postForEntity.getStatusCode(), HttpStatus.OK); responseBody = postForEntity.getBody(); Assert.assertEquals(responseBody.getEffect(), Effect.DENY); }
/** * Performs a query for a csrf token. * * @param jsessionId the cookie returned after a successful login. * @return a {@link ResponseEntity} containing an JSON object as its body. */ private ResponseEntity<String> csrf(String jsessionId) { String tmpUrl = "http://localhost:" + String.valueOf(this.port) + "/services/rest/security/v1/csrftoken"; HttpHeaders headers = prepareHeaders(new StrTup(HttpHeaders.COOKIE, jsessionId)); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> responseEntity = this.template.exchange(tmpUrl, HttpMethod.GET, entity, String.class); return responseEntity; }
private InputStream asInputStream(String url) { String targetUrl = url.replace(".webp", ".png"); HttpHeaders headers = new HttpHeaders(); // workaround to go through CloudFlare :^) headers.add("User-Agent", Constants.USER_AGENT); try { ResponseEntity<Resource> responseEntity = restTemplate.exchange(targetUrl, HttpMethod.GET, new HttpEntity<>(headers), Resource.class); return responseEntity.getBody().getInputStream(); } catch (IOException | RestClientException e) { log.warn("Could not get {} as InputStream", e); return null; } }
@RequestMapping("/cart-checkout") public ShoppingCart checkoutOrder() { LOG.info("you called home"); List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>(); acceptableMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); HttpHeaders headers = new HttpHeaders(); headers.setAccept(acceptableMediaTypes); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity<ShoppingCart> cart = new HttpEntity<>((new ShoppingCart(1, Arrays.asList(new LineItem(1, "abc")))), headers); ShoppingCart response = restTemplate.postForObject("http://localhost:9000/checkout", cart, ShoppingCart.class); return response; }
@RequestMapping(path = "/assays/{id}" + Links.INVALID_URL, method = RequestMethod.PUT) HttpEntity<?> invalidateAssay(@PathVariable("id") Assay assay) { Event event = this.getStateEngine().advanceStateOfMetadataDocument( getAssayService().getAssayRepository(), assay, ValidationState.INVALID); return ResponseEntity.accepted().body(event); }
GoogleConfigEnvironment getRemoteEnvironment() throws IOException, HttpClientErrorException { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setReadTimeout(this.timeout); RestTemplate template = new RestTemplate(requestFactory); HttpEntity<Void> requestEntity = getAuthorizedRequest(); ResponseEntity<GoogleConfigEnvironment> response = template.exchange( RUNTIMECONFIG_API_ROOT + ALL_VARIABLES_PATH, HttpMethod.GET, requestEntity, GoogleConfigEnvironment.class, this.projectId, this.name, this.profile); if (response == null || !response.getStatusCode().is2xxSuccessful()) { HttpStatus code = (response == null) ? HttpStatus.BAD_REQUEST : response.getStatusCode(); throw new HttpClientErrorException(code, "Invalid response from Runtime Configurator API"); } return response.getBody(); }