Search in sources :

Example 1 with HttpMessage

use of org.apache.camel.http.common.HttpMessage in project camel by apache.

the class AhcProducerSessionTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start").to("ahc:" + getTestServerEndpointSessionUrl()).to("ahc:" + getTestServerEndpointSessionUrl()).to("mock:result");
            from("direct:instance").to("ahc:" + getTestServerEndpointSessionUrl() + "?cookieHandler=#instanceCookieHandler").to("ahc:" + getTestServerEndpointSessionUrl() + "?cookieHandler=#instanceCookieHandler").to("mock:result");
            from("direct:exchange").to("ahc:" + getTestServerEndpointSessionUrl() + "?cookieHandler=#exchangeCookieHandler").to("ahc:" + getTestServerEndpointSessionUrl() + "?cookieHandler=#exchangeCookieHandler").to("mock:result");
            from(getTestServerEndpointSessionUri()).process(new Processor() {

                @Override
                public void process(Exchange exchange) throws Exception {
                    HttpMessage message = exchange.getIn(HttpMessage.class);
                    HttpSession session = message.getRequest().getSession();
                    String body = message.getBody(String.class);
                    if ("bar".equals(session.getAttribute("foo"))) {
                        message.setBody("Old " + body);
                    } else {
                        session.setAttribute("foo", "bar");
                        message.setBody("New " + body);
                    }
                }
            });
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) HttpSession(javax.servlet.http.HttpSession) HttpMessage(org.apache.camel.http.common.HttpMessage)

Example 2 with HttpMessage

use of org.apache.camel.http.common.HttpMessage in project camel by apache.

the class CamelContinuationServlet method doService.

@Override
protected void doService(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    log.trace("Service: {}", request);
    // is there a consumer registered for the request.
    HttpConsumer consumer = getServletResolveConsumerStrategy().resolve(request, getConsumers());
    if (consumer == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // figure out if continuation is enabled and what timeout to use
    boolean useContinuation = false;
    Long continuationTimeout = null;
    HttpCommonEndpoint endpoint = consumer.getEndpoint();
    if (endpoint instanceof JettyHttpEndpoint) {
        JettyHttpEndpoint jettyEndpoint = (JettyHttpEndpoint) endpoint;
        Boolean epUseContinuation = jettyEndpoint.getUseContinuation();
        Long epContinuationTimeout = jettyEndpoint.getContinuationTimeout();
        if (epUseContinuation != null) {
            useContinuation = epUseContinuation;
        } else {
            useContinuation = jettyEndpoint.getComponent().isUseContinuation();
        }
        if (epContinuationTimeout != null) {
            continuationTimeout = epContinuationTimeout;
        } else {
            continuationTimeout = jettyEndpoint.getComponent().getContinuationTimeout();
        }
    }
    if (useContinuation) {
        log.trace("Start request with continuation timeout of {}", continuationTimeout != null ? continuationTimeout : "jetty default");
    } else {
        log.trace("Usage of continuation is disabled, either by component or endpoint configuration, fallback to normal servlet processing instead");
        super.doService(request, response);
        return;
    }
    if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
        Iterator<?> it = ObjectHelper.createIterable(consumer.getEndpoint().getHttpMethodRestrict()).iterator();
        boolean match = false;
        while (it.hasNext()) {
            String method = it.next().toString();
            if (method.equalsIgnoreCase(request.getMethod())) {
                match = true;
                break;
            }
        }
        if (!match) {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    }
    if ("TRACE".equals(request.getMethod()) && !consumer.isTraceEnabled()) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    // we do not support java serialized objects unless explicit enabled
    String contentType = request.getContentType();
    if (HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType) && !consumer.getEndpoint().getComponent().isAllowJavaSerializedObject()) {
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        return;
    }
    final Exchange result = (Exchange) request.getAttribute(EXCHANGE_ATTRIBUTE_NAME);
    if (result == null) {
        // no asynchronous result so leverage continuation
        final Continuation continuation = ContinuationSupport.getContinuation(request);
        if (continuation.isInitial() && continuationTimeout != null) {
            // set timeout on initial
            continuation.setTimeout(continuationTimeout);
        }
        // are we suspended and a request is dispatched initially?
        if (consumer.isSuspended() && continuation.isInitial()) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }
        if (continuation.isExpired()) {
            String id = (String) continuation.getAttribute(EXCHANGE_ATTRIBUTE_ID);
            // remember this id as expired
            expiredExchanges.put(id, id);
            log.warn("Continuation expired of exchangeId: {}", id);
            consumer.getBinding().doWriteExceptionResponse(new TimeoutException(), response);
            return;
        }
        // a new request so create an exchange
        final 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);
        }
        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);
        updateHttpPath(exchange, contextPath);
        if (log.isTraceEnabled()) {
            log.trace("Suspending continuation of exchangeId: {}", exchange.getExchangeId());
        }
        continuation.setAttribute(EXCHANGE_ATTRIBUTE_ID, exchange.getExchangeId());
        // we want to handle the UoW
        try {
            consumer.createUoW(exchange);
        } catch (Exception e) {
            log.error("Error processing request", e);
            throw new ServletException(e);
        }
        // must suspend before we process the exchange
        continuation.suspend();
        ClassLoader oldTccl = overrideTccl(exchange);
        if (log.isTraceEnabled()) {
            log.trace("Processing request for exchangeId: {}", exchange.getExchangeId());
        }
        // use the asynchronous API to process the exchange
        consumer.getAsyncProcessor().process(exchange, new AsyncCallback() {

            public void done(boolean doneSync) {
                // check if the exchange id is already expired
                boolean expired = expiredExchanges.remove(exchange.getExchangeId()) != null;
                if (!expired) {
                    if (log.isTraceEnabled()) {
                        log.trace("Resuming continuation of exchangeId: {}", exchange.getExchangeId());
                    }
                    // resume processing after both, sync and async callbacks
                    continuation.setAttribute(EXCHANGE_ATTRIBUTE_NAME, exchange);
                    continuation.resume();
                } else {
                    log.warn("Cannot resume expired continuation of exchangeId: {}", exchange.getExchangeId());
                }
            }
        });
        if (oldTccl != null) {
            restoreTccl(exchange, oldTccl);
        }
        // method again when its resumed
        return;
    }
    try {
        // now lets output to the response
        if (log.isTraceEnabled()) {
            log.trace("Resumed continuation and writing response for exchangeId: {}", result.getExchangeId());
        }
        Integer bs = consumer.getEndpoint().getResponseBufferSize();
        if (bs != null) {
            log.trace("Using response buffer size: {}", bs);
            response.setBufferSize(bs);
        }
        consumer.getBinding().writeResponse(result, 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(result);
    }
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Continuation(org.eclipse.jetty.continuation.Continuation) AsyncCallback(org.apache.camel.AsyncCallback) IOException(java.io.IOException) HttpConsumer(org.apache.camel.http.common.HttpConsumer) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) ServletException(javax.servlet.ServletException) HttpMessage(org.apache.camel.http.common.HttpMessage) HttpCommonEndpoint(org.apache.camel.http.common.HttpCommonEndpoint) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with HttpMessage

use of org.apache.camel.http.common.HttpMessage in project camel by apache.

the class HttpConverterTest method testToInputStream.

@Test
public void testToInputStream() throws Exception {
    context.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("jetty://http://localhost:{{port}}/test").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    HttpMessage msg = exchange.getIn(HttpMessage.class);
                    InputStream sis = msg.getBody(InputStream.class);
                    assertNotNull(sis);
                    String s = exchange.getContext().getTypeConverter().convertTo(String.class, sis);
                    assertEquals("Hello World", s);
                }
            }).transform(constant("Bye World"));
        }
    });
    context.start();
    String out = template.requestBody("http://localhost:{{port}}/test", "Hello World", String.class);
    assertEquals("Bye World", out);
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) HttpMessage(org.apache.camel.http.common.HttpMessage) Test(org.junit.Test)

Example 4 with HttpMessage

use of org.apache.camel.http.common.HttpMessage in project camel by apache.

the class HttpConverterTest method testToServletInputStream.

@Test
public void testToServletInputStream() throws Exception {
    context.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("jetty://http://localhost:{{port}}/test").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    HttpMessage msg = exchange.getIn(HttpMessage.class);
                    ServletInputStream sis = HttpConverter.toServletInputStream(msg);
                    assertNotNull(sis);
                    // The ServletInputStream should be cached and you can't read message here
                    assertTrue(sis.available() == 0);
                    String s = msg.getBody(String.class);
                    assertEquals("Hello World", s);
                }
            }).transform(constant("Bye World"));
        }
    });
    context.start();
    String out = template.requestBody("http://localhost:{{port}}/test", "Hello World", String.class);
    assertEquals("Bye World", out);
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) ServletInputStream(javax.servlet.ServletInputStream) RouteBuilder(org.apache.camel.builder.RouteBuilder) HttpMessage(org.apache.camel.http.common.HttpMessage) Test(org.junit.Test)

Example 5 with HttpMessage

use of org.apache.camel.http.common.HttpMessage in project camel by apache.

the class HttpRouteTest method createRouteBuilder.

@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        public void configure() {
            port1 = getPort();
            port2 = getNextPort();
            port3 = getNextPort();
            port4 = getNextPort();
            // enable stream cache
            context.setStreamCaching(true);
            from("jetty:http://localhost:" + port1 + "/test").to("mock:a");
            Processor proc = new Processor() {

                public void process(Exchange exchange) throws Exception {
                    try {
                        HttpMessage message = (HttpMessage) exchange.getIn();
                        HttpSession session = message.getRequest().getSession();
                        assertNotNull("we should get session here", session);
                    } catch (Exception e) {
                        exchange.getOut().setFault(true);
                        exchange.getOut().setBody(e);
                    }
                    exchange.getOut().setBody("<b>Hello World</b>");
                }
            };
            from("jetty:http://localhost:" + port1 + "/responseCode").setHeader(Exchange.HTTP_RESPONSE_CODE, simple("400"));
            Processor printProcessor = new Processor() {

                public void process(Exchange exchange) throws Exception {
                    Message out = exchange.getOut();
                    out.copyFrom(exchange.getIn());
                    log.info("The body's object is " + exchange.getIn().getBody());
                    log.info("Process body = " + exchange.getIn().getBody(String.class));
                    InputStreamCache cache = out.getBody(InputStreamCache.class);
                    cache.reset();
                }
            };
            from("jetty:http://localhost:" + port2 + "/hello?sessionSupport=true").process(proc);
            from("jetty:http://localhost:" + port1 + "/echo").process(printProcessor).process(printProcessor);
            Processor procParameters = new Processor() {

                public void process(Exchange exchange) throws Exception {
                    // As the request input stream is cached by DefaultHttpBinding,
                    // HttpServletRequest can't get the parameters of post message
                    String value = exchange.getIn().getHeader("request", String.class);
                    if (value != null) {
                        assertNotNull("The value of the parameter should not be null", value);
                        exchange.getOut().setBody(value);
                    } else {
                        exchange.getOut().setBody("Can't get a right parameter");
                    }
                }
            };
            from("jetty:http://localhost:" + port1 + "/parameter").process(procParameters);
            from("jetty:http://localhost:" + port1 + "/postxml").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    String value = exchange.getIn().getBody(String.class);
                    assertEquals("The response message is wrong", value, POST_MESSAGE);
                    exchange.getOut().setBody("OK");
                }
            });
            from("jetty:http://localhost:" + port3 + "/noStreamCache?disableStreamCache=true").noStreamCaching().process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    InputStream is = (InputStream) exchange.getIn().getBody();
                    assertTrue("It should be a raw inputstream", is instanceof org.eclipse.jetty.server.HttpInput);
                    String request = exchange.getIn().getBody(String.class);
                    assertEquals("Got a wrong request", "This is a test", request);
                    exchange.getOut().setBody("OK");
                }
            });
            from("jetty:http://localhost:" + port4 + "/requestBufferSize").process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    String string = exchange.getIn().getBody(String.class);
                    exchange.getOut().setBody(string);
                }
            });
        }
    };
}
Also used : Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) Message(org.apache.camel.Message) HttpMessage(org.apache.camel.http.common.HttpMessage) HttpSession(javax.servlet.http.HttpSession) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) Exchange(org.apache.camel.Exchange) InputStreamCache(org.apache.camel.converter.stream.InputStreamCache) HttpMessage(org.apache.camel.http.common.HttpMessage)

Aggregations

HttpMessage (org.apache.camel.http.common.HttpMessage)14 Exchange (org.apache.camel.Exchange)13 Processor (org.apache.camel.Processor)8 RouteBuilder (org.apache.camel.builder.RouteBuilder)8 Test (org.junit.Test)6 InputStream (java.io.InputStream)5 HttpSession (javax.servlet.http.HttpSession)5 IOException (java.io.IOException)3 Matchers.anyString (org.mockito.Matchers.anyString)3 ServletException (javax.servlet.ServletException)2 ServletInputStream (javax.servlet.ServletInputStream)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpConsumer (org.apache.camel.http.common.HttpConsumer)2 DefaultExchange (org.apache.camel.impl.DefaultExchange)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 TimeoutException (java.util.concurrent.TimeoutException)1 AsyncCallback (org.apache.camel.AsyncCallback)1 Message (org.apache.camel.Message)1 Route (org.apache.camel.Route)1 InputStreamCache (org.apache.camel.converter.stream.InputStreamCache)1