Example usage for org.springframework.http HttpEntity getBody

List of usage examples for org.springframework.http HttpEntity getBody

Introduction

In this page you can find the example usage for org.springframework.http HttpEntity getBody.

Prototype

@Nullable
public T getBody() 

Source Link

Document

Returns the body of this entity.

Usage

From source file:com.jci.po.service.PoServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from  www  . ja v a 2 s  . c  o m
public BatchUpdateRes processErrorPos(PoDetailsReq request)
        throws InvalidKeyException, URISyntaxException, StorageException {

    LOG.info("starting processErrorPos request--->" + request);
    BatchUpdateRes res = new BatchUpdateRes();
    String partitionKey = AzureUtils.getPoPartitionKey(request.getErpName());
    BatchUpdateRes response = new BatchUpdateRes();

    if (StringUtils.isBlank(partitionKey)) {
        res.setError(true);
        res.setMessage("Invalid request parameters !");
        return res;
    }

    List<String> poList = request.getPoNo();
    if (poList == null || poList.size() < 1) {
        res.setError(true);
        res.setMessage("Invalid request parameters !");
        return res;
    }

    List<ServiceInstance> ffmsInstanceList = discoveryClient.getInstances(ffgenerationMSName);
    ServiceInstance ffmsInstance = ffmsInstanceList.get(0);
    LOG.info("Before calling from Flat File Generation Service: " + "http://"
            + ffmsInstance.getServiceId().toLowerCase() + ":" + Integer.toString(ffmsInstance.getPort())
            + poPostURLResource + "?userName=" + request.getUserName() + "&globalId=" + request.getGlobalId()
            + "&comment=" + request.getComment());

    // start new
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/json");

    /*
     * Map<String, String> params = new HashMap<String, String>();
     * params.put("userName", request.getUserName()); params.put("globalId",
     * request.getGlobalId()); params.put("comment", request.getComment());
     */

    HttpEntity entity = new HttpEntity(poList, headers);

    /*
     * HttpEntity<HashMap<String, String>> ffResponse =
     * restTemplate.exchange(
     * "http://api-gateway:8765/ffgenerator-service/postPOError",
     * HttpMethod.POST, entity, new
     * ParameterizedTypeReference<HashMap<String, String>>() { });
     */
    /*
     * HttpEntity<HashMap<String, String>> ffResponse =
     * restTemplate.exchange(
     * "http://ffgenerator-service:9200/postPOError?userName=" +
     * request.getUserName() + "&globalId=" + request.getGlobalId() +
     * "&comment=" + request.getComment(), HttpMethod.POST, entity, new
     * ParameterizedTypeReference<HashMap<String, String>>() { });
     */
    HttpEntity<FlatFileRes> ffResponse = restTemplate.exchange(
            "http://" + ffmsInstance.getServiceId().toLowerCase() + ":"
                    + Integer.toString(ffmsInstance.getPort()) + poPostURLResource + "?userName="
                    + request.getUserName() + "&globalId=" + request.getGlobalId() + "&comment="
                    + request.getComment(),
            HttpMethod.POST, entity, new ParameterizedTypeReference<FlatFileRes>() {
            });

    // client.processErrorPosFlatFiles(poList);
    FlatFileRes ffPos = ffResponse.getBody();

    /*// Update status in DB
    boolean isUpdated = updateStatus(pkToSuccessList, request.getGlobalId(), request.getUserName(),
    request.getComment());*/
    response = new BatchUpdateRes();
    response.setGraphData(repo.getGraphData());
    response.setSuccessList(ffPos.getSuccessList());
    response.setErrorList(ffPos.getErrorList());
    return response;
}

From source file:edu.harvard.i2b2.fhir.FetchInterceptor.java

void alterResponse(HttpServletResponse response, String path) throws IOException {
    ourLog.info("altering response");

    RestTemplate restTemplate = new MyGlobal().getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/json");

    HttpEntity entity = new HttpEntity(headers);
    Map<String, String> params = new HashMap<String, String>();
    String url = "http://localhost:8080/fhirRest/" + path;
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    HttpEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET,
            entity, String.class);
    String responseTxt = responseEntity.getBody();
    response.getWriter().println(responseTxt);

}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

protected ResponseEntity<byte[]> passthru(HttpServletRequest request, HttpEntity entity,
        Map<String, Object> model, boolean loginClientRequired) throws Exception {

    String path = extractPath(request);

    RestOperations template = loginClientRequired ? getAuthorizationTemplate() : getDefaultTemplate();
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.putAll(getRequestHeaders(entity.getHeaders()));
    requestHeaders.remove(COOKIE);//from  w  w w  .  j  a  v  a  2s . c  om
    requestHeaders.remove(COOKIE.toLowerCase());
    // Get back end cookie if saved in session
    String cookie = (String) model.get(COOKIE_MODEL);
    if (cookie != null) {
        logger.debug("Found back end cookies: " + cookie);
        for (String value : cookie.split(";")) {
            requestHeaders.add(COOKIE, value);
        }
    }

    ResponseEntity<byte[]> response = template.exchange(getUaaBaseUrl() + "/" + path,
            HttpMethod.valueOf(request.getMethod()), new HttpEntity(entity.getBody(), requestHeaders),
            byte[].class);
    HttpHeaders outgoingHeaders = getResponseHeaders(response.getHeaders());
    return new ResponseEntity<byte[]>(response.getBody(), outgoingHeaders, response.getStatusCode());

}

From source file:org.cruk.genologics.api.debugging.RestClientSnoopingAspect.java

/**
 * Join point for the rest template's {@code exchange} operations.
 * Logs the XML being sent and the reply received.
 *
 * @param pjp The AspectJ join point object.
 *
 * @return The reply object.// ww  w .  j  a  v  a2 s  . c o m
 *
 * @throws Throwable if there is any failure from the operation.
 * This is also logged if logging is set to DEBUG.
 *
 * @see RestTemplate#exchange(java.net.URI, HttpMethod, HttpEntity, Class)
 */
public Object checkExchange(ProceedingJoinPoint pjp) throws Throwable {
    Object uri = pjp.getArgs()[0];
    HttpMethod method = (HttpMethod) pjp.getArgs()[1];
    HttpEntity<?> entity = (HttpEntity<?>) pjp.getArgs()[2];
    Object request = entity.getBody();

    if (logger.isDebugEnabled()) {
        logger.debug("Calling {} via {} to {}", pjp.getSignature().getName(), method, uri);

        displayBefore(request);
    }

    try {
        Object reply = pjp.proceed();

        if (logger.isDebugEnabled()) {
            displayAfter(reply);
        }

        return reply;
    } catch (Throwable e) {
        fail(e);
        throw e;
    }
}

From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java

/**
 * Upload a file to the Genologics file store. This always uses the HTTP
 * protocol with the {@code file/id/upload} end point.
 *
 * @param fileURLResource The URL resource of the file on the local machine.
 * @param targetFile The GenologicsFile object that holds the reference to the
 * uploaded file, which was newly created using the API.
 *
 * @throws GenologicsException if the server reports a problem with the upload.
 * @throws IllegalStateException if {@code targetFile} does not have a LIMS id.
 * @throws IOException if there is a problem with the transfer.
 */// ww  w .ja  va 2  s.  c  o m
protected void uploadViaHTTP(URLInputStreamResource fileURLResource, GenologicsFile targetFile)
        throws IOException {
    GenologicsEntity entityAnno = checkEntityAnnotated(GenologicsFile.class);

    if (targetFile.getLimsid() == null) {
        // Need to post the file back to the LIMS to obtain a URI and LIMS
        // id for the file object.

        String filesUrl = getServerApiAddress() + entityAnno.uriSection();

        ResponseEntity<GenologicsFile> response = restClient.postForEntity(filesUrl, targetFile,
                GenologicsFile.class);

        reflectiveUpdate(targetFile, response.getBody());

        assert targetFile.getLimsid() != null : "Still no LIMS id on GenologicsFile object.";
    }

    boolean uploadedOk = false;
    try {
        URI uploadURI;
        try {
            uploadURI = new URI(
                    getServerApiAddress() + entityAnno.uriSection() + "/" + targetFile.getLimsid() + "/upload");
        } catch (URISyntaxException e) {
            throw new IOException(
                    "File LIMS id " + targetFile.getLimsid() + " produces an invalid URI for upload.", e);
        }

        logger.info("Uploading {} over {} to {} on {}", fileURLResource.getURL().getPath(),
                uploadURI.getScheme().toUpperCase(), targetFile.getContentLocation().getPath(),
                targetFile.getContentLocation().getHost());

        HttpEntity<MultiValueMap<String, Resource>> requestEntity = new HttpEntity<MultiValueMap<String, Resource>>(
                new LinkedMultiValueMap<String, Resource>(1));

        requestEntity.getBody().add("file", fileURLResource);

        ResponseEntity<String> uploadEntity = fileUploadClient.exchange(uploadURI, HttpMethod.POST,
                requestEntity, String.class);

        uploadedOk = true;

        if (logger.isDebugEnabled()) {
            if (uploadEntity.hasBody()) {
                logger.debug("Upload of file returned a {}: {}",
                        ClassUtils.getShortClassName(uploadEntity.getBody().getClass()),
                        uploadEntity.getBody());
            } else {
                logger.debug("Upload of file succeeded but returned nothing.");
            }
        }
    } finally {
        if (!uploadedOk) {
            try {
                delete(targetFile);
            } catch (Exception e) {
                logger.warn("Failed to clean up GenologicsFile object {} after upload failure:",
                        targetFile.getLimsid(), e);
            }
        }
    }

    if (!uploadedOk) {
        // I don't think the code can get here as other exceptions should
        // have been thrown. To make sure though...

        throw new GenologicsUpdateException("Failed to upload " + fileURLResource.getURL());
    }
}

From source file:org.infoscoop.api.oauth2.provider.ISOAuth2ExceptionRenderer.java

public void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest)
        throws Exception {
    if (responseEntity == null) {
        return;/*from   www  .ja v a2 s . c  o  m*/
    }
    HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
    HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
    HttpStatus statusCode = null;
    if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) {
        statusCode = ((ResponseEntity<?>) responseEntity).getStatusCode();
        ((ServerHttpResponse) outputMessage).setStatusCode(statusCode);
    }
    HttpHeaders entityHeaders = responseEntity.getHeaders();
    if (!entityHeaders.isEmpty()) {
        outputMessage.getHeaders().putAll(entityHeaders);
    }
    Object body = responseEntity.getBody();
    if (body != null) {
        writeWithMessageConverters(body, inputMessage, outputMessage, statusCode, webRequest.getRequest());
    } else {
        // flush headers
        outputMessage.getBody();
    }
}

From source file:org.jasig.portlet.courses.dao.xml.HttpClientCoursesDaoImpl.java

protected TermsAndCourses getTermsAndCourses(CoursesCacheKey key, String url) {
    Map<String, String> params = key.getParams();

    if (log.isDebugEnabled()) {
        log.debug("Invoking uri '" + url + "' with the following parameters:  " + params.toString());
    }/*from w w w  .  j a  va2  s .co m*/

    HttpEntity<?> requestEntity = getRequestEntity(key);
    HttpEntity<TermsAndCourses> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity,
            TermsAndCourses.class, params);

    final TermsAndCourses termsAndCourses = response.getBody();
    return termsAndCourses;
}

From source file:org.jgrades.rest.client.StatefullRestTemplate.java

private Object insertCookieToHeaderIfApplicable(Object requestBody) {
    HttpEntity<?> httpEntity;

    if (requestBody instanceof HttpEntity) {
        httpEntity = (HttpEntity<?>) requestBody;
    } else if (requestBody != null) {
        httpEntity = new HttpEntity<Object>(requestBody);
    } else {/*  ww  w  . j av  a2s . c  om*/
        httpEntity = HttpEntity.EMPTY;
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.putAll(httpEntity.getHeaders());

    httpHeaders.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    if (httpHeaders.getContentType() == null) {
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    }

    if (StringUtils.isNotEmpty(cookie)) {
        httpHeaders.add("Cookie", cookie);
    }

    return new HttpEntity<>(httpEntity.getBody(), httpHeaders);
}

From source file:org.springframework.http.converter.FormHttpMessageConverter.java

@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
    Object partBody = partEntity.getBody();
    if (partBody == null) {
        throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
    }//w ww  .j a v  a 2  s.  c  om
    Class<?> partType = partBody.getClass();
    HttpHeaders partHeaders = partEntity.getHeaders();
    MediaType partContentType = partHeaders.getContentType();
    for (HttpMessageConverter<?> messageConverter : this.partConverters) {
        if (messageConverter.canWrite(partType, partContentType)) {
            Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
            HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
            multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
            if (!partHeaders.isEmpty()) {
                multipartMessage.getHeaders().putAll(partHeaders);
            }
            ((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType,
                    multipartMessage);
            return;
        }
    }
    throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter "
            + "found for request type [" + partType.getName() + "]");
}