Search in sources :

Example 1 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project camel by apache.

the class DefaultCxfMessageMapper method createCxfMessageFromCamelExchange.

public Message createCxfMessageFromCamelExchange(Exchange camelExchange, HeaderFilterStrategy headerFilterStrategy) {
    org.apache.cxf.message.Message answer = CxfMessageHelper.getCxfInMessage(headerFilterStrategy, camelExchange, false);
    org.apache.camel.Message camelMessage = camelExchange.getIn();
    String requestContentType = getRequestContentType(camelMessage);
    String acceptContentTypes = camelMessage.getHeader("Accept", String.class);
    if (acceptContentTypes == null) {
        acceptContentTypes = "*/*";
    }
    String enc = getCharacterEncoding(camelMessage);
    String requestURI = getRequestURI(camelMessage);
    String path = getPath(camelMessage);
    String basePath = getBasePath(camelExchange);
    String verb = getVerb(camelMessage);
    String queryString = getQueryString(camelMessage);
    answer.put(org.apache.cxf.message.Message.REQUEST_URI, requestURI);
    answer.put(org.apache.cxf.message.Message.BASE_PATH, basePath);
    answer.put(org.apache.cxf.message.Message.HTTP_REQUEST_METHOD, verb);
    answer.put(org.apache.cxf.message.Message.PATH_INFO, path);
    answer.put(org.apache.cxf.message.Message.CONTENT_TYPE, requestContentType);
    answer.put(org.apache.cxf.message.Message.ACCEPT_CONTENT_TYPE, acceptContentTypes);
    answer.put(org.apache.cxf.message.Message.ENCODING, enc);
    answer.put(org.apache.cxf.message.Message.QUERY_STRING, queryString);
    HttpServletRequest request = (HttpServletRequest) camelMessage.getHeader(Exchange.HTTP_SERVLET_REQUEST);
    answer.put(CXF_HTTP_REQUEST, request);
    if (request != null) {
        setSecurityContext(answer, request);
    }
    Object response = camelMessage.getHeader(Exchange.HTTP_SERVLET_RESPONSE);
    answer.put(CXF_HTTP_RESPONSE, response);
    LOG.trace("Processing {}, requestContentType = {}, acceptContentTypes = {}, encoding = {}, path = {}, basePath = {}, verb = {}", new Object[] { camelExchange, requestContentType, acceptContentTypes, enc, path, basePath, verb });
    return answer;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Message(org.apache.cxf.message.Message)

Example 2 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project camel by apache.

the class HttpHelper method urlRewrite.

/**
     * Processes any custom {@link org.apache.camel.http.common.UrlRewrite}.
     *
     * @param exchange    the exchange
     * @param url         the url
     * @param endpoint    the http endpoint
     * @param producer    the producer
     * @return            the rewritten url, or <tt>null</tt> to use original url
     * @throws Exception is thrown if any error during rewriting url
     */
public static String urlRewrite(Exchange exchange, String url, HttpCommonEndpoint endpoint, Producer producer) throws Exception {
    String answer = null;
    String relativeUrl;
    if (endpoint.getUrlRewrite() != null) {
        // we should use the relative path if possible
        String baseUrl;
        relativeUrl = endpoint.getHttpUri().toASCIIString();
        // strip query parameters from relative url
        if (relativeUrl.contains("?")) {
            relativeUrl = ObjectHelper.before(relativeUrl, "?");
        }
        if (url.startsWith(relativeUrl)) {
            baseUrl = url.substring(0, relativeUrl.length());
            relativeUrl = url.substring(relativeUrl.length());
        } else {
            baseUrl = null;
            relativeUrl = url;
        }
        // mark it as null if its empty
        if (ObjectHelper.isEmpty(relativeUrl)) {
            relativeUrl = null;
        }
        String newUrl;
        if (endpoint.getUrlRewrite() instanceof HttpServletUrlRewrite) {
            // its servlet based, so we need the servlet request
            HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class);
            if (request == null) {
                HttpMessage msg = exchange.getIn(HttpMessage.class);
                if (msg != null) {
                    request = msg.getRequest();
                }
            }
            if (request == null) {
                throw new IllegalArgumentException("UrlRewrite " + endpoint.getUrlRewrite() + " requires the message body to be a" + "HttpServletRequest instance, but was: " + ObjectHelper.className(exchange.getIn().getBody()));
            }
            // we need to adapt the context-path to be the path from the endpoint, if it came from a http based endpoint
            // as eg camel-jetty have hardcoded context-path as / for all its servlets/endpoints
            // we have the actual context-path stored as a header with the key CamelServletContextPath
            String contextPath = exchange.getIn().getHeader("CamelServletContextPath", String.class);
            request = new UrlRewriteHttpServletRequestAdapter(request, contextPath);
            newUrl = ((HttpServletUrlRewrite) endpoint.getUrlRewrite()).rewrite(url, relativeUrl, producer, request);
        } else {
            newUrl = endpoint.getUrlRewrite().rewrite(url, relativeUrl, producer);
        }
        if (ObjectHelper.isNotEmpty(newUrl) && !newUrl.equals(url)) {
            // or a new relative url
            if (newUrl.startsWith("http:") || newUrl.startsWith("https:")) {
                answer = newUrl;
            } else if (baseUrl != null) {
                // avoid double // when adding the urls
                if (baseUrl.endsWith("/") && newUrl.startsWith("/")) {
                    answer = baseUrl + newUrl.substring(1);
                } else {
                    answer = baseUrl + newUrl;
                }
            } else {
                // use the new url as is
                answer = newUrl;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Using url rewrite to rewrite from url {} to {} -> {}", new Object[] { relativeUrl != null ? relativeUrl : url, newUrl, answer });
            }
        }
    }
    return answer;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest)

Example 3 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project camel by apache.

the class CamelServlet method doServiceAsync.

/**
     * This is used to handle request asynchronously
     * @param context the {@link AsyncContext}
     */
protected void doServiceAsync(AsyncContext context) {
    final HttpServletRequest request = (HttpServletRequest) context.getRequest();
    final HttpServletResponse response = (HttpServletResponse) context.getResponse();
    try {
        doService(request, response);
    } catch (Exception e) {
        //An error shouldn't occur as we should handle most of error in doService
        log.error("Error processing request", e);
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e1) {
            log.debug("Cannot send reply to client!", e1);
        }
        //Need to wrap it in RuntimeException as it occurs in a Runnable
        throw new RuntimeCamelException(e);
    } finally {
        context.complete();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) RuntimeCamelException(org.apache.camel.RuntimeCamelException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 4 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project camel by apache.

the class JettyHttpComponent method createServer.

protected Server createServer() {
    Server s = null;
    ThreadPool tp = threadPool;
    QueuedThreadPool qtp = null;
    // configure thread pool if min/max given
    if (minThreads != null || maxThreads != null) {
        if (getThreadPool() != null) {
            throw new IllegalArgumentException("You cannot configure both minThreads/maxThreads and a custom threadPool on JettyHttpComponent: " + this);
        }
        qtp = new QueuedThreadPool();
        if (minThreads != null) {
            qtp.setMinThreads(minThreads.intValue());
        }
        if (maxThreads != null) {
            qtp.setMaxThreads(maxThreads.intValue());
        }
        tp = qtp;
    }
    if (tp != null) {
        try {
            if (!Server.getVersion().startsWith("8")) {
                s = Server.class.getConstructor(ThreadPool.class).newInstance(tp);
            } else {
                s = new Server();
                if (isEnableJmx()) {
                    enableJmx(s);
                }
                Server.class.getMethod("setThreadPool", ThreadPool.class).invoke(s, tp);
            }
        } catch (Exception e) {
        //ignore
        }
    }
    if (s == null) {
        s = new Server();
    }
    if (qtp != null) {
        // let the thread names indicate they are from the server
        qtp.setName("CamelJettyServer(" + ObjectHelper.getIdentityHashCode(s) + ")");
        try {
            qtp.start();
        } catch (Exception e) {
            throw new RuntimeCamelException("Error starting JettyServer thread pool: " + qtp, e);
        }
    }
    ContextHandlerCollection collection = new ContextHandlerCollection();
    s.setHandler(collection);
    // setup the error handler if it set to Jetty component
    if (getErrorHandler() != null) {
        s.addBean(getErrorHandler());
    } else if (!Server.getVersion().startsWith("8")) {
        //need an error handler that won't leak information about the exception 
        //back to the client.
        ErrorHandler eh = new ErrorHandler() {

            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
                String msg = HttpStatus.getMessage(response.getStatus());
                request.setAttribute(RequestDispatcher.ERROR_MESSAGE, msg);
                if (response instanceof Response) {
                    //need to use the deprecated method to support compiling with Jetty 8
                    ((Response) response).setStatus(response.getStatus(), msg);
                }
                super.handle(target, baseRequest, request, response);
            }

            protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException {
                super.writeErrorPage(request, writer, code, message, false);
            }
        };
        s.addBean(eh, false);
    }
    return s;
}
Also used : ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) Server(org.eclipse.jetty.server.Server) MBeanServer(javax.management.MBeanServer) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ThreadPool(org.eclipse.jetty.util.thread.ThreadPool) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) GeneralSecurityException(java.security.GeneralSecurityException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) Endpoint(org.apache.camel.Endpoint) HttpCommonEndpoint(org.apache.camel.http.common.HttpCommonEndpoint) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) RuntimeCamelException(org.apache.camel.RuntimeCamelException) Writer(java.io.Writer)

Example 5 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project camel by apache.

the class HttpAuthMethodPriorityTest method createRouteBuilder.

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

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

                public void process(Exchange exchange) throws Exception {
                    HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class);
                    assertNotNull(req);
                    Principal user = req.getUserPrincipal();
                    assertNotNull(user);
                    assertEquals("donald", user.getName());
                }
            }).transform(constant("Bye World"));
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) HttpServletRequest(javax.servlet.http.HttpServletRequest) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) Principal(java.security.Principal)

Aggregations

HttpServletRequest (javax.servlet.http.HttpServletRequest)2488 HttpServletResponse (javax.servlet.http.HttpServletResponse)1308 Test (org.junit.Test)987 IOException (java.io.IOException)595 ServletException (javax.servlet.ServletException)498 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)223 FilterChain (javax.servlet.FilterChain)200 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)196 Test (org.testng.annotations.Test)168 Request (org.eclipse.jetty.server.Request)164 CountDownLatch (java.util.concurrent.CountDownLatch)160 HttpServlet (javax.servlet.http.HttpServlet)156 HttpSession (javax.servlet.http.HttpSession)150 HashMap (java.util.HashMap)130 PrintWriter (java.io.PrintWriter)121 Map (java.util.Map)100 InterruptedIOException (java.io.InterruptedIOException)97 ServletRequest (javax.servlet.ServletRequest)95 ServletContext (javax.servlet.ServletContext)91 ServletOutputStream (javax.servlet.ServletOutputStream)90