Java Code Examples for org.springframework.http.HttpEntity

The following are top voted examples for showing how to use org.springframework.http.HttpEntity. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: second-opinion-api   File: TreatmentControllerIT.java   Source Code and License 8 votes vote down vote up
@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);
}
 
Example 2
Project: OpenLRW   File: IntegrationAPITest.java   Source Code and License 8 votes vote down vote up
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();
}
 
Example 3
Project: monarch   File: ClientHttpRequest.java   Source Code and License 7 votes vote down vote up
/**
 * 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());
  }
}
 
Example 4
Project: catalog-search-service   File: SearchController.java   Source Code and License 7 votes vote down vote up
@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);
	}

}
 
Example 5
Project: api-batchupload-sample-application   File: Client.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 6
Project: incubator-servicecomb-java-chassis   File: SpringMvcIntegrationTestBase.java   Source Code and License 7 votes vote down vote up
@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));
}
 
Example 7
Project: REST-Web-Services   File: SettingsController.java   Source Code and License 7 votes vote down vote up
/**
 * This method activates the e-mail change using a token
 * @param token E-mail change activation token
 * @param uriComponentsBuilder {@link UriComponentsBuilder}
 * @return The ModelAndView for sign in
 */
@PreAuthorize("permitAll()")
@GetMapping(value = "changeEmail/thanks")
public
ModelAndView confirmEmail(
        @RequestParam final String token,
        final UriComponentsBuilder uriComponentsBuilder
) {
    SSLContextHelper.disable();

    final RestTemplate restTemplate = new RestTemplate();
    final HttpEntity<Object> entity = new HttpEntity<>(new HttpHeaders());

    final UriComponents uriComponents
            = uriComponentsBuilder.path("/api/v1.0/settings/changeEmail/token/{token}").buildAndExpand(token);

    ResponseEntity<Void> response;

    try {
        response = restTemplate
                .exchange(uriComponents.toUri(),
                          HttpMethod.PUT,
                          entity,
                          Void.class);
    } catch (HttpClientErrorException e) /* IF 404 */ {
        return new ModelAndView("tokenNotFound");
    }

    /* IF 200 */
    return new ModelAndView("redirect:/signIn");
}
 
Example 8
Project: Learning-Spring-Boot-2.0-Second-Edition   File: CommentHelper.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 9
Project: alexa-skill   File: CalendarSpeechletIT.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 10
Project: incubator-servicecomb-java-chassis   File: JaxrsIntegrationTestBase.java   Source Code and License 6 votes vote down vote up
@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));
  }
}
 
Example 11
Project: spring-credhub   File: CredHubTemplateDetailUnitTestsBase.java   Source Code and License 6 votes vote down vote up
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);
	}
}
 
Example 12
Project: catalog-search-service   File: SearchController.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
	}

}
 
Example 13
Project: second-opinion-api   File: TreatmentControllerIT.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 14
Project: alexa-proxy   File: AlexaProxyServlet.java   Source Code and License 6 votes vote down vote up
@Override
// A. It must be a POST request.
protected void doPost(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws ServletException, IOException {
    byte[] serializedSpeechletRequest = IOUtils.toByteArray(httpRequest.getInputStream());

    try {
        if (this.checkAmazonSignature) {
            // B. It must come from the Amazon Alexa cloud.
            SpeechletRequestSignatureVerifier.checkRequestSignature(serializedSpeechletRequest,
                    httpRequest.getHeader(Sdk.SIGNATURE_REQUEST_HEADER),
                    httpRequest.getHeader(Sdk.SIGNATURE_CERTIFICATE_CHAIN_URL_REQUEST_HEADER));
        }

        final SpeechletRequestEnvelope<?> requestEnvelope = SpeechletRequestEnvelope.fromJson(serializedSpeechletRequest);

        for (SpeechletRequestEnvelopeVerifier verifier : this.requestEnvelopeVerifiers) {
            if (!verifier.verify(requestEnvelope)) {
                throw new SpeechletRequestHandlerException(this.createExceptionMessage(verifier, requestEnvelope));
            }
        }

        HttpEntity<byte[]> requestEntity = new HttpEntity<>(serializedSpeechletRequest);
        ResponseEntity<SpeechletResponseEnvelope> speechletResponse = this.restTemplate.postForEntity(
                this.endpoint, requestEntity, SpeechletResponseEnvelope.class);
        if (speechletResponse.getStatusCode().is2xxSuccessful() && speechletResponse.hasBody()) {
            byte[] outputBytes = speechletResponse.getBody().toJsonBytes();
            httpResponse.setContentType("application/json");
            httpResponse.setStatus(speechletResponse.getStatusCodeValue());
            httpResponse.setContentLength(outputBytes.length);
            httpResponse.getOutputStream().write(outputBytes);
        } else {
            // Should never happen, cause all edge cases are already covered by actual exceptions thrown.
            httpResponse.sendError(speechletResponse.getStatusCodeValue(), "Unexpected error in proxy");
        }
    } catch (Exception e) {
        int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        if (BAD_REQUEST_EXCEPTION_TYPES.contains(e.getClass())) {
            statusCode = HttpServletResponse.SC_BAD_REQUEST;
        }
        this.log.error("Exception occurred in doPost, returning status code {}", statusCode, e);
        httpResponse.sendError(statusCode, e.getClass().getSimpleName() + ": " + e.getMessage());
    }
}
 
Example 15
Project: spring-credhub   File: CredHubTemplateDetailUnitTestsBase.java   Source Code and License 6 votes vote down vote up
@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);
	}
}
 
Example 16
Project: bxbot-ui-server   File: ExchangeConfigRepositoryRestClient.java   Source Code and License 6 votes vote down vote up
@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;
    }
}
 
Example 17
Project: Learning-Spring-5.0   File: Main_Get_Book.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub

	RestTemplate template = new RestTemplate();
	Book book = template.getForObject("http://localhost:8080/Ch11_Spring_Reactive_Web/books/14", Book.class);
	System.out.println(book.getAuthor() + "\t" + book.getISBN());

	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
	HttpEntity<String> entity = new HttpEntity<String>(headers);

	ResponseEntity<List> responseEntity = template
			.getForEntity("http://localhost:8080/Ch11_Spring_Reactive_Web/books", List.class);
	List<ArrayList<Book>> books = responseEntity.getBody();
	int i = 0;
	for (ArrayList l : books) {
		for (int j = 0; i < l.size(); j++) {
			LinkedHashMap<String, Book> map = (LinkedHashMap<String, Book>) l.get(i);
			Set<Entry<String, Book>> set = map.entrySet();
			System.out.println("***\tBook:-"+i +"\t****");
			for (Entry<String, Book> entry : set) {
				System.out.print(entry.getValue() + "\t");
			}
			i++;
			System.out.println();
		}
	}
}
 
Example 18
Project: OAuth-2.0-Cookbook   File: OAuth2ResourceServer.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 19
Project: microservice-atom   File: ShippingPoller.java   Source Code and License 6 votes vote down vote up
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");
	}
}
 
Example 20
Project: keti   File: AccessControlServiceIT.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 21
Project: microservice-atom   File: AtomClientTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 22
Project: poppynotes   File: UserClientServiceTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testCachedRequest_withThreeCallsAndClearCache_shouldReallyCallTwoTimes() {
	reset(mockTemplate);
	when(mockTemplate.exchange(anyString(), any(HttpMethod.class),any(HttpEntity.class),any(Class.class))).thenReturn(new ResponseEntity<>(HttpStatus.OK));
	service.setRestTemplate(mockTemplate);
	
	service.getUserInfoFromAuthEmail("[email protected]");
	service.getUserInfoFromAuthEmail("[email protected]");
	
	service.clearCachedUser("[email protected]");
	
	service.getUserInfoFromAuthEmail("[email protected]");
	service.getUserInfoFromAuthEmail("[email protected]");
	service.getUserInfoFromAuthEmail("[email protected]");
	
	verify(mockTemplate,times(2)).exchange(anyString(), any(HttpMethod.class),any(HttpEntity.class),any(Class.class));
}
 
Example 23
Project: cas-5.1.0   File: RestPasswordManagementService.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 24
Project: friendly-id   File: FooController.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 25
Project: tdd-pingpong   File: FakeSandboxRestService.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 26
Project: spring-cloud-gcp   File: GoogleConfigPropertySourceLocator.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 27
Project: tokenapp-backend   File: Etherscan.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 28
Project: botengine-ai   File: Engine.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 29
Project: graphium   File: SubscriptionRestCallServiceImpl.java   Source Code and License 6 votes vote down vote up
@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);	
	}
 
Example 30
Project: bxbot-ui-server   File: EmailAlertsConfigRepositoryRestClient.java   Source Code and License 6 votes vote down vote up
@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;
    }
}
 
Example 31
Project: esup-ecandidat   File: LimeSurveyRest.java   Source Code and License 6 votes vote down vote up
/** 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;
	}
}
 
Example 32
Project: crnk-framework   File: RestTemplateRequest.java   Source Code and License 5 votes vote down vote up
@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());
	}
}
 
Example 33
Project: EasyTransaction   File: RestRibbonEasyTransRpcConsumerImpl.java   Source Code and License 5 votes vote down vote up
@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();
}
 
Example 34
Project: ServiceServer   File: SmsService.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 35
Project: keti   File: PrivilegeHelper.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 36
Project: FakeTwitterDetection   File: Request.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 37
Project: spring-security-oauth2-boot   File: OAuth2AutoConfigurationTests.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 38
Project: keti   File: PolicyEvaluationCachingIT.java   Source Code and License 5 votes vote down vote up
/**
 * 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);

}
 
Example 39
Project: sentry   File: Info.java   Source Code and License 5 votes vote down vote up
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;
    }
}
 
Example 40
Project: trace-demo   File: TraceDemoApplication.java   Source Code and License 5 votes vote down vote up
@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;
}