Search in sources :

Example 86 with IOException

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;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Serializable(java.io.Serializable) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) Message(org.apache.camel.Message) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) GenericFile(org.apache.camel.component.file.GenericFile) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 87 with IOException

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();
            }
        }
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) CachedOutputStream(org.apache.camel.converter.stream.CachedOutputStream) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvalidPayloadException(org.apache.camel.InvalidPayloadException) Endpoint(org.apache.camel.Endpoint) CachedOutputStream(org.apache.camel.converter.stream.CachedOutputStream)

Example 88 with IOException

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);
    }
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) DefaultExchange(org.apache.camel.impl.DefaultExchange) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 89 with IOException

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);
    }
}
Also used : IOException(java.io.IOException) CachedOutputStream(org.apache.camel.converter.stream.CachedOutputStream)

Example 90 with IOException

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;
}
Also used : Header(org.apache.http.Header) HashMap(java.util.HashMap) HttpOperationFailedException(org.apache.camel.http.common.HttpOperationFailedException) List(java.util.List) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HttpOperationFailedException(org.apache.camel.http.common.HttpOperationFailedException) CamelExchangeException(org.apache.camel.CamelExchangeException)

Aggregations

IOException (java.io.IOException)41104 File (java.io.File)7663 InputStream (java.io.InputStream)4105 Test (org.junit.Test)3557 ArrayList (java.util.ArrayList)3023 FileInputStream (java.io.FileInputStream)2674 FileOutputStream (java.io.FileOutputStream)2358 FileNotFoundException (java.io.FileNotFoundException)2146 BufferedReader (java.io.BufferedReader)2028 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1761 InputStreamReader (java.io.InputStreamReader)1677 URL (java.net.URL)1608 HashMap (java.util.HashMap)1552 ByteArrayInputStream (java.io.ByteArrayInputStream)1534 OutputStream (java.io.OutputStream)1349 Path (org.apache.hadoop.fs.Path)1316 Map (java.util.Map)1212 List (java.util.List)1042 Properties (java.util.Properties)994 ServletException (javax.servlet.ServletException)916