Java Code Examples for org.springframework.http.ResponseEntity#getBody()

The following examples show how to use org.springframework.http.ResponseEntity#getBody() . 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 File: BeerController.java    From spring-cloud-contract-samples with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.POST,
		value = "/beer",
		consumes = MediaType.APPLICATION_JSON_VALUE)
public String gimmeABeer(@RequestBody Person person) {
	//remove::start[]
	//tag::controller[]
	ResponseEntity<Response> response = this.restTemplate.exchange(
			RequestEntity
					.post(URI.create("http://localhost:" + this.port + "/check"))
					.contentType(MediaType.APPLICATION_JSON)
					.body(person),
			Response.class);
	switch (response.getBody().status) {
	case OK:
		return "THERE YOU GO";
	default:
		return "GET LOST";
	}
	//end::controller[]
	//remove::end[return]
}
 
Example 2
Source File: TaskControllerIntTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@Test
void should_ChangeValueOfModified_When_UpdatingTask() {

  ResponseEntity<TaskRepresentationModel> responseGet =
      template.exchange(
          restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000"),
          HttpMethod.GET,
          new HttpEntity<>(restHelper.getHeadersTeamlead_1()),
          TASK_MODEL_TYPE);

  final TaskRepresentationModel originalTask = responseGet.getBody();

  ResponseEntity<TaskRepresentationModel> responseUpdate =
      template.exchange(
          restHelper.toUrl(Mapping.URL_TASKS_ID, "TKI:100000000000000000000000000000000000"),
          HttpMethod.PUT,
          new HttpEntity<>(originalTask, restHelper.getHeadersTeamlead_1()),
          TASK_MODEL_TYPE);

  TaskRepresentationModel updatedTask = responseUpdate.getBody();
  assertThat(originalTask).isNotNull();
  assertThat(updatedTask).isNotNull();
  assertThat(originalTask.getModified()).isBefore(updatedTask.getModified());
}
 
Example 3
Source File: RestApiSecurityApplicationTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void testDmnRestApiIntegrationWithAuthentication() {
    String processDefinitionsUrl = "http://localhost:" + serverPort + "/dmn-api/dmn-repository/deployments";

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

    assertThat(response.getStatusCode())
        .as("Status code")
        .isEqualTo(HttpStatus.OK);
    DataResponse<DmnDeploymentResponse> deployments = response.getBody();
    assertThat(deployments).isNotNull();
    assertThat(deployments.getData())
        .isEmpty();
    assertThat(deployments.getTotal()).isZero();
}
 
Example 4
Source File: GrumpyBartenderController.java    From spring-cloud-contract-samples with Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "/grumpy", produces = MediaType.APPLICATION_JSON_VALUE)
GrumpyResponse grumpy(@RequestBody GrumpyPerson person) {
	//remove::start[]
	//tag::controller[]
	ResponseEntity<GrumpyBartenderResponse> response = this.restTemplate.exchange(
			RequestEntity
					.post(URI.create("http://localhost:" + this.port + "/buy"))
					.contentType(MediaType.APPLICATION_JSON)
					.body(person),
			GrumpyBartenderResponse.class);
	switch (response.getBody().status) {
	case OK:
		return new GrumpyResponse(response.getBody().message, "Enjoy!");
	default:
		return new GrumpyResponse(response.getBody().message, "Go to another bar");
	}
	//end::controller[]
	//remove::end[return]
}
 
Example 5
Source File: DefaultSkipperClient.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@Override
public Release scale(String releaseName, ScaleRequest scaleRequest) {
	ParameterizedTypeReference<Release> typeReference =
			new ParameterizedTypeReference<Release>() { };

	Map<String, String> uriVariables = new HashMap<String, String>();
	uriVariables.put("releaseName", releaseName);

	HttpEntity<ScaleRequest> httpEntity = new HttpEntity<>(scaleRequest);
	ResponseEntity<Release> resourceResponseEntity =
			restTemplate.exchange(baseUri + "/release/scale/{releaseName}",
					HttpMethod.POST,
					httpEntity,
					typeReference,
					uriVariables);
	return resourceResponseEntity.getBody();
}
 
Example 6
Source File: CustomerWebIntegrationTest.java    From microservice-consul with Apache License 2.0 6 votes vote down vote up
@Test
public void IsCustomerListReturned() {

	Iterable<Customer> customers = customerRepository.findAll();
	assertTrue(StreamSupport.stream(customers.spliterator(), false)
			.noneMatch(c -> (c.getName().equals("Hoeller1"))));
	ResponseEntity<String> resultEntity = restTemplate.getForEntity(
			customerURL() + "/list.html", String.class);
	assertTrue(resultEntity.getStatusCode().is2xxSuccessful());
	String customerList = resultEntity.getBody();
	assertFalse(customerList.contains("Hoeller1"));
	customerRepository.save(new Customer("Juergen", "Hoeller1",
			"[email protected]", "Schlossallee", "Linz"));

	customerList = restTemplate.getForObject(customerURL() + "/list.html",
			String.class);
	assertTrue(customerList.contains("Hoeller1"));

}
 
Example 7
Source File: PagingIterator.java    From booties with Apache License 2.0 6 votes vote down vote up
protected void fetchFromGithub() {
	if (next != null) {
		return;
	}
	if (uri == null) {
		return;
	}

	ResponseEntity<E> entity = getReponseEntity();
	List<String> headerValues = entity.getHeaders().get("Link");
	if (headerValues == null) {
		uri = null;
	} else {
		String first = headerValues.get(0);
		if (StringUtils.hasText(first)) {
			Optional<LinkRelation> linkRelation = linkRelationExtractor.extractLinkRelation(first, LinkRelation.NEXT);
			if (linkRelation.isPresent()) {
				uri = URI.create(linkRelation.get().getLink());
			}else{
				uri = null;
			}
		}
	}

	next = entity.getBody();
}
 
Example 8
Source File: HealthCheckTasklet.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private void checkJobExecuteStatus(ResponseEntity<Map> responseEntity, Map<String, Boolean> jobExecuteStatus) {
    Map<?, ?> responseData = responseEntity.getBody();
    List<?> runningJob = (List<?>)responseData.get("running");

    if (runningJob != null) {
        for (Object job : runningJob) {
            Map<?, ?> jobInfo = (Map<?, ?>)job;
            String jobName = (String) jobInfo.get("name");

            Boolean status = jobExecuteStatus.get(jobName);

            if (status != null) {
                jobExecuteStatus.put(jobName, true);
            }
        }
    }
}
 
Example 9
Source File: EndpointAutoConfigurationTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Test
public void mvcEndpoint() throws Throwable {

    AnnotationConfigEmbeddedWebApplicationContext applicationContext = 
        new AnnotationConfigEmbeddedWebApplicationContext(CallbackEmbeddedContainerCustomizer.class, EmbeddedContainerConfiguration.class, EndpointConfiguration.class);

    ProcessEngine processEngine = applicationContext.getBean(ProcessEngine.class);
    org.junit.Assert.assertNotNull("the processEngine should not be null", processEngine);

    ProcessEngineEndpoint processEngineEndpoint =
            applicationContext.getBean(ProcessEngineEndpoint.class);
    org.junit.Assert.assertNotNull("the processEngineEndpoint should not be null", processEngineEndpoint);

    RestTemplate restTemplate = applicationContext.getBean(RestTemplate.class);

    ResponseEntity<Map> mapResponseEntity =
            restTemplate.getForEntity("http://localhost:9091/activiti/", Map.class);

    Map map = mapResponseEntity.getBody();

    String[] criticalKeys = {"completedTaskCount", "openTaskCount", "cachedProcessDefinitionCount"};

    Map<?, ?> invokedResults = processEngineEndpoint.invoke();
    for (String k : criticalKeys) {
        org.junit.Assert.assertTrue(map.containsKey(k));
        org.junit.Assert.assertEquals(((Number) map.get(k)).longValue(), ((Number) invokedResults.get(k)).longValue());
    }
}
 
Example 10
Source File: LoanApplicationService.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private FraudServiceResponse sendRequestToFraudDetectionService(
		FraudServiceRequest request) {
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.add(HttpHeaders.CONTENT_TYPE, FRAUD_SERVICE_JSON_VERSION_1);

	// tag::client_call_server[]
	ResponseEntity<FraudServiceResponse> response = restTemplate.exchange(
			"http://localhost:" + getPort() + "/fraudcheck", HttpMethod.PUT,
			new HttpEntity<>(request, httpHeaders), FraudServiceResponse.class);
	// end::client_call_server[]

	return response.getBody();
}
 
Example 11
Source File: CustomSwaggerConnectorITCase.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateCustomConnectorInfoForUploadedSwagger() throws IOException {
    final ConnectorSettings connectorSettings = new ConnectorSettings.Builder().connectorTemplateId(TEMPLATE_ID).build();

    final ResponseEntity<Connector> response = post("/api/v1/connectors/custom",
        multipartBodyForInfo(connectorSettings, getClass().getResourceAsStream("/io/syndesis/server/runtime/test-swagger.json")),
        Connector.class, tokenRule.validToken(), HttpStatus.OK, multipartHeaders());

    final Connector got = response.getBody();

    assertThat(got).isNotNull();
}
 
Example 12
Source File: CustomerWebIntegrationTest.java    From microservice-consul with Apache License 2.0 5 votes vote down vote up
private <T> T getForMediaType(Class<T> value, MediaType mediaType,
		String url) {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Arrays.asList(mediaType));

	HttpEntity<String> entity = new HttpEntity<String>("parameters",
			headers);

	ResponseEntity<T> resultEntity = restTemplate.exchange(url,
			HttpMethod.GET, entity, value);

	return resultEntity.getBody();
}
 
Example 13
Source File: RestTemplateApiTest.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
@Test
public void testExchangeWithRequestEntityForPostWithRequestParam_Map_Header() {
    //因为post请求有请求体application/x-www-form-urlencoded,RequestParam需要拼到url字符串中,
    // 因为postForEntity中没有urlVariables,只有uriVariables,因此RequestParam只能放到request中的form请求体中
    String userId = "1";
    int pageId = 0;
    int pageSize = 10;
    String auth = "secret In Header";
    Result excepted = new Result(userId, pageId, pageSize, auth);

    String url = domain + "/" + userId + "/auth";//userId是uriVariables;?pageId={pageId}&pageSize={pageSize}不是uri,需要放在request请求体中

    //Header只能使用MultiValueMap类型
    MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
    header.add("auth", auth);

    //如果给定一个MultiValueMap<String,String>,
    // 那么这个Map中的值将会被FormHttpMessageConverter以"application/x-www-form-urlencoded"的格式写到请求体中
    //java.util.Map中存放的数据,不会放到request请求的请求体中,只能是org.springframework.util.MultiValueMap
    MultiValueMap<String, Integer> body = new LinkedMultiValueMap<>();
    body.add("pageId", pageId);
    body.add("pageSize", pageSize);

    //RequestEntity中只有有body,header,PathVariable这种参数,就只能自己拼字符串喽
    RequestEntity<MultiValueMap<String, Integer>> requestEntity = new RequestEntity<>(body, header, HttpMethod.POST, URI.create(url));
    ResponseEntity<Result> forEntity = restTemplate.exchange(requestEntity, Result.class);
    Result actual = forEntity.getBody();
    assertThat(actual, is(excepted));
}
 
Example 14
Source File: BarClient.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Bar create(Bar object) throws JsonProcessingException {
    HttpEntity<String> entity = getJsonEntity(new NewBar(object));
    ResponseEntity<Bar> responseEntity = restTemplate.postForEntity(getUrl("bars"), entity, Bar.class);

    return responseEntity.getBody();
}
 
Example 15
Source File: HelloController.java    From Mastering-Distributed-Tracing with MIT License 4 votes vote down vote up
private Person getPerson(String name) {
    String url = "http://localhost:8081/getPerson/" + name;
    ResponseEntity<Person> response = restTemplate.getForEntity(url, Person.class);
    return response.getBody();
}
 
Example 16
Source File: SpringRESTClientConnector.java    From egeria with Apache License 2.0 4 votes vote down vote up
/**
 * Issue a PUT REST call that returns a response object. This is typically an update.
 *
 * @param <T> type of the return object
 * @param methodName  name of the method being called.
 * @param returnClass class of the response object.
 * @param urlTemplate  template of the URL for the REST API call with place-holders for the parameters.
 * @param requestBody request body for the request.
 * @param params  a list of parameters that are slotted into the url template.
 *
 * @return Object
 * @throws RESTServerException something went wrong with the REST call stack.
 */
public  <T> T callPutRESTCall(String    methodName,
                               Class<T>  returnClass,
                               String    urlTemplate,
                               Object    requestBody,
                               Object... params) throws RESTServerException
{
    try
    {
        log.debug("Calling " + methodName + " with URL template " + urlTemplate + " and parameters " + Arrays.toString(params) + ".");

        HttpEntity<?> request = new HttpEntity<>(requestBody);

        if (requestBody == null)
        {
            // continue with a null body, we may want to fail this request here in the future.
            log.warn("Poorly formed PUT call made by " + methodName);
        }
        if (basicAuthorizationHeader != null)
        {
                request = new HttpEntity<>(requestBody, basicAuthorizationHeader);
        }

        ResponseEntity<T> responseEntity = restTemplate.exchange(urlTemplate, HttpMethod.PUT, request, returnClass, params);
        T responseObject = responseEntity.getBody();

        if (responseObject != null)
        {
            log.debug("Returning from " + methodName + " with response object " + responseObject.toString() + ".");
        }
        else
        {
            log.debug("Returning from " + methodName + " with no response object.");
        }

        return responseObject;
    }
    catch (Throwable error)
    {
        log.debug("Exception " + error.getClass().getName() + " with message " + error.getMessage() + " occurred during REST call for " + methodName + ".");

        RESTClientConnectorErrorCode errorCode = RESTClientConnectorErrorCode.CLIENT_SIDE_REST_API_ERROR;
        String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(error.getClass().getName(),
                                                                                                 methodName,
                                                                                                 urlTemplate,
                                                                                                 serverName,
                                                                                                 serverPlatformURLRoot,
                                                                                                 error.getMessage());

        throw new RESTServerException(errorCode.getHTTPErrorCode(),
                                      this.getClass().getName(),
                                      methodName,
                                      errorMessage,
                                      errorCode.getSystemAction(),
                                      errorCode.getUserAction(),
                                      error);
    }
}
 
Example 17
Source File: UserService.java    From DBus with Apache License 2.0 4 votes vote down vote up
public ResultEntity updateUser(User user) {
    ResponseEntity<ResultEntity> result = sender.post(MS_SERVICE, "/users/update/" + user.getId(), user);
    return result.getBody();
}
 
Example 18
Source File: ProjectTopologyService.java    From DBus with Apache License 2.0 4 votes vote down vote up
public ResultEntity queryOutPutTopics(Integer projectId, Integer topoId) {
    ResponseEntity<ResultEntity> result = sender.get(ServiceNames.KEEPER_SERVICE, "/project-topos/out-topics/{0}/{1}", StringUtils.EMPTY, projectId, topoId);
    return result.getBody();
}
 
Example 19
Source File: AbstractRetryTest.java    From resilience4j-spring-boot2-demo with Apache License 2.0 4 votes vote down vote up
protected void checkMetrics(String kind, String backend, float count) {
    ResponseEntity<String> metricsResponse = restTemplate.getForEntity("/actuator/prometheus", String.class);
    assertThat(metricsResponse.getBody()).isNotNull();
    String response = metricsResponse.getBody();
    assertThat(response).contains(getMetricName(kind, backend) + String.format("%.1f", count));
}
 
Example 20
Source File: TableService.java    From DBus with Apache License 2.0 4 votes vote down vote up
public ResultEntity findAllTables(String queryString) {
    ResponseEntity<ResultEntity> result = sender.get(ServiceNames.KEEPER_SERVICE, "/tables/findAll", queryString);
    return result.getBody();
}