Search in sources :

Example 51 with Handler

use of org.eclipse.jetty.server.Handler in project jetty.project by eclipse.

the class SecurityHandler method handle.

/* ------------------------------------------------------------ */
/*
     * @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, int)
     */
@Override
public void handle(String pathInContext, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    final Response base_response = baseRequest.getResponse();
    final Handler handler = getHandler();
    if (handler == null)
        return;
    final Authenticator authenticator = _authenticator;
    if (checkSecurity(baseRequest)) {
        //See Servlet Spec 3.1 sec 13.6.3
        if (authenticator != null)
            authenticator.prepareRequest(baseRequest);
        RoleInfo roleInfo = prepareConstraintInfo(pathInContext, baseRequest);
        // Check data constraints
        if (!checkUserDataPermissions(pathInContext, baseRequest, base_response, roleInfo)) {
            if (!baseRequest.isHandled()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                baseRequest.setHandled(true);
            }
            return;
        }
        // is Auth mandatory?
        boolean isAuthMandatory = isAuthMandatory(baseRequest, base_response, roleInfo);
        if (isAuthMandatory && authenticator == null) {
            LOG.warn("No authenticator for: " + roleInfo);
            if (!baseRequest.isHandled()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                baseRequest.setHandled(true);
            }
            return;
        }
        // check authentication
        Object previousIdentity = null;
        try {
            Authentication authentication = baseRequest.getAuthentication();
            if (authentication == null || authentication == Authentication.NOT_CHECKED)
                authentication = authenticator == null ? Authentication.UNAUTHENTICATED : authenticator.validateRequest(request, response, isAuthMandatory);
            if (authentication instanceof Authentication.Wrapped) {
                request = ((Authentication.Wrapped) authentication).getHttpServletRequest();
                response = ((Authentication.Wrapped) authentication).getHttpServletResponse();
            }
            if (authentication instanceof Authentication.ResponseSent) {
                baseRequest.setHandled(true);
            } else if (authentication instanceof Authentication.User) {
                Authentication.User userAuth = (Authentication.User) authentication;
                baseRequest.setAuthentication(authentication);
                if (_identityService != null)
                    previousIdentity = _identityService.associate(userAuth.getUserIdentity());
                if (isAuthMandatory) {
                    boolean authorized = checkWebResourcePermissions(pathInContext, baseRequest, base_response, roleInfo, userAuth.getUserIdentity());
                    if (!authorized) {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN, "!role");
                        baseRequest.setHandled(true);
                        return;
                    }
                }
                handler.handle(pathInContext, baseRequest, request, response);
                if (authenticator != null)
                    authenticator.secureResponse(request, response, isAuthMandatory, userAuth);
            } else if (authentication instanceof Authentication.Deferred) {
                DeferredAuthentication deferred = (DeferredAuthentication) authentication;
                baseRequest.setAuthentication(authentication);
                try {
                    handler.handle(pathInContext, baseRequest, request, response);
                } finally {
                    previousIdentity = deferred.getPreviousAssociation();
                }
                if (authenticator != null) {
                    Authentication auth = baseRequest.getAuthentication();
                    if (auth instanceof Authentication.User) {
                        Authentication.User userAuth = (Authentication.User) auth;
                        authenticator.secureResponse(request, response, isAuthMandatory, userAuth);
                    } else
                        authenticator.secureResponse(request, response, isAuthMandatory, null);
                }
            } else {
                baseRequest.setAuthentication(authentication);
                if (_identityService != null)
                    previousIdentity = _identityService.associate(null);
                handler.handle(pathInContext, baseRequest, request, response);
                if (authenticator != null)
                    authenticator.secureResponse(request, response, isAuthMandatory, null);
            }
        } catch (ServerAuthException e) {
            // jaspi 3.8.3 send HTTP 500 internal server error, with message
            // from AuthException
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } finally {
            if (_identityService != null)
                _identityService.disassociate(previousIdentity);
        }
    } else
        handler.handle(pathInContext, baseRequest, request, response);
}
Also used : Handler(org.eclipse.jetty.server.Handler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) Authentication(org.eclipse.jetty.server.Authentication)

Example 52 with Handler

use of org.eclipse.jetty.server.Handler in project buck by facebook.

the class WebServer method createHandlers.

@VisibleForTesting
ImmutableList<ContextHandler> createHandlers() {
    Map<String, Handler> contextPathToHandler = Maps.newHashMap();
    contextPathToHandler.put(INDEX_CONTEXT_PATH, new TemplateHandler(new IndexHandlerDelegate()));
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase(staticContentDirectory);
    contextPathToHandler.put(STATIC_CONTEXT_PATH, resourceHandler);
    // Handlers for traces.
    BuildTraces buildTraces = new BuildTraces(projectFilesystem);
    contextPathToHandler.put(TRACE_CONTEXT_PATH, new TemplateHandler(new TraceHandlerDelegate(buildTraces)));
    contextPathToHandler.put(TRACES_CONTEXT_PATH, new TemplateHandler(new TracesHandlerDelegate(buildTraces)));
    contextPathToHandler.put(TRACE_DATA_CONTEXT_PATH, new TraceDataHandler(buildTraces));
    contextPathToHandler.put(ARTIFACTS_CONTEXT_PATH, artifactCacheHandler);
    ImmutableList.Builder<ContextHandler> handlers = ImmutableList.builder();
    for (Map.Entry<String, Handler> entry : contextPathToHandler.entrySet()) {
        String contextPath = entry.getKey();
        Handler handler = entry.getValue();
        ContextHandler contextHandler = new ContextHandler(contextPath);
        contextHandler.setHandler(handler);
        handlers.add(contextHandler);
    }
    // Create a handler that acts as a WebSocket server.
    ServletContextHandler servletContextHandler = new ServletContextHandler(/* parent */
    server, /* contextPath */
    "/ws", /* sessions */
    true, /* security */
    false);
    servletContextHandler.addServlet(new ServletHolder(streamingWebSocketServlet), "/build");
    handlers.add(servletContextHandler);
    return handlers.build();
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) BuildTraces(com.facebook.buck.util.trace.BuildTraces) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Map(java.util.Map) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 53 with Handler

use of org.eclipse.jetty.server.Handler in project buck by facebook.

the class WebServer method updateAndStartIfNeeded.

/**
   * Update state and start the server if necessary.
   *
   * @param artifactCache cache to serve.
   * @throws WebServerException
   */
public synchronized void updateAndStartIfNeeded(Optional<ArtifactCache> artifactCache) throws WebServerException {
    artifactCacheHandler.setArtifactCache(artifactCache);
    if (server.isStarted()) {
        return;
    }
    // Package up all of the handlers into a ContextHandlerCollection to serve as the handler for
    // the server.
    ImmutableList<? extends Handler> handlers = createHandlers();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[0]));
    server.setHandler(contexts);
    try {
        server.start();
    } catch (Exception e) {
        throw new WebServerException("Cannot start Websocket server.", e);
    }
}
Also used : ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection)

Example 54 with Handler

use of org.eclipse.jetty.server.Handler in project hadoop by apache.

the class HttpServer2 method start.

/**
   * Start the server. Does not wait for the server to start.
   */
public void start() throws IOException {
    try {
        try {
            openListeners();
            webServer.start();
        } catch (IOException ex) {
            LOG.info("HttpServer.start() threw a non Bind IOException", ex);
            throw ex;
        } catch (MultiException ex) {
            LOG.info("HttpServer.start() threw a MultiException", ex);
            throw ex;
        }
        // Make sure there is no handler failures.
        Handler[] hs = webServer.getHandlers();
        for (Handler handler : hs) {
            if (handler.isFailed()) {
                throw new IOException("Problem in starting http server. Server handlers failed");
            }
        }
        // Make sure there are no errors initializing the context.
        Throwable unavailableException = webAppContext.getUnavailableException();
        if (unavailableException != null) {
            // Have to stop the webserver, or else its non-daemon threads
            // will hang forever.
            webServer.stop();
            throw new IOException("Unable to initialize WebAppContext", unavailableException);
        }
    } catch (IOException e) {
        throw e;
    } catch (InterruptedException e) {
        throw (IOException) new InterruptedIOException("Interrupted while starting HTTP server").initCause(e);
    } catch (Exception e) {
        throw new IOException("Problem starting http server", e);
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ServletHandler(org.eclipse.jetty.servlet.ServletHandler) Handler(org.eclipse.jetty.server.Handler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) MultiException(org.eclipse.jetty.util.MultiException) ServletException(javax.servlet.ServletException) MultiException(org.eclipse.jetty.util.MultiException) FileNotFoundException(java.io.FileNotFoundException) BindException(java.net.BindException) InterruptedIOException(java.io.InterruptedIOException) HadoopIllegalArgumentException(org.apache.hadoop.HadoopIllegalArgumentException) IOException(java.io.IOException)

Example 55 with Handler

use of org.eclipse.jetty.server.Handler in project camel by apache.

the class JettyHttpComponent method createEndpoint.

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    // must extract well known parameters before we create the endpoint
    List<Handler> handlerList = resolveAndRemoveReferenceListParameter(parameters, "handlers", Handler.class);
    HttpBinding binding = resolveAndRemoveReferenceParameter(parameters, "httpBindingRef", HttpBinding.class);
    JettyHttpBinding jettyBinding = resolveAndRemoveReferenceParameter(parameters, "jettyHttpBindingRef", JettyHttpBinding.class);
    Boolean enableJmx = getAndRemoveParameter(parameters, "enableJmx", Boolean.class);
    Boolean enableMultipartFilter = getAndRemoveParameter(parameters, "enableMultipartFilter", Boolean.class, true);
    Filter multipartFilter = resolveAndRemoveReferenceParameter(parameters, "multipartFilterRef", Filter.class);
    List<Filter> filters = resolveAndRemoveReferenceListParameter(parameters, "filtersRef", Filter.class);
    Boolean enableCors = getAndRemoveParameter(parameters, "enableCORS", Boolean.class, false);
    HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
    UrlRewrite urlRewrite = resolveAndRemoveReferenceParameter(parameters, "urlRewrite", UrlRewrite.class);
    SSLContextParameters sslContextParameters = resolveAndRemoveReferenceParameter(parameters, "sslContextParametersRef", SSLContextParameters.class);
    SSLContextParameters ssl = sslContextParameters != null ? sslContextParameters : this.sslContextParameters;
    String proxyHost = getAndRemoveParameter(parameters, "proxyHost", String.class, getProxyHost());
    Integer proxyPort = getAndRemoveParameter(parameters, "proxyPort", Integer.class, getProxyPort());
    Integer httpClientMinThreads = getAndRemoveParameter(parameters, "httpClientMinThreads", Integer.class, this.httpClientMinThreads);
    Integer httpClientMaxThreads = getAndRemoveParameter(parameters, "httpClientMaxThreads", Integer.class, this.httpClientMaxThreads);
    HttpClient httpClient = resolveAndRemoveReferenceParameter(parameters, "httpClient", HttpClient.class);
    Boolean async = getAndRemoveParameter(parameters, "async", Boolean.class);
    // extract httpClient. parameters
    Map<String, Object> httpClientParameters = IntrospectionSupport.extractProperties(parameters, "httpClient.");
    // extract filterInit. parameters
    Map<String, String> filterInitParameters = IntrospectionSupport.extractStringProperties(IntrospectionSupport.extractProperties(parameters, "filterInit."));
    String address = remaining;
    URI addressUri = new URI(UnsafeUriCharactersEncoder.encodeHttpURI(address));
    URI endpointUri = URISupport.createRemainingURI(addressUri, parameters);
    // need to keep the httpMethodRestrict parameter for the endpointUri
    String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
    // restructure uri to be based on the parameters left as we dont want to include the Camel internal options
    URI httpUri = URISupport.createRemainingURI(addressUri, parameters);
    // create endpoint after all known parameters have been extracted from parameters
    // include component scheme in the uri
    String scheme = ObjectHelper.before(uri, ":");
    endpointUri = new URI(scheme + ":" + endpointUri);
    JettyHttpEndpoint endpoint = createEndpoint(endpointUri, httpUri);
    if (async != null) {
        endpoint.setAsync(async);
    }
    if (headerFilterStrategy != null) {
        endpoint.setHeaderFilterStrategy(headerFilterStrategy);
    } else {
        setEndpointHeaderFilterStrategy(endpoint);
    }
    // setup the proxy host and proxy port
    if (proxyHost != null) {
        endpoint.setProxyHost(proxyHost);
        endpoint.setProxyPort(proxyPort);
    }
    if (urlRewrite != null) {
        // let CamelContext deal with the lifecycle of the url rewrite
        // this ensures its being shutdown when Camel shutdown etc.
        getCamelContext().addService(urlRewrite);
        endpoint.setUrlRewrite(urlRewrite);
    }
    if (httpClientParameters != null && !httpClientParameters.isEmpty()) {
        endpoint.setHttpClientParameters(httpClientParameters);
    }
    if (filterInitParameters != null && !filterInitParameters.isEmpty()) {
        endpoint.setFilterInitParameters(filterInitParameters);
    }
    if (handlerList.size() > 0) {
        endpoint.setHandlers(handlerList);
    }
    // prefer to use endpoint configured over component configured
    if (binding == null) {
        // fallback to component configured
        binding = getHttpBinding();
    }
    if (binding != null) {
        endpoint.setBinding(binding);
    }
    // prefer to use endpoint configured over component configured
    if (jettyBinding == null) {
        // fallback to component configured
        jettyBinding = getJettyHttpBinding();
    }
    if (jettyBinding != null) {
        endpoint.setJettyBinding(jettyBinding);
    }
    if (enableJmx != null) {
        endpoint.setEnableJmx(enableJmx);
    } else {
        // set this option based on setting of JettyHttpComponent
        endpoint.setEnableJmx(isEnableJmx());
    }
    endpoint.setEnableMultipartFilter(enableMultipartFilter);
    if (multipartFilter != null) {
        endpoint.setMultipartFilter(multipartFilter);
        endpoint.setEnableMultipartFilter(true);
    }
    if (enableCors) {
        endpoint.setEnableCORS(enableCors);
        if (filters == null) {
            filters = new ArrayList<Filter>(1);
        }
        filters.add(new CrossOriginFilter());
    }
    if (filters != null) {
        endpoint.setFilters(filters);
    }
    if (httpMethodRestrict != null) {
        endpoint.setHttpMethodRestrict(httpMethodRestrict);
    }
    if (ssl != null) {
        endpoint.setSslContextParameters(ssl);
    }
    if (httpClientMinThreads != null) {
        endpoint.setHttpClientMinThreads(httpClientMinThreads);
    }
    if (httpClientMaxThreads != null) {
        endpoint.setHttpClientMaxThreads(httpClientMaxThreads);
    }
    if (httpClient != null) {
        endpoint.setHttpClient(httpClient);
    }
    endpoint.setSendServerVersion(isSendServerVersion());
    setProperties(endpoint, parameters);
    // re-create http uri after all parameters has been set on the endpoint, as the remainders are for http uri
    httpUri = URISupport.createRemainingURI(addressUri, parameters);
    endpoint.setHttpUri(httpUri);
    return endpoint;
}
Also used : UrlRewrite(org.apache.camel.http.common.UrlRewrite) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) Handler(org.eclipse.jetty.server.Handler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) HttpRestHeaderFilterStrategy(org.apache.camel.http.common.HttpRestHeaderFilterStrategy) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) URI(java.net.URI) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) Filter(javax.servlet.Filter) MultiPartFilter(org.eclipse.jetty.servlets.MultiPartFilter) CrossOriginFilter(org.eclipse.jetty.servlets.CrossOriginFilter) HttpClient(org.eclipse.jetty.client.HttpClient) HttpBinding(org.apache.camel.http.common.HttpBinding)

Aggregations

Handler (org.eclipse.jetty.server.Handler)63 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)18 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)18 Server (org.eclipse.jetty.server.Server)14 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)13 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)12 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)10 RequestLogHandler (org.eclipse.jetty.server.handler.RequestLogHandler)10 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)10 ConstraintSecurityHandler (org.eclipse.jetty.security.ConstraintSecurityHandler)7 ServerConnector (org.eclipse.jetty.server.ServerConnector)7 ErrorHandler (org.eclipse.jetty.server.handler.ErrorHandler)7 HandlerList (org.eclipse.jetty.server.handler.HandlerList)7 ArrayList (java.util.ArrayList)6 Connector (org.eclipse.jetty.server.Connector)6 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)6 Test (org.junit.Test)6 HandlerWrapper (org.eclipse.jetty.server.handler.HandlerWrapper)5 GzipHandler (org.eclipse.jetty.server.handler.gzip.GzipHandler)5 URI (java.net.URI)4