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

The following examples show how to use org.springframework.http.client.ClientHttpResponse#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: SpringRestDataProviderEngine.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
    String result;
    try (InputStream body = response.getBody()) {
        result = IOUtils.toString(body, StandardCharsets.UTF_8);
    }
    Object data = null;
    if (result != null && !result.isEmpty()) {
        result = result.trim();
        if (result.startsWith("["))
            data = mapper.<List<DataSet>>readValue(result, mapper.getTypeFactory().constructCollectionType(List.class, DataSet.class));
        else if (result.startsWith("{"))
            data = mapper.readValue(result, DataSet.class);
        else
            data = mapper.readValue(result, Object.class);
    }
    return data;
}
 
Example 2
Source File: ArtifactDownloader.java    From steady with Apache License 2.0 6 votes vote down vote up
@Override
public Path extractData(ClientHttpResponse response) throws IOException {
	// In case of 200, write the bytes to disk
	if(response.getStatusCode().equals(HttpStatus.OK)) {
		try(final FileOutputStream fos = new FileOutputStream(this.file.toFile())){
			byte[] bytes = new byte[1024];
			int buffer_length = 0;
			try(final BufferedInputStream is = new BufferedInputStream(response.getBody())){ 
				while( (buffer_length=is.read(bytes, 0, 1024)) > 0 ) {
					fos.write(bytes, 0, buffer_length);
					fos.flush();
				}
				fos.flush();
				fos.close();
			}
		}
		return this.file;
	}
	else {
		log.error("Error " + response.getRawStatusCode() + " when retrieving " + this.artifact.getLibId() + ": " + response.getStatusText());
		return null;
	}
}
 
Example 3
Source File: CloudControllerResponseErrorHandler.java    From cf-java-client-sap with Apache License 2.0 6 votes vote down vote up
private static CloudOperationException getException(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    String statusText = response.getStatusText();

    ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally

    if (response.getBody() != null) {
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> responseBody = mapper.readValue(response.getBody(), Map.class);
            String description = getTrimmedDescription(responseBody);
            return new CloudOperationException(statusCode, statusText, description);
        } catch (IOException e) {
            // Fall through. Handled below.
        }
    }
    return new CloudOperationException(statusCode, statusText);
}
 
Example 4
Source File: CustomResponseErrorHandler.java    From sdk-rest with MIT License 6 votes vote down vote up
private byte[] getResponseBody(ClientHttpResponse response) {
    try {
        InputStream responseBody = response.getBody();

        if (responseBody != null) {

            StringWriter writer = new StringWriter();
            IOUtils.copy(responseBody, writer, "UTF-8");
            String responseBodyString = writer.toString();

            byte[] bytes = responseBodyString.getBytes();
            return bytes;
        }
    } catch (IOException ex) {
        log.info("here");
    }
    return new byte[0];
}
 
Example 5
Source File: GetResponseExtractor.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.putAll(response.getHeaders());
    for(Map.Entry<String, List<String>> e: headers.entrySet()) {
        List<String> values = e.getValue();
        for(int i = 0; i < values.size(); i++) {
            final String key = e.getKey();
            if(FORBIDDEN_HEADERS.contains(key)) {
                continue;
            }
            servletResponse.setHeader(key, values.get(i));
        }
    }
    try(InputStream is = response.getBody();
        ServletOutputStream os = servletResponse.getOutputStream()) {
        IOUtils.copy(is, os);
        servletResponse.flushBuffer();

    }
    return null;
}
 
Example 6
Source File: DefaultResponseErrorHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private byte[] getResponseBody(ClientHttpResponse response) {
	try {
		InputStream responseBody = response.getBody();
		if (responseBody != null) {
			return FileCopyUtils.copyToByteArray(responseBody);
		}
	}
	catch (IOException ex) {
		// ignore
	}
	return new byte[0];
}
 
Example 7
Source File: ResponseResults.java    From tutorials with MIT License 5 votes vote down vote up
ResponseResults(final ClientHttpResponse response) throws IOException {
    this.theResponse = response;
    final InputStream bodyInputStream = response.getBody();
    final StringWriter stringWriter = new StringWriter();
    IOUtils.copy(bodyInputStream, stringWriter);
    this.body = stringWriter.toString();
}
 
Example 8
Source File: LoggingInterceptor.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest req, byte[] reqBody, ClientHttpRequestExecution ex) throws IOException {
    log.debug("Request body: {}", new String(reqBody, StandardCharsets.UTF_8));
    ClientHttpResponse response = ex.execute(req, reqBody);
    InputStreamReader isr = new InputStreamReader(response.getBody(), StandardCharsets.UTF_8);
    String body = new BufferedReader(isr).lines()
        .collect(Collectors.joining("\n"));
    log.debug("Response body: {}", body);
    return response;
}
 
Example 9
Source File: JsonRpcResponseErrorHandler.java    From jsonrpc4j with MIT License 5 votes vote down vote up
private byte[] getResponseBody(ClientHttpResponse response) {
	try {
		final InputStream responseBody = response.getBody();
		if (responseBody != null) {
			return FileCopyUtils.copyToByteArray(responseBody);
		}
	} catch (IOException ex) {
           // No body in response 401 for example
           logger.debug("Can not read resonse body", ex);
	}
	return new byte[0];
}
 
Example 10
Source File: RestClientResponseErrorHandler.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
private byte[] getResponseBody(ClientHttpResponse response) {
    try {
        InputStream responseBody = response.getBody();
        if (responseBody != null) { 
            return FileCopyUtils.copyToByteArray(responseBody);
        }
    } catch (IOException ex) {
        if (L.isDebugEnabled()) {
            L.debug(R.getString("D-SPRINGMVC-REST-CLIENT-HANDLER#0015"), ex);
        }
    }
    return new byte[0];
}
 
Example 11
Source File: HttpResponseException.java    From riptide with MIT License 5 votes vote down vote up
private static byte[] readFromBody(final ClientHttpResponse response) throws IOException {
    @Nullable final InputStream stream = response.getBody();

    // needed for spring versions prior to 4.3.14
    if (stream == null) {
        return new byte[0];
    }

    final InputStream input = ByteStreams.limit(stream, MAX_BODY_BYTES_TO_READ);
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    ByteStreams.copy(input, output);
    return output.toByteArray();
}
 
Example 12
Source File: ImportSummariesResponseExtractor.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public ImportSummaries extractData( ClientHttpResponse response ) throws IOException
{
    InputStream stream = response.getBody();

    ImportSummaries summary = null;
    
    if ( stream != null )
    {
        summary = WebMessageParseUtils.fromWebMessageResponse( stream, ImportSummaries.class );
    }
    
    return summary;
}
 
Example 13
Source File: RestTemplateXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	if (!HttpStatus.OK.equals(response.getStatusCode())) {
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
Example 14
Source File: RestTemplateXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseEntity<String> extractData(ClientHttpResponse response) throws IOException {
	if (response.getBody() == null) {
		return new ResponseEntity<String>(response.getHeaders(), response.getStatusCode());
	}
	else {
		String body = StreamUtils.copyToString(response.getBody(), SockJsFrame.CHARSET);
		return new ResponseEntity<String>(body, response.getHeaders(), response.getStatusCode());
	}
}
 
Example 15
Source File: SeyrenResponseErrorHandler.java    From cerebro with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    String seyrenResponseBody;
    LOGGER.debug("Response : {} {}", response.getStatusCode(), response.getStatusText());
    if (response.getBody() != null) {
        seyrenResponseBody = CharStreams.toString(new InputStreamReader(response.getBody(), "UTF-8"));
    } else {
        seyrenResponseBody = "Response whithout body";
    }
    CerebroException exception = new CerebroException(ErrorCode.SEYREN_ERROR, seyrenResponseBody);
    throw exception;
}
 
Example 16
Source File: WxResponseErrorHandler.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
protected byte[] getResponseBody(ClientHttpResponse response) {
    try {
        InputStream responseBody = response.getBody();
        if (responseBody != null) {
            return FileCopyUtils.copyToByteArray(responseBody);
        }
    } catch (IOException ex) {
        // ignore
    }
    return new byte[0];
}
 
Example 17
Source File: RestTemplateXhrTransport.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
	if (httpStatus == null) {
		throw new UnknownHttpStatusCodeException(
				response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
	}
	if (httpStatus != HttpStatus.OK) {
		throw new HttpServerErrorException(
				httpStatus, response.getStatusText(), response.getHeaders(), null, null);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
Example 18
Source File: LicenceController.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, value = "/licence/{licenceId}/generate")
public @ResponseBody Object generateLicence(@PathVariable Long licenceId) throws Exception {
    try {
        Map<String, Object> map = new HashMap<String, Object>();
        User user = AuthenticationService.currentActingUser();
        Licence licence = Licence.findByIdAndCompanyId(licenceId, user.getCompany().getId());
        if (licence.getStatus() == LicenceStatus.NEW) {
            if (licence.getPageLayout() == PageLayout.PHOTOCOPY) {
                String filename = FilenameUtils.concat(licenceFileService.getLicencedPdfFileFolder(), licence.getId() + ".pdf");
                licenceInvoiceService.generateOutletInvoice(licence, filename);
                licence.setStatus(LicenceStatus.GENERATED);
                licence.merge();
                map.put("result", true);
            } else {
                ClientHttpResponse serverResponse = RestHttpClientFactory.execute("rest/licence/generate/" + licence.getId(), HttpMethod.GET);
                InputStream inputStream = serverResponse.getBody();
                try {
                    if (serverResponse.getStatusCode() == HttpStatus.OK) {
                        Response response = new ObjectMapper().readValue(inputStream, Response.class);
                        if (response.getStatus() == ResponseStatus.OK) {
                            map.put("result", true);
                        } else {
                            map.put("result", false);
                            map.put("message", response.getResponseObject());
                        }
                    } else {
                        map.put("result", false);
                        map.put("message", "Error generating licence");
                    }
                } finally {
                    inputStream.close();
                }
            }
        } else {
            map.put("result", false);
            map.put("message", "Licence already generated");
        }
        return map;
    } catch (Exception e) {
        logger.error("Unable to generate licenceid: " + licenceId, e);
        throw e;
    }
}
 
Example 19
Source File: RestTemplateXhrTransport.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
	if (httpStatus == null) {
		throw new UnknownHttpStatusCodeException(
				response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
	}
	if (httpStatus != HttpStatus.OK) {
		throw new HttpServerErrorException(
				httpStatus, response.getStatusText(), response.getHeaders(), null, null);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
Example 20
Source File: JwtSsoResponseErrorHandler.java    From wecube-platform with Apache License 2.0 4 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    if (!HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())) {
        errorHandler.handleError(response);
    } else {
        ClientHttpResponse bufferedResponse = new ClientHttpResponse() {
            private byte[] lazyBody;

            public HttpStatus getStatusCode() throws IOException {
                return response.getStatusCode();
            }

            public synchronized InputStream getBody() throws IOException {
                if (lazyBody == null) {
                    InputStream bodyStream = response.getBody();
                    if (bodyStream != null) {
                        lazyBody = FileCopyUtils.copyToByteArray(bodyStream);
                    } else {
                        lazyBody = new byte[0];
                    }
                }
                return new ByteArrayInputStream(lazyBody);
            }

            public HttpHeaders getHeaders() {
                return response.getHeaders();
            }

            public String getStatusText() throws IOException {
                return response.getStatusText();
            }

            public void close() {
                response.close();
            }

            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }
        };

        List<String> authenticateHeaders = bufferedResponse.getHeaders()
                .get(JwtSsoClientContext.HEADER_WWW_AUTHENTICATE);
        if (authenticateHeaders != null) {
            for (String authenticateHeader : authenticateHeaders) {
                if (authenticateHeader.startsWith(JwtSsoClientContext.PREFIX_BEARER_TOKEN)) {
                    throw new JwtSsoAccessTokenRequiredException("access token required.");
                }
            }
        }
        errorHandler.handleError(bufferedResponse);
    }

}