Example usage for org.springframework.http.client ClientHttpResponse getBody

List of usage examples for org.springframework.http.client ClientHttpResponse getBody

Introduction

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

Prototype

InputStream getBody() throws IOException;

Source Link

Document

Return the body of the message as an input stream.

Usage

From source file:org.fao.geonet.api.mapservers.GeoServerRest.java

/**
 * @param method      e.g. 'POST', 'GET', 'PUT' or 'DELETE'
 * @param urlParams   REST API parameter
 * @param postData    XML data//w w  w  .  j  a v  a  2  s .c o  m
 * @param file        File to upload
 * @param contentType type of content in case of post data or file updload.
 */
public @CheckReturnValue int sendREST(String method, String urlParams, String postData, Path file,
        String contentType, Boolean saveResponse) throws IOException {

    response = "";
    String url = this.restUrl + urlParams;
    if (Log.isDebugEnabled(LOGGER_NAME)) {
        Log.debug(LOGGER_NAME, "url:" + url);
        Log.debug(LOGGER_NAME, "method:" + method);
        if (postData != null)
            Log.debug(LOGGER_NAME, "postData:" + postData);
    }

    HttpRequestBase m;
    if (method.equals(METHOD_PUT)) {
        m = new HttpPut(url);
        if (file != null) {
            ((HttpPut) m)
                    .setEntity(new PathHttpEntity(file, ContentType.create(contentType, Constants.ENCODING)));
        }

        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPut) m).setEntity(entity);
        }
    } else if (method.equals(METHOD_DELETE)) {
        m = new HttpDelete(url);
    } else if (method.equals(METHOD_POST)) {
        m = new HttpPost(url);
        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPost) m).setEntity(entity);
        }
    } else {
        m = new HttpGet(url);
    }

    if (contentType != null && !"".equals(contentType)) {
        m.setHeader("Content-type", contentType);
    }

    m.setConfig(RequestConfig.custom().setAuthenticationEnabled(true).build());

    // apparently this is needed to preemptively send the auth, for servers that dont require it but
    // dont send the same data if you're authenticated or not.
    try {
        m.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), m));
    } catch (AuthenticationException a) {
        Log.warning(LOGGER_NAME, "Failed to add the authentication Header, error is: " + a.getMessage());
    }
    ;

    final ClientHttpResponse httpResponse = factory.execute(m,
            new UsernamePasswordCredentials(username, password), AuthScope.ANY);

    try {
        status = httpResponse.getRawStatusCode();
        if (Log.isDebugEnabled(LOGGER_NAME)) {
            Log.debug(LOGGER_NAME, "status:" + status);
        }
        if (saveResponse) {
            this.response = IOUtils.toString(httpResponse.getBody());
        }
    } finally {
        httpResponse.close();
    }

    return status;
}

From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java

@SuppressWarnings("deprecation")
private RestTemplate setErrorHandler(final RestTemplate restTemplate) {
    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        private final Set<HttpStatus> errorStatuses = new HashSet<>();

        /* non-static */ {
            errorStatuses.add(HttpStatus.BAD_REQUEST);
            errorStatuses.add(HttpStatus.UNAUTHORIZED);
            errorStatuses.add(HttpStatus.FORBIDDEN);
            errorStatuses.add(HttpStatus.NOT_FOUND);
            errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED);
            errorStatuses.add(HttpStatus.NOT_ACCEPTABLE);
            errorStatuses.add(HttpStatus.REQUEST_TIMEOUT);
            errorStatuses.add(HttpStatus.CONFLICT);
            errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE);
            errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG);
            errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
            errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS);
            errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR);
            errorStatuses.add(HttpStatus.NOT_IMPLEMENTED);
            errorStatuses.add(HttpStatus.BAD_GATEWAY);
            errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE);
        }//from  w ww . j  a  va  2 s . c o  m

        @Override
        public boolean hasError(final ClientHttpResponse response) throws IOException {
            return errorStatuses.contains(response.getStatusCode());
        }

        @Override
        public void handleError(final ClientHttpResponse response) throws IOException {
            System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText());
            System.err.println(readBody(response));
        }

        private String readBody(final ClientHttpResponse response) throws IOException {
            BufferedReader responseBodyReader = null;

            try {
                responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody()));

                StringBuilder buffer = new StringBuilder();
                String line;

                while ((line = responseBodyReader.readLine()) != null) {
                    buffer.append(line).append(System.getProperty("line.separator"));
                }

                return buffer.toString().trim();
            } finally {
                FileSystemUtils.close(responseBodyReader);
            }
        }
    });

    return restTemplate;
}

From source file:org.fao.geonet.api.records.formatters.FormatterApi.java

private String getXmlFromUrl(ServiceContext context, String lang, String url, WebRequest request)
        throws IOException, URISyntaxException {
    String adjustedUrl = url;//from  w  w w .j av  a2s.  com
    if (!url.startsWith("http")) {
        adjustedUrl = context.getBean(SettingManager.class).getSiteURL(lang) + url;
    } else {
        final URI uri = new URI(url);
        Set allowedRemoteHosts = context.getApplicationContext().getBean("formatterRemoteFormatAllowedHosts",
                Set.class);
        Assert.isTrue(allowedRemoteHosts.contains(uri.getHost()),
                "xml.format is not allowed to make requests to " + uri.getHost());
    }

    HttpUriRequest getXmlRequest = new HttpGet(adjustedUrl);
    final Iterator<String> headerNames = request.getHeaderNames();
    while (headerNames.hasNext()) {
        String headerName = headerNames.next();
        final String[] headers = request.getHeaderValues(headerName);
        for (String header : headers) {
            getXmlRequest.addHeader(headerName, header);
        }
    }

    GeonetHttpRequestFactory requestFactory = context.getBean(GeonetHttpRequestFactory.class);
    final ClientHttpResponse execute = requestFactory.execute(getXmlRequest);
    if (execute.getRawStatusCode() != 200) {
        throw new IllegalArgumentException("Request " + adjustedUrl + " did not succeed.  Response Status: "
                + execute.getStatusCode() + ", status text: " + execute.getStatusText());
    }
    return new String(ByteStreams.toByteArray(execute.getBody()), Constants.CHARSET);
}

From source file:com.netflix.genie.web.controllers.JobRestController.java

/**
 * Get the job output directory./*www  . j  a  v  a 2 s .  co  m*/
 *
 * @param id            The id of the job to get output for
 * @param forwardedFrom The host this request was forwarded from if present
 * @param request       the servlet request
 * @param response      the servlet response
 * @throws IOException      on redirect error
 * @throws ServletException when trying to handle the request
 * @throws GenieException   on any Genie internal error
 */
@RequestMapping(value = { "/{id}/output", "/{id}/output/",
        "/{id}/output/**" }, method = RequestMethod.GET, produces = MediaType.ALL_VALUE)
public void getJobOutput(@PathVariable("id") final String id,
        @RequestHeader(name = JobConstants.GENIE_FORWARDED_FROM_HEADER, required = false) final String forwardedFrom,
        final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException, GenieException {
    log.info("[getJobOutput] Called for job with id: {}", id);

    // if forwarded from isn't null it's already been forwarded to this node. Assume data is on this node.
    if (this.jobsProperties.getForwarding().isEnabled() && forwardedFrom == null) {
        // TODO: It's possible that could use the JobMonitorCoordinator to check this in memory
        //       However that could get into problems where the job finished or died
        //       and it would return false on check if the job with given id is running on that node
        final String jobHostname = this.jobSearchService.getJobHost(id);
        if (!this.hostName.equals(jobHostname)) {
            log.info("Job {} is not or was not run on this node. Forwarding to {}", id, jobHostname);
            final String forwardUrl = buildForwardURL(request, jobHostname);
            try {
                this.restTemplate.execute(forwardUrl, HttpMethod.GET,
                        forwardRequest -> copyRequestHeaders(request, forwardRequest),
                        new ResponseExtractor<Void>() {
                            @Override
                            public Void extractData(final ClientHttpResponse forwardResponse)
                                    throws IOException {
                                response.setStatus(HttpStatus.OK.value());
                                copyResponseHeaders(response, forwardResponse);
                                // Documentation I could find pointed to the HttpEntity reading the bytes off
                                // the stream so this should resolve memory problems if the file returned is large
                                ByteStreams.copy(forwardResponse.getBody(), response.getOutputStream());
                                return null;
                            }
                        });
            } catch (HttpStatusCodeException e) {
                log.error("Failed getting the remote job output from {}. Error: {}", forwardUrl,
                        e.getMessage());
                response.sendError(e.getStatusCode().value(), e.getStatusText());
            } catch (Exception e) {
                log.error("Failed getting the remote job output from {}. Error: {}", forwardUrl,
                        e.getMessage());
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
            }

            //No need to search on this node
            return;
        }
    }

    log.info("Job {} is running or was run on this node. Fetching requested resource...", id);
    final String path = ControllerUtils.getRemainingPath(request);
    if (StringUtils.isNotBlank(path)) {
        request.setAttribute(GenieResourceHttpRequestHandler.GENIE_JOB_IS_ROOT_DIRECTORY, false);
    } else {
        request.setAttribute(GenieResourceHttpRequestHandler.GENIE_JOB_IS_ROOT_DIRECTORY, true);
    }
    log.debug("PATH = {}", path);
    request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, id + "/" + path);

    this.resourceHttpRequestHandler.handleRequest(request, response);
}

From source file:org.springframework.social.soundcloud.api.impl.SoundCloudErrorHandler.java

@SuppressWarnings("unchecked")
private List<Map<String, String>> extractErrorDetailsFromResponse(ClientHttpResponse response)
        throws IOException {

    ObjectMapper mapper = new ObjectMapper(new JsonFactory());

    List<String> authenticateHeaders = response.getHeaders().get("Www-Authenticate");
    String authenticateHeader = authenticateHeaders == null || authenticateHeaders.size() == 0 ? null
            : authenticateHeaders.get(0);
    String json = null;//from  ww  w.  ja  v a 2 s.  c om
    if (authenticateHeader != null) {
        json = "{" + authenticateHeader.replace('=', ':').replace("OAuth realm", "\"OAuth realm\"")
                .replace("error", "\"error\"") + "}";
        try {
            Map<String, String> responseMap = mapper.<Map<String, String>>readValue(json,
                    new TypeReference<Map<String, String>>() {
                    });
            List<Map<String, String>> errorsList = new ArrayList<Map<String, String>>();
            if (responseMap.containsKey("error")) {
                Map<String, String> errorMap = new HashMap<String, String>();
                errorMap.put("error_message", responseMap.get("error"));
                errorsList.add(errorMap);
                return errorsList;
            }

        } catch (JsonParseException e) {
            return null;
        }
    } else {
        json = readFully(response.getBody());
        try {
            Map<String, Object> responseMap = mapper.<Map<String, Object>>readValue(json,
                    new TypeReference<Map<String, Object>>() {
                    });
            if (responseMap.containsKey("errors")) {
                return (List<Map<String, String>>) responseMap.get("errors");
            } else {
                return null;
            }
        } catch (JsonParseException e) {
            return null;
        }
    }
    return null;

}

From source file:com.jaspersoft.android.sdk.client.JsRestClient.java

protected int copyResponseToFile(ClientHttpResponse response, File file) throws IOException {
    File parentFolder = file.getParentFile();
    if (parentFolder != null && !parentFolder.exists() && !parentFolder.mkdirs()) {
        throw new IllegalStateException("Unable to create folder: " + parentFolder);
    }//ww  w. j  a va2  s.c  o  m
    return FileCopyUtils.copy(response.getBody(), new FileOutputStream(file));
}

From source file:de.zib.gndms.gndmc.test.gorfx.ESGFGet.java

@Override
protected void run() throws Exception {

    SetupSSL setupSSL = new SetupSSL();
    setupSSL.setKeyStoreLocation(keyStoreLocation);
    setupSSL.prepareKeyStore(passwd, passwd);
    setupSSL.setupDefaultSSLContext(passwd);

    final RestTemplate rt = new RestTemplate();

    rt.execute(url, HttpMethod.GET, null, new ResponseExtractor<Object>() {
        @Override//from  ww w  .  j a  v a 2  s  . c  o m
        public Object extractData(final ClientHttpResponse response) throws IOException {

            String url = null;
            String cookieTmp = null;
            System.out.println(response.getStatusCode().toString());
            for (String s : response.getHeaders().keySet())
                for (String v : response.getHeaders().get(s)) {
                    System.out.println(s + ":" + v);
                    if ("Location".equals(s))
                        url = v;
                    else if ("Set-Cookie".equals(s))
                        cookieTmp = v;
                }
            final String cookie = cookieTmp.split(";")[0];

            if (url != null)
                rt.execute(decodeUrl(url), HttpMethod.GET, new RequestCallback() {
                    @Override
                    public void doWithRequest(final ClientHttpRequest request) throws IOException {

                        System.out.println("setting cookie: " + cookie);
                        request.getHeaders().set("Cookie", cookie);
                    }
                }, new ResponseExtractor<Object>() {
                    @Override
                    public Object extractData(final ClientHttpResponse response) throws IOException {

                        System.out.println(response.getStatusCode().toString());
                        System.out.println("Received data, copying");
                        InputStream is = response.getBody();
                        OutputStream os = new FileOutputStream(off);
                        StreamCopyNIO.copyStream(is, os);
                        System.out.println("Done");
                        return null;
                    }
                });

            return null;
        }
    });
}