Search in sources :

Example 16 with SessionHandler

use of org.eclipse.jetty.server.session.SessionHandler in project neo4j by neo4j.

the class Jetty9WebServer method loadJAXRSResource.

private void loadJAXRSResource(SessionManager sm, String mountPoint, JaxRsServletHolderFactory jaxRsServletHolderFactory) {
    SessionHandler sessionHandler = new SessionHandler(sm);
    sessionHandler.setServer(getJetty());
    log.debug("Mounting servlet at [%s]", mountPoint);
    ServletContextHandler jerseyContext = new ServletContextHandler();
    jerseyContext.setServer(getJetty());
    jerseyContext.setErrorHandler(new NeoJettyErrorHandler());
    jerseyContext.setContextPath(mountPoint);
    jerseyContext.setSessionHandler(sessionHandler);
    jerseyContext.addServlet(jaxRsServletHolderFactory.create(defaultInjectables, wadlEnabled), "/*");
    addFiltersTo(jerseyContext);
    handlers.addHandler(jerseyContext);
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 17 with SessionHandler

use of org.eclipse.jetty.server.session.SessionHandler in project gerrit by GerritCodeReview.

the class JettyServer method makeContext.

private ContextHandler makeContext(final String contextPath, final JettyEnv env, final Config cfg) {
    final ServletContextHandler app = new ServletContextHandler();
    // This enables the use of sessions in Jetty, feature available
    // for Gerrit plug-ins to enable user-level sessions.
    //
    app.setSessionHandler(new SessionHandler());
    app.setErrorHandler(new HiddenErrorHandler());
    // This is the path we are accessed by clients within our domain.
    //
    app.setContextPath(contextPath);
    // HTTP front-end filters to be used as surrogate of Apache HTTP
    // reverse-proxy filtering.
    // It is meant to be used as simpler tiny deployment of custom-made
    // security enforcement (Security tokens, IP-based security filtering, others)
    String[] filterClassNames = cfg.getStringList("httpd", null, "filterClass");
    for (String filterClassName : filterClassNames) {
        try {
            @SuppressWarnings("unchecked") Class<? extends Filter> filterClass = (Class<? extends Filter>) Class.forName(filterClassName);
            Filter filter = env.webInjector.getInstance(filterClass);
            app.addFilter(new FilterHolder(filter), "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
        } catch (Throwable e) {
            String errorMessage = "Unable to instantiate front-end HTTP Filter " + filterClassName;
            log.error(errorMessage, e);
            throw new IllegalArgumentException(errorMessage, e);
        }
    }
    // Perform the same binding as our web.xml would do, but instead
    // of using the listener to create the injector pass the one we
    // already have built.
    //
    GuiceFilter filter = env.webInjector.getInstance(GuiceFilter.class);
    app.addFilter(new FilterHolder(filter), "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
    app.addEventListener(new GuiceServletContextListener() {

        @Override
        protected Injector getInjector() {
            return env.webInjector;
        }
    });
    // Jetty requires at least one servlet be bound before it will
    // bother running the filter above. Since the filter has all
    // of our URLs except the static resources, the only servlet
    // we need to bind is the default static resource servlet from
    // the Jetty container.
    //
    final ServletHolder ds = app.addServlet(DefaultServlet.class, "/");
    ds.setInitParameter("dirAllowed", "false");
    ds.setInitParameter("redirectWelcome", "false");
    ds.setInitParameter("useFileMappedBuffer", "false");
    ds.setInitParameter("gzip", "true");
    app.setWelcomeFiles(new String[0]);
    return app;
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) GuiceFilter(com.google.inject.servlet.GuiceFilter) Filter(javax.servlet.Filter) GuiceFilter(com.google.inject.servlet.GuiceFilter) Injector(com.google.inject.Injector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) GuiceServletContextListener(com.google.inject.servlet.GuiceServletContextListener)

Example 18 with SessionHandler

use of org.eclipse.jetty.server.session.SessionHandler in project XRTB by benmfaul.

the class Handler method run.

/**
	 * Starts the JETTY server
	 */
public void run() {
    Server server = new Server(port);
    Handler handler = new Handler();
    // org.eclipse.jetty.server.session.SessionHandler
    SessionHandler sh = new SessionHandler();
    sh.setHandler(handler);
    // set session handle
    server.setHandler(sh);
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) Server(org.eclipse.jetty.server.Server) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 19 with SessionHandler

use of org.eclipse.jetty.server.session.SessionHandler in project XRTB by benmfaul.

the class AddShutdownHook method run.

/**
	 * Establishes the HTTP Handler, creates the Jetty server and attaches the
	 * handler and then joins the server. This method does not return, but it is
	 * interruptable by calling the halt() method.
	 * 
	 */
@Override
public void run() {
    SSL ssl = Configuration.getInstance().ssl;
    if (Configuration.getInstance().port == 0 && ssl == null) {
        try {
            Controller.getInstance().sendLog(1, "RTBServer.run", "Neither HTTP or HTTPS configured, error, stop");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return;
    }
    QueuedThreadPool threadPool = new QueuedThreadPool(threads, 50);
    server = new Server(threadPool);
    ServerConnector connector = null;
    if (Configuration.getInstance().port != 0) {
        connector = new ServerConnector(server);
        connector.setPort(Configuration.getInstance().port);
        connector.setIdleTimeout(60000);
    }
    if (config.getInstance().ssl != null) {
        HttpConfiguration https = new HttpConfiguration();
        https.addCustomizer(new SecureRequestCustomizer());
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(ssl.setKeyStorePath);
        sslContextFactory.setKeyStorePassword(ssl.setKeyStorePassword);
        sslContextFactory.setKeyManagerPassword(ssl.setKeyManagerPassword);
        ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https));
        sslConnector.setPort(Configuration.getInstance().sslPort);
        if (connector != null)
            server.setConnectors(new Connector[] { connector, sslConnector });
        else
            server.setConnectors(new Connector[] { sslConnector });
        try {
            Controller.getInstance().sendLog(1, "RTBServer.run", "SSL configured on port " + Configuration.getInstance().sslPort);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else
        server.setConnectors(new Connector[] { connector });
    Handler handler = new Handler();
    node = null;
    try {
        new WebMQ(7379, null);
        BidRequest.compile();
        // org.eclipse.jetty.server.session.SessionHandler
        SessionHandler sh = new SessionHandler();
        sh.setHandler(handler);
        // set session handle
        server.setHandler(sh);
        startPeridocLogger();
        /**
			 * Override the start state if the deadmanswitch object is not null
			 * and the key doesn't exist
			 */
        if (Configuration.getInstance().deadmanSwitch != null) {
            if (Configuration.getInstance().deadmanSwitch.canRun() == false) {
                RTBServer.stopped = true;
            }
        }
        server.start();
        Thread.sleep(500);
        ready = true;
        // qps timer
        deltaTime = System.currentTimeMillis();
        Controller.getInstance().responseQueue.add(getStatus());
        Controller.getInstance().sendLog(1, "initialization", ("System start on port: " + Configuration.getInstance().port));
        startSeparateAdminServer();
        startedLatch.countDown();
        server.join();
    } catch (Exception error) {
        if (error.toString().contains("Interrupt"))
            try {
                Controller.getInstance().sendLog(1, "initialization", "HALT: : " + error.toString());
                if (node != null)
                    node.halt();
            } catch (Exception e) {
                e.printStackTrace();
            }
        else
            error.printStackTrace();
    } finally {
        if (node != null)
            node.stop();
    }
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) WebMQ(com.xrtb.jmq.WebMQ) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) AerospikeHandler(com.aerospike.redisson.AerospikeHandler) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) SSL(com.xrtb.common.SSL) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool)

Example 20 with SessionHandler

use of org.eclipse.jetty.server.session.SessionHandler in project ddf by codice.

the class FilterInjector method injectFilter.

/**
     * Injects the filter into the passed-in servlet context. This only works if
     * the servlet has not already been initialized.
     *
     * @param serviceReference Reference to the servlet context that the filter should be
     *                         injected into.
     */
public void injectFilter(ServiceReference<ServletContext> serviceReference) {
    Bundle refBundle = serviceReference.getBundle();
    LOGGER.debug("Adding Servlet Filter for {}", refBundle.getSymbolicName());
    BundleContext bundlectx = refBundle.getBundleContext();
    ServletContext context = bundlectx.getService(serviceReference);
    try {
        SessionCookieConfig sessionCookieConfig = context.getSessionCookieConfig();
        sessionCookieConfig.setPath("/");
        sessionCookieConfig.setSecure(true);
        sessionCookieConfig.setHttpOnly(true);
    } catch (Exception e) {
        LOGGER.trace("Failed trying to set the cookie config path to /. This can usually be ignored", e);
    }
    //Jetty will place non-programmatically added filters (filters added via web.xml) in front of programmatically
    //added filters. This is probably OK in most instances, however, this security filter must ALWAYS be first.
    //This reflection hack basically tricks Jetty into believing that this filter is a web.xml filter so that it always ends up first.
    //In order for this to work correctly, the delegating filter must always be added before any other programmatically added filters.
    Field field = null;
    try {
        //this grabs the enclosing instance class, which is actually a private class
        //this is the only way to do this in Java
        field = context.getClass().getDeclaredField("this$0");
        field.setAccessible(true);
    } catch (NoSuchFieldException e) {
        LOGGER.warn("Unable to find enclosing class of ServletContext for delegating filter. Security may not work correctly", e);
    }
    Field matchAfterField = null;
    Object matchAfterValue = null;
    ServletHandler handler = null;
    if (field != null) {
        //need to grab the servlet context handler so we can get down to the handler, which is what we really need
        ServletContextHandler httpServiceContext = null;
        try {
            httpServiceContext = (ServletContextHandler) field.get(context);
        } catch (IllegalAccessException e) {
            LOGGER.warn("Unable to get the ServletContextHandler for {}. The delegating filter may not work properly.", refBundle.getSymbolicName(), e);
        }
        if (httpServiceContext != null) {
            //now that we have the handler, we can muck with the filters and state variables
            handler = httpServiceContext.getServletHandler();
            SessionHandler sessionHandler = httpServiceContext.getSessionHandler();
            if (sessionHandler != null) {
                sessionHandler.addEventListener(new WrapperListener());
            }
            if (handler != null) {
                try {
                    matchAfterField = handler.getClass().getSuperclass().getDeclaredField("_matchAfterIndex");
                    matchAfterField.setAccessible(true);
                } catch (NoSuchFieldException e) {
                    LOGGER.warn("Unable to find the matchAfterIndex value for the ServletHandler. The delegating filter may not work properly.", e);
                }
                if (matchAfterField != null) {
                    try {
                        //this value is initialized to -1 and only changes after a programmatic filter has been added
                        //so basically we are grabbing this value (should be -1) and then setting the field back to that value
                        //after we add our delegating filter to the mix
                        matchAfterValue = matchAfterField.get(handler);
                    } catch (IllegalAccessException e) {
                        LOGGER.warn("Unable to get the value of the match after field. The delegating filter may not work properly.", e);
                    }
                }
            }
        }
    }
    try {
        //This causes the value of "_matchAfterIndex" to jump to 0 which means all web.xml filters will be added in front of it
        //this isn't what we want, so we need to reset it back to what it was before
        FilterRegistration filterReg = context.addFilter(DELEGATING_FILTER, delegatingServletFilter);
        if (filterReg == null) {
            filterReg = context.getFilterRegistration(DELEGATING_FILTER);
        } else {
            ((FilterRegistration.Dynamic) filterReg).setAsyncSupported(true);
        }
        filterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, ALL_URLS);
    } catch (IllegalStateException ise) {
        LOGGER.warn("Could not inject filter into {} because the servlet was already initialized.", refBundle.getSymbolicName(), ise);
    }
    if (matchAfterField != null && matchAfterValue != null) {
        try {
            //Reset the value back to what it was before we added our delegating filter, this should cause Jetty to behave as if
            //this was a filter added via web.xml
            matchAfterField.set(handler, matchAfterValue);
        } catch (IllegalAccessException e) {
            LOGGER.warn("Unable to set the match after field back to the original value. The delegating filter might be out of order", e);
        }
    } else {
        LOGGER.warn("Unable to set the match after field back to the original value. The delegating filter might be out of order.");
    }
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ServletHandler(org.eclipse.jetty.servlet.ServletHandler) Bundle(org.osgi.framework.Bundle) Field(java.lang.reflect.Field) ServletContext(javax.servlet.ServletContext) SessionCookieConfig(javax.servlet.SessionCookieConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) BundleContext(org.osgi.framework.BundleContext) FilterRegistration(javax.servlet.FilterRegistration)

Aggregations

SessionHandler (org.eclipse.jetty.server.session.SessionHandler)43 Server (org.eclipse.jetty.server.Server)13 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)10 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)10 Test (org.junit.Test)10 IOException (java.io.IOException)8 ServletException (javax.servlet.ServletException)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 HashSessionManager (org.eclipse.jetty.server.session.HashSessionManager)5 File (java.io.File)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpSession (javax.servlet.http.HttpSession)4 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)4 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)4 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)4 BeforeClass (org.junit.BeforeClass)4 ConstraintSecurityHandler (org.eclipse.jetty.security.ConstraintSecurityHandler)3 LocalConnector (org.eclipse.jetty.server.LocalConnector)3 ServerConnector (org.eclipse.jetty.server.ServerConnector)3 SessionManager (org.eclipse.jetty.server.SessionManager)3