Search in sources :

Example 81 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class WebSocketServerContainerInitializer method onStartup.

@Override
public void onStartup(Set<Class<?>> c, ServletContext context) throws ServletException {
    if (!isEnabledViaContext(context, ENABLE_KEY, true)) {
        LOG.info("JSR-356 is disabled by configuration");
        return;
    }
    ContextHandler handler = ContextHandler.getContextHandler(context);
    if (handler == null) {
        throw new ServletException("Not running on Jetty, JSR-356 support unavailable");
    }
    if (!(handler instanceof ServletContextHandler)) {
        throw new ServletException("Not running in Jetty ServletContextHandler, JSR-356 support unavailable");
    }
    ServletContextHandler jettyContext = (ServletContextHandler) handler;
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(context.getClassLoader());
        // Create the Jetty ServerContainer implementation
        ServerContainer jettyContainer = configureContext(jettyContext);
        // make sure context is cleaned up when the context stops
        context.addListener(new ContextDestroyListener());
        if (c.isEmpty()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No JSR-356 annotations or interfaces discovered");
            }
            return;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found {} classes", c.size());
        }
        // Now process the incoming classes
        Set<Class<? extends Endpoint>> discoveredExtendedEndpoints = new HashSet<>();
        Set<Class<?>> discoveredAnnotatedEndpoints = new HashSet<>();
        Set<Class<? extends ServerApplicationConfig>> serverAppConfigs = new HashSet<>();
        filterClasses(c, discoveredExtendedEndpoints, discoveredAnnotatedEndpoints, serverAppConfigs);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Discovered {} extends Endpoint classes", discoveredExtendedEndpoints.size());
            LOG.debug("Discovered {} @ServerEndpoint classes", discoveredAnnotatedEndpoints.size());
            LOG.debug("Discovered {} ServerApplicationConfig classes", serverAppConfigs.size());
        }
        // Process the server app configs to determine endpoint filtering
        boolean wasFiltered = false;
        Set<ServerEndpointConfig> deployableExtendedEndpointConfigs = new HashSet<>();
        Set<Class<?>> deployableAnnotatedEndpoints = new HashSet<>();
        for (Class<? extends ServerApplicationConfig> clazz : serverAppConfigs) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found ServerApplicationConfig: {}", clazz);
            }
            try {
                ServerApplicationConfig config = clazz.newInstance();
                Set<ServerEndpointConfig> seconfigs = config.getEndpointConfigs(discoveredExtendedEndpoints);
                if (seconfigs != null) {
                    wasFiltered = true;
                    deployableExtendedEndpointConfigs.addAll(seconfigs);
                }
                Set<Class<?>> annotatedClasses = config.getAnnotatedEndpointClasses(discoveredAnnotatedEndpoints);
                if (annotatedClasses != null) {
                    wasFiltered = true;
                    deployableAnnotatedEndpoints.addAll(annotatedClasses);
                }
            } catch (InstantiationException | IllegalAccessException e) {
                throw new ServletException("Unable to instantiate: " + clazz.getName(), e);
            }
        }
        // Default behavior if nothing filtered
        if (!wasFiltered) {
            deployableAnnotatedEndpoints.addAll(discoveredAnnotatedEndpoints);
            // Note: it is impossible to determine path of "extends Endpoint" discovered classes
            deployableExtendedEndpointConfigs = new HashSet<>();
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Deploying {} ServerEndpointConfig(s)", deployableExtendedEndpointConfigs.size());
        }
        // Deploy what should be deployed.
        for (ServerEndpointConfig config : deployableExtendedEndpointConfigs) {
            try {
                jettyContainer.addEndpoint(config);
            } catch (DeploymentException e) {
                throw new ServletException(e);
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Deploying {} @ServerEndpoint(s)", deployableAnnotatedEndpoints.size());
        }
        for (Class<?> annotatedClass : deployableAnnotatedEndpoints) {
            try {
                jettyContainer.addEndpoint(annotatedClass);
            } catch (DeploymentException e) {
                throw new ServletException(e);
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServerApplicationConfig(javax.websocket.server.ServerApplicationConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ServletException(javax.servlet.ServletException) ServerEndpoint(javax.websocket.server.ServerEndpoint) Endpoint(javax.websocket.Endpoint) DeploymentException(javax.websocket.DeploymentException) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ServerContainer(org.eclipse.jetty.websocket.jsr356.server.ServerContainer) HashSet(java.util.HashSet)

Example 82 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class MessageReceivingTest method startServer.

@BeforeClass
public static void startServer() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(0);
    server.addConnector(connector);
    handler = new EchoHandler();
    ContextHandler context = new ContextHandler();
    context.setContextPath("/");
    context.setHandler(handler);
    server.setHandler(context);
    // Start Server
    server.start();
    String host = connector.getHost();
    if (host == null) {
        host = "localhost";
    }
    int port = connector.getLocalPort();
    serverUri = new URI(String.format("ws://%s:%d/", host, port));
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Server(org.eclipse.jetty.server.Server) URI(java.net.URI) Endpoint(javax.websocket.Endpoint) BeforeClass(org.junit.BeforeClass)

Example 83 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class TestServer method main.

public static void main(String[] args) throws Exception {
    ((StdErrLog) Log.getLog()).setSource(false);
    String jetty_root = "../../..";
    // Setup Threadpool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(100);
    // Setup server
    Server server = new Server(threadPool);
    server.manage(threadPool);
    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);
    server.addBean(Log.getLog());
    // Common HTTP configuration
    HttpConfiguration config = new HttpConfiguration();
    config.setSecurePort(8443);
    config.addCustomizer(new ForwardedRequestCustomizer());
    config.addCustomizer(new SecureRequestCustomizer());
    config.setSendDateHeader(true);
    config.setSendServerVersion(true);
    // Http Connector
    HttpConnectionFactory http = new HttpConnectionFactory(config);
    ServerConnector httpConnector = new ServerConnector(server, http);
    httpConnector.setPort(8080);
    httpConnector.setIdleTimeout(30000);
    server.addConnector(httpConnector);
    // Handlers
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    // Add restart handler to test the ability to save sessions and restart
    RestartHandler restart = new RestartHandler();
    restart.setHandler(handlers);
    server.setHandler(restart);
    // Setup context
    HashLoginService login = new HashLoginService();
    login.setName("Test Realm");
    login.setConfig(jetty_root + "/tests/test-webapps/test-jetty-webapp/src/main/config/demo-base/etc/realm.properties");
    server.addBean(login);
    File log = File.createTempFile("jetty-yyyy_mm_dd", "log");
    NCSARequestLog requestLog = new NCSARequestLog(log.toString());
    requestLog.setExtended(false);
    requestLogHandler.setRequestLog(requestLog);
    server.setStopAtShutdown(true);
    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/test");
    webapp.setParentLoaderPriority(true);
    webapp.setResourceBase("./src/main/webapp");
    webapp.setAttribute("testAttribute", "testValue");
    File sessiondir = File.createTempFile("sessions", null);
    if (sessiondir.exists())
        sessiondir.delete();
    sessiondir.mkdir();
    sessiondir.deleteOnExit();
    DefaultSessionCache ss = new DefaultSessionCache(webapp.getSessionHandler());
    FileSessionDataStore sds = new FileSessionDataStore();
    ss.setSessionDataStore(sds);
    sds.setStoreDir(sessiondir);
    webapp.getSessionHandler().setSessionCache(ss);
    contexts.addHandler(webapp);
    ContextHandler srcroot = new ContextHandler();
    srcroot.setResourceBase(".");
    srcroot.setHandler(new ResourceHandler());
    srcroot.setContextPath("/src");
    contexts.addHandler(srcroot);
    server.start();
    server.join();
}
Also used : DefaultSessionCache(org.eclipse.jetty.server.session.DefaultSessionCache) StdErrLog(org.eclipse.jetty.util.log.StdErrLog) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) HashLoginService(org.eclipse.jetty.security.HashLoginService) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) NCSARequestLog(org.eclipse.jetty.server.NCSARequestLog) MBeanContainer(org.eclipse.jetty.jmx.MBeanContainer) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) FileSessionDataStore(org.eclipse.jetty.server.session.FileSessionDataStore) File(java.io.File)

Example 84 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class AliasedConstraintTest method startServer.

@BeforeClass
public static void startServer() throws Exception {
    server = new Server();
    connector = new LocalConnector(server);
    server.setConnectors(new Connector[] { connector });
    ContextHandler context = new ContextHandler();
    SessionHandler session = new SessionHandler();
    TestLoginService loginService = new TestLoginService(TEST_REALM);
    loginService.putUser("user0", new Password("password"), new String[] {});
    loginService.putUser("user", new Password("password"), new String[] { "user" });
    loginService.putUser("user2", new Password("password"), new String[] { "user" });
    loginService.putUser("admin", new Password("password"), new String[] { "user", "administrator" });
    loginService.putUser("user3", new Password("password"), new String[] { "foo" });
    context.setContextPath("/ctx");
    context.setResourceBase(MavenTestingUtils.getTestResourceDir("docroot").getAbsolutePath());
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
    server.setHandler(handlers);
    context.setHandler(session);
    // context.addAliasCheck(new AllowSymLinkAliasChecker());
    server.addBean(loginService);
    security = new ConstraintSecurityHandler();
    session.setHandler(security);
    ResourceHandler handler = new ResourceHandler();
    security.setHandler(handler);
    List<ConstraintMapping> constraints = new ArrayList<>();
    Constraint constraint0 = new Constraint();
    constraint0.setAuthenticate(true);
    constraint0.setName("forbid");
    ConstraintMapping mapping0 = new ConstraintMapping();
    mapping0.setPathSpec("/forbid/*");
    mapping0.setConstraint(constraint0);
    constraints.add(mapping0);
    Set<String> knownRoles = new HashSet<>();
    knownRoles.add("user");
    knownRoles.add("administrator");
    security.setConstraintMappings(constraints, knownRoles);
    server.start();
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HandlerList(org.eclipse.jetty.server.handler.HandlerList) Server(org.eclipse.jetty.server.Server) Constraint(org.eclipse.jetty.util.security.Constraint) LocalConnector(org.eclipse.jetty.server.LocalConnector) ArrayList(java.util.ArrayList) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) Matchers.containsString(org.hamcrest.Matchers.containsString) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Password(org.eclipse.jetty.util.security.Password) HashSet(java.util.HashSet) BeforeClass(org.junit.BeforeClass)

Example 85 with ContextHandler

use of org.eclipse.jetty.server.handler.ContextHandler in project jetty.project by eclipse.

the class Server method getURI.

/* ------------------------------------------------------------ */
/**
     * @return The URI of the first {@link NetworkConnector} and first {@link ContextHandler}, or null
     */
public URI getURI() {
    NetworkConnector connector = null;
    for (Connector c : _connectors) {
        if (c instanceof NetworkConnector) {
            connector = (NetworkConnector) c;
            break;
        }
    }
    if (connector == null)
        return null;
    ContextHandler context = getChildHandlerByClass(ContextHandler.class);
    try {
        String protocol = connector.getDefaultConnectionFactory().getProtocol();
        String scheme = "http";
        if (protocol.startsWith("SSL-") || protocol.equals("SSL"))
            scheme = "https";
        String host = connector.getHost();
        if (context != null && context.getVirtualHosts() != null && context.getVirtualHosts().length > 0)
            host = context.getVirtualHosts()[0];
        if (host == null)
            host = InetAddress.getLocalHost().getHostAddress();
        String path = context == null ? null : context.getContextPath();
        if (path == null)
            path = "/";
        return new URI(scheme, null, host, connector.getLocalPort(), path, null, null);
    } catch (Exception e) {
        LOG.warn(e);
        return null;
    }
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) HttpURI(org.eclipse.jetty.http.HttpURI) URI(java.net.URI) ServletException(javax.servlet.ServletException) MultiException(org.eclipse.jetty.util.MultiException) IOException(java.io.IOException)

Aggregations

ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)127 Server (org.eclipse.jetty.server.Server)47 ServerConnector (org.eclipse.jetty.server.ServerConnector)27 URI (java.net.URI)21 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)20 Test (org.junit.Test)20 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)19 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)19 IOException (java.io.IOException)18 Handler (org.eclipse.jetty.server.Handler)14 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)14 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)14 File (java.io.File)13 ServletException (javax.servlet.ServletException)13 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)13 BeforeClass (org.junit.BeforeClass)11 BaseIntegrationTest (com.ctrip.framework.apollo.BaseIntegrationTest)10 Config (com.ctrip.framework.apollo.Config)10 ApolloConfig (com.ctrip.framework.apollo.core.dto.ApolloConfig)10 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)10