use of java.io.IOException in project camel by apache.
the class HttpProducer method createRequestEntity.
/**
* Creates a holder object for the data to send to the remote server.
*
* @param exchange the exchange with the IN message with data to send
* @return the data holder
* @throws CamelExchangeException is thrown if error creating RequestEntity
*/
protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
Message in = exchange.getIn();
if (in.getBody() == null) {
return null;
}
RequestEntity answer = in.getBody(RequestEntity.class);
if (answer == null) {
try {
Object data = in.getBody();
if (data != null) {
String contentType = ExchangeHelper.getContentType(exchange);
if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
throw new CamelExchangeException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
}
// serialized java object
Serializable obj = in.getMandatoryBody(Serializable.class);
// write object to output stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
HttpHelper.writeObjectToStream(bos, obj);
answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
IOHelper.close(bos);
} else if (data instanceof File || data instanceof GenericFile) {
// file based (could potentially also be a FTP file etc)
File file = in.getBody(File.class);
if (file != null) {
answer = new FileRequestEntity(file, contentType);
}
} else if (data instanceof String) {
// be a bit careful with String as any type can most likely be converted to String
// so we only do an instanceof check and accept String if the body is really a String
// do not fallback to use the default charset as it can influence the request
// (for example application/x-www-form-urlencoded forms being sent)
String charset = IOHelper.getCharsetName(exchange, false);
answer = new StringRequestEntity((String) data, contentType, charset);
}
// fallback as input stream
if (answer == null) {
// force the body as an input stream since this is the fallback
InputStream is = in.getMandatoryBody(InputStream.class);
answer = new InputStreamRequestEntity(is, contentType);
}
}
} catch (UnsupportedEncodingException e) {
throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
} catch (IOException e) {
throw new CamelExchangeException("Error serializing message body", exchange, e);
}
}
return answer;
}
use of java.io.IOException in project camel by apache.
the class DefaultHttpBinding method doWriteDirectResponse.
protected void doWriteDirectResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
// if content type is serialized Java object, then serialize and write it to the response
String contentType = message.getHeader(Exchange.CONTENT_TYPE, String.class);
if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
if (allowJavaSerializedObject || isTransferException()) {
try {
Object object = message.getMandatoryBody(Serializable.class);
HttpHelper.writeObjectToServletResponse(response, object);
// object is written so return
return;
} catch (InvalidPayloadException e) {
throw new IOException(e);
}
} else {
throw new RuntimeCamelException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed");
}
}
// prefer streaming
InputStream is = null;
if (checkChunked(message, exchange)) {
is = message.getBody(InputStream.class);
} else {
// try to use input stream first, so we can copy directly
if (!isText(contentType)) {
is = exchange.getContext().getTypeConverter().tryConvertTo(InputStream.class, message.getBody());
}
}
if (is != null) {
ServletOutputStream os = response.getOutputStream();
if (!checkChunked(message, exchange)) {
CachedOutputStream stream = new CachedOutputStream(exchange);
try {
// copy directly from input stream to the cached output stream to get the content length
int len = copyStream(is, stream, response.getBufferSize());
// we need to setup the length if message is not chucked
response.setContentLength(len);
OutputStream current = stream.getCurrentStream();
if (current instanceof ByteArrayOutputStream) {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming (direct) response in non-chunked mode with content-length {}");
}
ByteArrayOutputStream bos = (ByteArrayOutputStream) current;
bos.writeTo(os);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming response in non-chunked mode with content-length {} and buffer size: {}", len, len);
}
copyStream(stream.getInputStream(), os, len);
}
} finally {
IOHelper.close(is, os);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Streaming response in chunked mode with buffer size {}", response.getBufferSize());
}
copyStream(is, os, response.getBufferSize());
}
} else {
// not convertable as a stream so fallback as a String
String data = message.getBody(String.class);
if (data != null) {
// set content length and encoding before we write data
String charset = IOHelper.getCharsetName(exchange, true);
final int dataByteLength = data.getBytes(charset).length;
response.setCharacterEncoding(charset);
response.setContentLength(dataByteLength);
if (LOG.isDebugEnabled()) {
LOG.debug("Writing response in non-chunked mode as plain text with content-length {} and buffer size: {}", dataByteLength, response.getBufferSize());
}
try {
response.getWriter().print(data);
} finally {
response.getWriter().flush();
}
}
}
}
use of java.io.IOException in project camel by apache.
the class CamelServlet method doService.
/**
* This is the logical implementation to handle request with {@link CamelServlet}
* This is where most exceptions should be handled
*
* @param request the {@link HttpServletRequest}
* @param response the {@link HttpServletResponse}
* @throws ServletException
* @throws IOException
*/
protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.trace("Service: {}", request);
// Is there a consumer registered for the request.
HttpConsumer consumer = resolve(request);
if (consumer == null) {
log.debug("No consumer to service request {}", request);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// are we suspended?
if (consumer.isSuspended()) {
log.debug("Consumer suspended, cannot service request {}", request);
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
return;
}
// if its an OPTIONS request then return which method is allowed
if ("OPTIONS".equals(request.getMethod()) && !consumer.isOptionsEnabled()) {
String s;
if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
} else {
// allow them all
s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
}
response.addHeader("Allow", s);
response.setStatus(HttpServletResponse.SC_OK);
return;
}
if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.getMethod())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
if ("TRACE".equals(request.getMethod()) && !consumer.isTraceEnabled()) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
// create exchange and set data on it
Exchange exchange = new DefaultExchange(consumer.getEndpoint(), ExchangePattern.InOut);
if (consumer.getEndpoint().isBridgeEndpoint()) {
exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
exchange.setProperty(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.TRUE);
}
if (consumer.getEndpoint().isDisableStreamCache()) {
exchange.setProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.TRUE);
}
// we override the classloader before building the HttpMessage just in case the binding
// does some class resolution
ClassLoader oldTccl = overrideTccl(exchange);
HttpHelper.setCharsetFromContentType(request.getContentType(), exchange);
exchange.setIn(new HttpMessage(exchange, request, response));
// set context path as header
String contextPath = consumer.getEndpoint().getPath();
exchange.getIn().setHeader("CamelServletContextPath", contextPath);
String httpPath = (String) exchange.getIn().getHeader(Exchange.HTTP_PATH);
// here we just remove the CamelServletContextPath part from the HTTP_PATH
if (contextPath != null && httpPath.startsWith(contextPath)) {
exchange.getIn().setHeader(Exchange.HTTP_PATH, httpPath.substring(contextPath.length()));
}
// we want to handle the UoW
try {
consumer.createUoW(exchange);
} catch (Exception e) {
log.error("Error processing request", e);
throw new ServletException(e);
}
try {
if (log.isTraceEnabled()) {
log.trace("Processing request for exchangeId: {}", exchange.getExchangeId());
}
// process the exchange
consumer.getProcessor().process(exchange);
} catch (Exception e) {
exchange.setException(e);
}
try {
// now lets output to the response
if (log.isTraceEnabled()) {
log.trace("Writing response for exchangeId: {}", exchange.getExchangeId());
}
Integer bs = consumer.getEndpoint().getResponseBufferSize();
if (bs != null) {
log.trace("Using response buffer size: {}", bs);
response.setBufferSize(bs);
}
consumer.getBinding().writeResponse(exchange, response);
} catch (IOException e) {
log.error("Error processing request", e);
throw e;
} catch (Exception e) {
log.error("Error processing request", e);
throw new ServletException(e);
} finally {
consumer.doneUoW(exchange);
restoreTccl(exchange, oldTccl);
}
}
use of java.io.IOException in project camel by apache.
the class HttpProducer method doExtractResponseBodyAsStream.
private static InputStream doExtractResponseBodyAsStream(InputStream is, Exchange exchange) throws IOException {
// As httpclient is using a AutoCloseInputStream, it will be closed when the connection is closed
// we need to cache the stream for it.
CachedOutputStream cos = null;
try {
// This CachedOutputStream will not be closed when the exchange is onCompletion
cos = new CachedOutputStream(exchange, false);
IOHelper.copy(is, cos);
// When the InputStream is closed, the CachedOutputStream will be closed
return cos.getWrappedInputStream();
} catch (IOException ex) {
// try to close the CachedOutputStream when we get the IOException
try {
cos.close();
} catch (IOException ignore) {
//do nothing here
}
throw ex;
} finally {
IOHelper.close(is, "Extracting response body", LOG);
}
}
use of java.io.IOException in project camel by apache.
the class HttpProducer method populateHttpOperationFailedException.
protected Exception populateHttpOperationFailedException(Exchange exchange, HttpRequestBase httpRequest, HttpResponse httpResponse, int responseCode) throws IOException, ClassNotFoundException {
Exception answer;
String uri = httpRequest.getURI().toString();
String statusText = httpResponse.getStatusLine() != null ? httpResponse.getStatusLine().getReasonPhrase() : null;
Map<String, String> headers = extractResponseHeaders(httpResponse.getAllHeaders());
// handle cookies
if (getEndpoint().getCookieHandler() != null) {
Map<String, List<String>> m = new HashMap<String, List<String>>();
for (Entry<String, String> e : headers.entrySet()) {
m.put(e.getKey(), Collections.singletonList(e.getValue()));
}
getEndpoint().getCookieHandler().storeCookies(exchange, httpRequest.getURI(), m);
}
Object responseBody = extractResponseBody(httpRequest, httpResponse, exchange, getEndpoint().isIgnoreResponseBody());
if (transferException && responseBody != null && responseBody instanceof Exception) {
// if the response was a serialized exception then use that
return (Exception) responseBody;
}
// make a defensive copy of the response body in the exception so its detached from the cache
String copy = null;
if (responseBody != null) {
copy = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, responseBody);
}
Header locationHeader = httpResponse.getFirstHeader("location");
if (locationHeader != null && (responseCode >= 300 && responseCode < 400)) {
answer = new HttpOperationFailedException(uri, responseCode, statusText, locationHeader.getValue(), headers, copy);
} else {
answer = new HttpOperationFailedException(uri, responseCode, statusText, null, headers, copy);
}
return answer;
}
Aggregations