Search in sources :

Example 81 with Request

use of org.eclipse.jetty.server.Request in project httpx by EricEdens.

the class JettyPathTest method testParameterDecoding.

@Test
public void testParameterDecoding() throws Exception {
    Server server = run(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print(request.getParameter("hi"));
            baseRequest.setHandled(true);
        }
    });
    try {
        for (char c = 0; c < 1024; c++) {
            String queryParam = String.valueOf(c);
            String url = Url.httpBuilder("localhost", "/").port(8080).addQueryParam("hi", queryParam).toString();
            try (InputStream stream = new URL(url).openStream()) {
                byte[] bytes = ByteStreams.toByteArray(stream);
                assertEquals("char c = " + c, queryParam, new String(bytes));
            }
        }
    } finally {
        server.stop();
    }
}
Also used : Server(org.eclipse.jetty.server.Server) InputStream(java.io.InputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) URL(java.net.URL) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Test(org.junit.Test)

Example 82 with Request

use of org.eclipse.jetty.server.Request in project jersey by jersey.

the class JettyHttpContainer method handle.

@Override
public void handle(final String target, final Request request, final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException, ServletException {
    final Response response = Response.getResponse(httpServletResponse);
    final ResponseWriter responseWriter = new ResponseWriter(request, response, configSetStatusOverSendError);
    final URI baseUri = getBaseUri(request);
    final URI requestUri = getRequestUri(request, baseUri);
    try {
        final ContainerRequest requestContext = new ContainerRequest(baseUri, requestUri, request.getMethod(), getSecurityContext(request), new MapPropertiesDelegate());
        requestContext.setEntityStream(request.getInputStream());
        final Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            requestContext.headers(headerName, headerValue == null ? "" : headerValue);
        }
        requestContext.setWriter(responseWriter);
        requestContext.setRequestScopedInitializer(injectionManager -> {
            injectionManager.<Ref<Request>>getInstance(REQUEST_TYPE).set(request);
            injectionManager.<Ref<Response>>getInstance(RESPONSE_TYPE).set(response);
        });
        // Mark the request as handled before generating the body of the response
        request.setHandled(true);
        appHandler.handle(requestContext);
    } catch (final Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) ContainerResponseWriter(org.glassfish.jersey.server.spi.ContainerResponseWriter) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) URI(java.net.URI) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) ContainerException(org.glassfish.jersey.server.ContainerException) IOException(java.io.IOException)

Example 83 with Request

use of org.eclipse.jetty.server.Request in project blade by biezhi.

the class FormAuthenticator method validateRequest.

/* ------------------------------------------------------------ */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    Request base_request = Request.getBaseRequest(request);
    Response base_response = base_request.getResponse();
    String uri = request.getRequestURI();
    if (uri == null)
        uri = URIUtil.SLASH;
    mandatory |= isJSecurityCheck(uri);
    if (!mandatory)
        return new DeferredAuthentication(this);
    if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())) && !DeferredAuthentication.isDeferred(response))
        return new DeferredAuthentication(this);
    HttpSession session = request.getSession(true);
    try {
        // Handle a request for authentication.
        if (isJSecurityCheck(uri)) {
            final String username = request.getParameter(__J_USERNAME);
            final String password = request.getParameter(__J_PASSWORD);
            UserIdentity user = login(username, password, request);
            LOG.debug("jsecuritycheck {} {}", username, user);
            session = request.getSession(true);
            if (user != null) {
                // Redirect to original request
                String nuri;
                FormAuthentication form_auth;
                synchronized (session) {
                    nuri = (String) session.getAttribute(__J_URI);
                    if (nuri == null || nuri.length() == 0) {
                        nuri = request.getContextPath();
                        if (nuri.length() == 0)
                            nuri = URIUtil.SLASH;
                    }
                    form_auth = new FormAuthentication(getAuthMethod(), user);
                }
                LOG.debug("authenticated {}->{}", form_auth, nuri);
                response.setContentLength(0);
                int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
                base_response.sendRedirect(redirectCode, response.encodeRedirectURL(nuri));
                return form_auth;
            }
            // not authenticated
            if (LOG.isDebugEnabled())
                LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
            if (_formErrorPage == null) {
                LOG.debug("auth failed {}->403", username);
                if (response != null)
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else if (_dispatch) {
                LOG.debug("auth failed {}=={}", username, _formErrorPage);
                RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
                response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
                response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
                dispatcher.forward(new FormRequest(request), new FormResponse(response));
            } else {
                LOG.debug("auth failed {}->{}", username, _formErrorPage);
                int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
                base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
            }
            return Authentication.SEND_FAILURE;
        }
        // Look for cached authentication
        Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
        if (authentication != null) {
            // Has authentication been revoked?
            if (authentication instanceof User && _loginService != null && !_loginService.validate(((User) authentication).getUserIdentity())) {
                LOG.debug("auth revoked {}", authentication);
                session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
            } else {
                synchronized (session) {
                    String j_uri = (String) session.getAttribute(__J_URI);
                    if (j_uri != null) {
                        //check if the request is for the same url as the original and restore
                        //params if it was a post
                        LOG.debug("auth retry {}->{}", authentication, j_uri);
                        StringBuffer buf = request.getRequestURL();
                        if (request.getQueryString() != null)
                            buf.append("?").append(request.getQueryString());
                        if (j_uri.equals(buf.toString())) {
                            MultiMap<String> j_post = (MultiMap<String>) session.getAttribute(__J_POST);
                            if (j_post != null) {
                                LOG.debug("auth rePOST {}->{}", authentication, j_uri);
                                base_request.setContentParameters(j_post);
                            }
                            session.removeAttribute(__J_URI);
                            session.removeAttribute(__J_METHOD);
                            session.removeAttribute(__J_POST);
                        }
                    }
                }
                LOG.debug("auth {}", authentication);
                return authentication;
            }
        }
        // if we can't send challenge
        if (DeferredAuthentication.isDeferred(response)) {
            LOG.debug("auth deferred {}", session.getId());
            return Authentication.UNAUTHENTICATED;
        }
        // remember the current URI
        synchronized (session) {
            // But only if it is not set already, or we save every uri that leads to a login form redirect
            if (session.getAttribute(__J_URI) == null || _alwaysSaveUri) {
                StringBuffer buf = request.getRequestURL();
                if (request.getQueryString() != null)
                    buf.append("?").append(request.getQueryString());
                session.setAttribute(__J_URI, buf.toString());
                session.setAttribute(__J_METHOD, request.getMethod());
                if (MimeTypes.Type.FORM_ENCODED.is(req.getContentType()) && HttpMethod.POST.is(request.getMethod())) {
                    MultiMap<String> formParameters = new MultiMap<>();
                    base_request.extractFormParameters(formParameters);
                    session.setAttribute(__J_POST, formParameters);
                }
            }
        }
        // send the the challenge
        if (_dispatch) {
            LOG.debug("challenge {}=={}", session.getId(), _formLoginPage);
            RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
            response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
            dispatcher.forward(new FormRequest(request), new FormResponse(response));
        } else {
            LOG.debug("challenge {}->{}", session.getId(), _formLoginPage);
            int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
            base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
        }
        return Authentication.SEND_CONTINUE;
    } catch (IOException | ServletException e) {
        throw new ServerAuthException(e);
    }
}
Also used : User(org.eclipse.jetty.server.Authentication.User) HttpSession(javax.servlet.http.HttpSession) UserIdentity(org.eclipse.jetty.server.UserIdentity) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) Constraint(org.eclipse.jetty.util.security.Constraint) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ServletException(javax.servlet.ServletException) MultiMap(org.eclipse.jetty.util.MultiMap) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication)

Example 84 with Request

use of org.eclipse.jetty.server.Request in project blade by biezhi.

the class FormAuthenticator method prepareRequest.

/* ------------------------------------------------------------ */
@Override
public void prepareRequest(ServletRequest request) {
    //if this is a request resulting from a redirect after auth is complete
    //(ie its from a redirect to the original request uri) then due to 
    //browser handling of 302 redirects, the method may not be the same as
    //that of the original request. Replace the method and original post
    //params (if it was a post).
    //
    //See Servlet Spec 3.1 sec 13.6.3
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpSession session = httpRequest.getSession(false);
    if (session == null || session.getAttribute(SessionAuthentication.__J_AUTHENTICATED) == null)
        //not authenticated yet
        return;
    String juri = (String) session.getAttribute(__J_URI);
    if (juri == null || juri.length() == 0)
        //no original uri saved
        return;
    String method = (String) session.getAttribute(__J_METHOD);
    if (method == null || method.length() == 0)
        //didn't save original request method
        return;
    StringBuffer buf = httpRequest.getRequestURL();
    if (httpRequest.getQueryString() != null)
        buf.append("?").append(httpRequest.getQueryString());
    if (!juri.equals(buf.toString()))
        //this request is not for the same url as the original
        return;
    //restore the original request's method on this request
    if (LOG.isDebugEnabled())
        LOG.debug("Restoring original method {} for {} with method {}", method, juri, httpRequest.getMethod());
    Request base_request = Request.getBaseRequest(request);
    base_request.setMethod(method);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest)

Example 85 with Request

use of org.eclipse.jetty.server.Request 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)

Aggregations

Request (org.eclipse.jetty.server.Request)297 HttpServletRequest (javax.servlet.http.HttpServletRequest)250 HttpServletResponse (javax.servlet.http.HttpServletResponse)225 Test (org.junit.Test)177 IOException (java.io.IOException)169 ServletException (javax.servlet.ServletException)150 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)147 CountDownLatch (java.util.concurrent.CountDownLatch)66 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)64 InterruptedIOException (java.io.InterruptedIOException)45 Server (org.eclipse.jetty.server.Server)41 InputStream (java.io.InputStream)37 AtomicReference (java.util.concurrent.atomic.AtomicReference)35 ByteArrayInputStream (java.io.ByteArrayInputStream)27 Response (org.eclipse.jetty.client.api.Response)27 Result (org.eclipse.jetty.client.api.Result)27 ServletInputStream (javax.servlet.ServletInputStream)24 ByteArrayOutputStream (java.io.ByteArrayOutputStream)23 ServletOutputStream (javax.servlet.ServletOutputStream)23 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)23