Java Code Examples for org.springframework.http.HttpEntity

The following examples show how to use org.springframework.http.HttpEntity. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: jVoiD   Author: schogini   File: HomeController.java    License: Apache License 2.0 8 votes vote down vote up
@RequestMapping("/order")
public @ResponseBody String orderProductNowById(@RequestParam("cartId") String cartId, @RequestParam("prodId") String productId) {
	RestTemplate restTemplate = new RestTemplate();
	HttpHeaders headers = new HttpHeaders();
	headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

	JSONObject jsonObj = new JSONObject();
	try {
		jsonObj.put("cartId", Integer.parseInt(cartId));
		jsonObj.put("productId", Integer.parseInt(productId));
		jsonObj.put("attributeId", 1);
		jsonObj.put("quantity", 1);
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	System.out.println("param jsonObj=>"+jsonObj.toString());
	
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(ServerUris.QUOTE_SERVER_URI+URIConstants.ADD_PRODUCT_TO_CART)
	        .queryParam("params", jsonObj);	
	HttpEntity<?> entity = new HttpEntity<>(headers);
	HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class);
	return returnString.getBody();
}
 
Example #2
Source Project: camunda-bpm-platform   Author: camunda   File: CorsAuthenticationTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void shouldPassAuthenticatedCorsRequest() {
  // given
  // cross origin but allowed through wildcard
  String origin = "http://other.origin";

  HttpHeaders headers = new HttpHeaders();
  headers.add(HttpHeaders.ORIGIN, origin);

  Group group = new GroupEntity("groupId");
  
  // create group
  processEngine.getIdentityService().saveGroup(new GroupEntity("groupId"));

  group.setName("updatedGroupName");

  // when
  ResponseEntity<String> response = authTestRestTemplate.exchange(CONTEXT_PATH + "/group/" + group.getId(), HttpMethod.PUT, new HttpEntity<>(group, headers),
      String.class);

  // then
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
  assertThat(response.getHeaders().getAccessControlAllowOrigin()).contains("*");
}
 
Example #3
Source Project: camunda-bpm-platform   Author: camunda   File: CorsAuthenticationTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void shouldPassNonAuthenticatedPreflightRequest() {
  // given
  // cross origin but allowed through wildcard
  String origin = "http://other.origin";

  HttpHeaders headers = new HttpHeaders();
  headers.add(HttpHeaders.HOST, "localhost");
  headers.add(HttpHeaders.ORIGIN, origin);
  headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.PUT.name());
  headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, HttpHeaders.ORIGIN);

  // when
  ResponseEntity<String> response = testRestTemplate.exchange(CONTEXT_PATH + "/task", HttpMethod.OPTIONS, new HttpEntity<>(headers), String.class);

  // then
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
 
Example #4
Source Project: Moss   Author: SpringCloud   File: MicrosoftTeamsNotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void test_onClientApplicationDeRegisteredEvent_resolve() {
    InstanceDeregisteredEvent event = new InstanceDeregisteredEvent(instance.getId(), 1L);

    StepVerifier.create(notifier.doNotify(event, instance)).verifyComplete();

    ArgumentCaptor<HttpEntity<Message>> entity = ArgumentCaptor.forClass(HttpEntity.class);
    verify(mockRestTemplate).postForEntity(eq(URI.create("http://example.com")),
        entity.capture(),
        eq(Void.class)
    );

    assertThat(entity.getValue().getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
    assertMessage(entity.getValue().getBody(),
        notifier.getDeRegisteredTitle(),
        notifier.getMessageSummary(),
        String.format(notifier.getDeregisterActivitySubtitlePattern(),
            instance.getRegistration().getName(),
            instance.getId()
        )
    );
}
 
Example #5
Source Project: MicroCommunity   Author: java110   File: AddStaffServiceListener.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 用户赋权
 *
 * @return
 */
private void privilegeUserDefault(DataFlowContext dataFlowContext, JSONObject paramObj) {
    ResponseEntity responseEntity = null;
    AppService appService = DataFlowFactory.getService(dataFlowContext.getAppId(), ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE);
    if (appService == null) {
        responseEntity = new ResponseEntity<String>("当前没有权限访问" + ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE, HttpStatus.UNAUTHORIZED);
        dataFlowContext.setResponseEntity(responseEntity);
        return;
    }
    String requestUrl = appService.getUrl();
    HttpHeaders header = new HttpHeaders();
    header.add(CommonConstant.HTTP_SERVICE.toLowerCase(), ServiceCodeConstant.SERVICE_CODE_SAVE_USER_DEFAULT_PRIVILEGE);
    userBMOImpl.freshHttpHeader(header, dataFlowContext.getRequestCurrentHeaders());
    JSONObject paramInObj = new JSONObject();
    paramInObj.put("userId", paramObj.getString("userId"));
    paramInObj.put("storeTypeCd", paramObj.getString("storeTypeCd"));
    paramInObj.put("userFlag", "staff");
    HttpEntity<String> httpEntity = new HttpEntity<String>(paramInObj.toJSONString(), header);
    doRequest(dataFlowContext, appService, httpEntity);
    responseEntity = dataFlowContext.getResponseEntity();

    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        dataFlowContext.setResponseEntity(responseEntity);
    }
}
 
Example #6
Source Project: spring-credhub   Author: spring-projects   File: CredHubCertificateTemplateUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void bulkRegenerate() {
	Map<String, List<CredentialName>> expectedResponse = Collections.singletonMap(
			CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD,
			Arrays.asList(new SimpleCredentialName("example-certificate1"),
					new SimpleCredentialName("example-certificate2")));

	Map<String, Object> request = new HashMap<String, Object>() {
		{
			put(CredHubCertificateTemplate.SIGNED_BY_REQUEST_FIELD, NAME.getName());
		}
	};

	given(this.restTemplate.exchange(eq(CredHubCertificateTemplate.BULK_REGENERATE_URL_PATH), eq(HttpMethod.POST),
			eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class)))
					.willReturn(new ResponseEntity<>(expectedResponse, HttpStatus.OK));

	List<CredentialName> response = this.credHubTemplate.regenerate(NAME);

	assertThat(response).isNotNull();
	assertThat(response)
			.isEqualTo(expectedResponse.get(CredHubCertificateTemplate.REGENERATED_CREDENTIALS_RESPONSE_FIELD));
}
 
Example #7
Source Project: spring-boot-demo   Author: xkcoding   File: OauthResourceTokenConfig.java    License: MIT License 6 votes vote down vote up
/**
 * 本地没有公钥的时候,从服务器上获取
 * 需要进行 Basic 认证
 *
 * @return public key
 */
private String getKeyFromAuthorizationServer() {
    ObjectMapper objectMapper = new ObjectMapper();
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add(HttpHeaders.AUTHORIZATION, encodeClient());
    HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
    String pubKey = new RestTemplate()
        .getForObject(resourceServerProperties.getJwt().getKeyUri(), String.class, requestEntity);
    try {
        JSONObject body = objectMapper.readValue(pubKey, JSONObject.class);
        log.info("Get Key From Authorization Server.");
        return body.getStr("value");
    } catch (IOException e) {
        log.error("Get public key error: {}", e.getMessage());
    }
    return null;
}
 
Example #8
Source Project: servicecomb-java-chassis   Author: apache   File: JaxrsIntegrationTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void ableToPostWithHeader() {
  Person person = new Person();
  person.setName("person name");

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(APPLICATION_JSON);
  headers.add("prefix", "prefix  prefix");

  HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
  for (String url : urls) {
    ResponseEntity<String> responseEntity = restTemplate
        .postForEntity(url + "saysomething", requestEntity, String.class);

    assertEquals("prefix  prefix person name", jsonBodyOf(responseEntity, String.class));
  }
}
 
Example #9
Source Project: demo-spring-boot-security-oauth2   Author: leftso   File: GrantByImplicitProviderTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getJwtTokenByImplicitGrant() throws JsonParseException, JsonMappingException, IOException {
    String redirectUrl = "http://localhost:"+port+"/resources/user";
    ResponseEntity<String> response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
       + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}", null, String.class,redirectUrl);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    List<String> setCookie = response.getHeaders().get("Set-Cookie");
    String jSessionIdCookie = setCookie.get(0);
    String cookieValue = jSessionIdCookie.split(";")[0];

    HttpHeaders headers = new HttpHeaders();
    headers.add("Cookie", cookieValue);
    response = new TestRestTemplate("user","password").postForEntity("http://localhost:" + port 
            + "oauth/authorize?response_type=token&client_id=normal-app&redirect_uri={redirectUrl}&user_oauth_approval=true&authorize=Authorize",
            new HttpEntity<>(headers), String.class, redirectUrl);
    assertEquals(HttpStatus.FOUND, response.getStatusCode());
    assertNull(response.getBody());
    String location = response.getHeaders().get("Location").get(0);

    //FIXME: Is this a bug with redirect URL?
    location = location.replace("#", "?");

    response = new TestRestTemplate().getForEntity(location, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
}
 
Example #10
Source Project: DataLink   Author: ucarGroup   File: WorkerController.java    License: Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/doEditLogback")
public String saveLogback(String workerId, String content) {
    logger.info("Receive a request to save logback.xml, with workerId " + workerId + "\r\n with content " + content);

    if (StringUtils.isBlank(content)) {
        return "content can not be null";
    }
    try {
        WorkerInfo workerInfo = workerService.getById(Long.valueOf(workerId));
        if (workerInfo != null) {
            String url = "http://" + workerInfo.getWorkerAddress() + ":" + workerInfo.getRestPort() + "/worker/doEditLogback/" + workerId;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            Map<String, String> map = new HashMap<>();
            map.put("content", content);
            HttpEntity request = new HttpEntity(map, headers);
            new RestTemplate(Lists.newArrayList(new FastJsonHttpMessageConverter())).postForObject(url, request, String.class);
            return "success";
        }
        return "fail";
    } catch (Exception e) {
        logger.info("request to save logback.xml error:", e);
        return e.getMessage();
    }
}
 
Example #11
Source Project: spring-analysis-note   Author: Vip-Augus   File: RestTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void postForLocationEntityContentType() throws Exception {
	mockSentRequest(POST, "https://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);

	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("https://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_PLAIN);
	HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);

	URI result = template.postForLocation("https://example.com", entity);
	assertEquals("Invalid POST result", expected, result);

	verify(response).close();
}
 
Example #12
Source Project: java-technology-stack   Author: codeEngraver   File: AsyncRestTemplateIntegrationTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void exchangeGetCallback() throws Exception {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("MyHeader", "MyValue");
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ListenableFuture<ResponseEntity<String>> responseFuture =
			template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get");
	responseFuture.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
		@Override
		public void onSuccess(ResponseEntity<String> result) {
			assertEquals("Invalid content", helloWorld, result.getBody());
		}
		@Override
		public void onFailure(Throwable ex) {
			fail(ex.getMessage());
		}
	});
	waitTillDone(responseFuture);
}
 
Example #13
Source Project: taskana   Author: Taskana   File: TaskControllerIntTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * TSK-926: If Planned and Due Date is provided to create a task and not matching to service level
 * throw an exception One is calculated by other other date +- service level.
 */
@Test
void testCreateWithPlannedAndDueDate() {
  TaskRepresentationModel taskRepresentationModel = getTaskResourceSample();
  Instant now = Instant.now();
  taskRepresentationModel.setPlanned(now);
  taskRepresentationModel.setDue(now);

  ThrowingCallable httpCall =
      () ->
          template.exchange(
              restHelper.toUrl(Mapping.URL_TASKS),
              HttpMethod.POST,
              new HttpEntity<>(taskRepresentationModel, restHelper.getHeadersUser_1_1()),
              TASK_MODEL_TYPE);
  assertThatThrownBy(httpCall).isInstanceOf(HttpClientErrorException.class);
}
 
Example #14
Source Project: cloud-espm-cloud-native   Author: SAP-samples   File: CloudSalesOrderService.java    License: Apache License 2.0 6 votes vote down vote up
private String getTaxUrlFromDestinationService() {
	try {
		final DestinationService destination = getDestinationServiceDetails("destination");
		final String accessToken = getOAuthToken(destination);
		headers.set("Authorization", "Bearer " + accessToken);
		HttpEntity entity = new HttpEntity(headers);
		final String taxUrl = destination.uri + DESTINATION_PATH + taxDestination;
		final ResponseEntity<String> response = restTemplate.exchange(taxUrl, HttpMethod.GET, entity, String.class);
		final JsonNode root = mapper.readTree(response.getBody());
		final String texDestination = root.path("destinationConfiguration").path("URL").asText();
		return texDestination;
	} catch (IOException e) {
		logger.error("No proper destination Service available: {}", e.getMessage());

	}
	return "";
}
 
Example #15
Source Project: servicecomb-java-chassis   Author: apache   File: BeanParamRestTemplateClient.java    License: Apache License 2.0 6 votes vote down vote up
private void testUpload() {
  BufferedInputStream bufferedInputStream0 = new BufferedInputStream(new ByteArrayInputStream("up0".getBytes()));
  BufferedInputStream bufferedInputStream1 = new BufferedInputStream(new ByteArrayInputStream("up1".getBytes()));
  BufferedInputStream bufferedInputStream2 = new BufferedInputStream(new ByteArrayInputStream("up2".getBytes()));

  HashMap<String, Object> formData = new HashMap<>();
  formData.put("up0", bufferedInputStream0);
  formData.put("up1", bufferedInputStream1);
  formData.put("up2", bufferedInputStream2);
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  HttpEntity<Map<String, Object>> entity = new HttpEntity<>(formData, headers);

  String result = restTemplate.postForObject("cse://jaxrs/beanParamTest/upload?query=fromTemplate&extraQuery=ex",
      entity,
      String.class);
  TestMgr.check(
      "testBeanParameter=TestBeanParameterWithUpload{queryStr='fromTemplate'}|extraQuery=ex|up0=up0|up1=up1|up2=up2",
      result);
}
 
Example #16
Source Project: SkaETL   Author: skalogs   File: MetricImporter.java    License: Apache License 2.0 6 votes vote down vote up
private void sendToRegistry(String action) {
    if (registryConfiguration.getActive()) {
        RegistryWorker registry = null;
        try {
            registry = RegistryWorker.builder()
                    .workerType(WorkerType.METRIC_PROCESS)
                    .ip(InetAddress.getLocalHost().getHostName())
                    .name(InetAddress.getLocalHost().getHostName())
                    .port(processConfiguration.getPortClient())
                    .statusConsumerList(statusExecutor())
                    .build();
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<RegistryWorker> request = new HttpEntity<>(registry);
            String url = processConfiguration.getUrlRegistry();
            String res = restTemplate.postForObject(url + "/process/registry/" + action, request, String.class);
            log.debug("sendToRegistry result {}", res);
        } catch (Exception e) {
            log.error("Exception on sendToRegistry", e);
        }
    }
}
 
Example #17
Source Project: spring-in-action-5-samples   Author: habuma   File: IngredientServiceClient.java    License: Apache License 2.0 6 votes vote down vote up
@HystrixCommand(fallbackMethod="getDefaultIngredients",
    commandProperties={
        @HystrixProperty(
            name="execution.isolation.thread.timeoutInMilliseconds",
            value="500"),
            @HystrixProperty(
                name="circuitBreaker.requestVolumeThreshold",
                value="30"),
            @HystrixProperty(
                name="circuitBreaker.errorThresholdPercentage",
                value="25"),
            @HystrixProperty(
                name="metrics.rollingStats.timeInMilliseconds",
                value="20000"),
            @HystrixProperty(
                name="circuitBreaker.sleepWindowInMilliseconds",
                value="60000")
    })
public Iterable<Ingredient> getAllIngredients() {
  ParameterizedTypeReference<List<Ingredient>> stringList =
      new ParameterizedTypeReference<List<Ingredient>>() {};
  return rest.exchange(
      "http://ingredient-service/ingredients", HttpMethod.GET,
      HttpEntity.EMPTY, stringList).getBody();
}
 
Example #18
Source Project: flowable-engine   Author: flowable   File: RestApiSecurityApplicationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCmmnRestApiIntegrationWithAuthentication() {
    String processDefinitionsUrl = "http://localhost:" + serverPort + "/cmmn-api/cmmn-repository/case-definitions";

    HttpEntity<?> request = new HttpEntity<>(createHeaders("filiphr", "password"));
    ResponseEntity<DataResponse<CaseDefinitionResponse>> response = restTemplate
        .exchange(processDefinitionsUrl, HttpMethod.GET, request, new ParameterizedTypeReference<DataResponse<CaseDefinitionResponse>>() {
        });

    assertThat(response.getStatusCode())
        .as("Status code")
        .isEqualTo(HttpStatus.OK);
    DataResponse<CaseDefinitionResponse> caseDefinitions = response.getBody();
    assertThat(caseDefinitions).isNotNull();
    CaseDefinitionResponse defResponse = caseDefinitions.getData().get(0);
    assertThat(defResponse.getKey()).isEqualTo("case1");
    assertThat(defResponse.getUrl()).startsWith("http://localhost:" + serverPort + "/cmmn-api/cmmn-repository/case-definitions/");
}
 
Example #19
Source Project: onboard   Author: sercxtyf   File: AttachmentApi.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/api/{companyId}/projects/{projectId}/attachments/{attachmentId}/download", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> downloadAttachment(@PathVariable("companyId") int companyId,
        @PathVariable("projectId") int projectId, @PathVariable("attachmentId") int attachmentId, HttpServletRequest request)
        throws IOException {
    String byteUri = String.format(ATTACHMENT_BYTE, companyId, projectId, attachmentId);
    String attachmentUri = String.format(ATTACHMENT_ID, companyId, projectId, attachmentId);
    byte[] bytes = netService.getForObject(byteUri, byte[].class);
    AttachmentDTO attachment = netService.getForObject(attachmentUri, AttachmentDTO.class);
    if (attachment == null || bytes == null) {
        throw new com.onboard.frontend.exception.ResourceNotFoundException();
    }
    HttpHeaders header = new HttpHeaders();
    String filename = new String(attachment.getName().getBytes("GB2312"), "ISO_8859_1");
    header.setContentDispositionFormData("attachment", filename);
    return new HttpEntity<byte[]>(bytes, header);
}
 
Example #20
Source Project: spring-analysis-note   Author: Vip-Augus   File: RequestMappingHandlerAdapterIntegrationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void handleHttpEntity() throws Exception {
	Class<?>[] parameterTypes = new Class<?>[] {HttpEntity.class};

	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.setContent("Hello Server".getBytes("UTF-8"));

	HandlerMethod handlerMethod = handlerMethod("handleHttpEntity", parameterTypes);

	ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod);

	assertNull(mav);
	assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus());
	assertEquals("Handled requestBody=[Hello Server]", new String(response.getContentAsByteArray(), "UTF-8"));
	assertEquals("headerValue", response.getHeader("header"));
	// set because of @SesstionAttributes
	assertEquals("no-store", response.getHeader("Cache-Control"));
}
 
Example #21
Source Project: WeEvent   Author: WeBankFinTech   File: RestfulTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPublishContentIs10K() {
    MultiValueMap<String, String> eventData = new LinkedMultiValueMap<>();
    eventData.add("topic", this.topicName);
    eventData.add("content", get10KStr());

    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.APPLICATION_FORM_URLENCODED;
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(eventData, headers);
    ResponseEntity<SendResult> rsp = rest.postForEntity(url + "publish", request, SendResult.class);
    log.info("publish, status: " + rsp.getStatusCode() + " body: " + rsp.getBody());
    Assert.assertEquals(200, rsp.getStatusCodeValue());
    Assert.assertNotNull(rsp.getBody());
    Assert.assertTrue(rsp.getBody().getEventId().contains("-"));
}
 
Example #22
Source Project: java-technology-stack   Author: codeEngraver   File: RestTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void postForLocationEntityContentType() throws Exception {
	mockSentRequest(POST, "http://example.com");
	mockTextPlainHttpMessageConverter();
	mockResponseStatus(HttpStatus.OK);

	String helloWorld = "Hello World";
	HttpHeaders responseHeaders = new HttpHeaders();
	URI expected = new URI("http://example.com/hotels");
	responseHeaders.setLocation(expected);
	given(response.getHeaders()).willReturn(responseHeaders);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(MediaType.TEXT_PLAIN);
	HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);

	URI result = template.postForLocation("http://example.com", entity);
	assertEquals("Invalid POST result", expected, result);

	verify(response).close();
}
 
Example #23
Source Project: Moss   Author: SpringCloud   File: LetsChatNotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_onApplicationEvent_resolve_with_custom_message() {
    notifier.setMessage("TEST");
    StepVerifier.create(notifier.notify(
        new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown())))
                .verifyComplete();
    clearInvocations(restTemplate);

    StepVerifier.create(
        notifier.notify(new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofUp())))
                .verifyComplete();

    HttpEntity<?> expected = expectedMessage("TEST");
    verify(restTemplate).exchange(eq(URI.create(String.format("%s/rooms/%s/messages", host, room))),
        eq(HttpMethod.POST), eq(expected), eq(Void.class));
}
 
Example #24
Source Project: api-layer   Author: zowe   File: StaticAPIService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private HttpEntity<?> getHttpEntity(String discoveryServiceUrl) {
    boolean isHttp = discoveryServiceUrl.startsWith("http://");
    HttpHeaders httpHeaders = new HttpHeaders();
    if (isHttp) {
        String basicToken = "Basic " + Base64.getEncoder().encodeToString((eurekaUserid + ":" + eurekaPassword).getBytes());
        httpHeaders.add("Authorization", basicToken);
    }

    return new HttpEntity<>(null, httpHeaders);
}
 
Example #25
Source Project: java-technology-stack   Author: codeEngraver   File: HttpEntityArgumentResolverTests.java    License: MIT License 5 votes vote down vote up
@Test
public void httpEntityWithCompletableFutureBody() throws Exception {
	ServerWebExchange exchange = postExchange("line1");
	ResolvableType type = httpEntityType(CompletableFuture.class, String.class);
	HttpEntity<CompletableFuture<String>> httpEntity = resolveValue(exchange, type);

	assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
	assertEquals("line1", httpEntity.getBody().get());
}
 
Example #26
Source Project: taskana   Author: Taskana   File: WorkbasketControllerIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testMarkWorkbasketForDeletionAsBusinessAdminWithoutExplicitReadPermission() {

  String workbasketID = "WBI:100000000000000000000000000000000005";

  ResponseEntity<?> response =
      TEMPLATE.exchange(
          restHelper.toUrl(Mapping.URL_WORKBASKET_ID, workbasketID),
          HttpMethod.DELETE,
          new HttpEntity<>(restHelper.getHeadersBusinessAdmin()),
          Void.class);
  assertThat(response.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);
}
 
Example #27
Source Project: Mastering-Spring-5.0   Author: PacktPublishing   File: TodoControllerIT.java    License: MIT License 5 votes vote down vote up
@Test
public void retrieveTodos() throws Exception {
	String expected = "[" + "{id:1,user:Jack,desc:\"Learn Spring MVC\",done:false}" + ","
			+ "{id:2,user:Jack,desc:\"Learn Struts\",done:false}" + "]";
	
	ResponseEntity<String> response = template.exchange(
	           createUrl("/users/Jack/todos"), HttpMethod.GET,
	             new HttpEntity<String>(null, headers),
	               String.class);

	JSONAssert.assertEquals(expected, response.getBody(), false);
}
 
Example #28
Source Project: docs-manage   Author: yupaits   File: PostController.java    License: MIT License 5 votes vote down vote up
@PutMapping("/docs/{postId}")
public Result updatePost(@PathVariable Long postId, @RequestBody PostUpdate postUpdate) {
    String url = DocsConsts.DOCS_SERVER_HOST + "/docs/{postId}";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    HttpEntity<PostUpdate> entity = new HttpEntity<>(postUpdate, headers);
    return restTemplate.exchange(url, HttpMethod.PUT, entity, Result.class, postId).getBody();
}
 
Example #29
Source Project: zstack   Author: zstackio   File: SftpBackupStorageSimulator.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = SftpBackupStorageConstant.DOWNLOAD_IMAGE_PATH, method = RequestMethod.POST)
public
@ResponseBody
String download(HttpServletRequest req) throws InterruptedException {
    HttpEntity<String> entity = restf.httpServletRequestToHttpEntity(req);
    if (!config.downloadSuccess1) {
        throw new CloudRuntimeException("Fail download on purpose");
    } else {
        doDownload(entity);
    }
    return null;
}
 
Example #30
Source Project: java-technology-stack   Author: codeEngraver   File: HttpEntityMethodProcessorTests.java    License: MIT License 5 votes vote down vote up
@Test  // SPR-12861
public void resolveArgumentWithEmptyBody() throws Exception {
	this.servletRequest.setContent(new byte[0]);
	this.servletRequest.setContentType("application/json");

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(converters);

	HttpEntity<?> result = (HttpEntity<?>) processor.resolveArgument(this.paramSimpleBean,
			this.mavContainer, this.webRequest, this.binderFactory);

	assertNotNull(result);
	assertNull(result.getBody());
}