Search in sources :

Example 16 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project spark by perwendel.

the class EmbeddedJettyServer method ignite.

/**
     * {@inheritDoc}
     */
@Override
public int ignite(String host, int port, SslStores sslStores, int maxThreads, int minThreads, int threadIdleTimeoutMillis) {
    if (port == 0) {
        try (ServerSocket s = new ServerSocket(0)) {
            port = s.getLocalPort();
        } catch (IOException e) {
            logger.error("Could not get first available port (port set to 0), using default: {}", SPARK_DEFAULT_PORT);
            port = SPARK_DEFAULT_PORT;
        }
    }
    server = JettyServer.create(maxThreads, minThreads, threadIdleTimeoutMillis);
    ServerConnector connector;
    if (sslStores == null) {
        connector = SocketConnectorFactory.createSocketConnector(server, host, port);
    } else {
        connector = SocketConnectorFactory.createSecureSocketConnector(server, host, port, sslStores);
    }
    server = connector.getServer();
    server.setConnectors(new Connector[] { connector });
    ServletContextHandler webSocketServletContextHandler = WebSocketServletContextHandlerFactory.create(webSocketHandlers, webSocketIdleTimeoutMillis);
    // Handle web socket routes
    if (webSocketServletContextHandler == null) {
        server.setHandler(handler);
    } else {
        List<Handler> handlersInList = new ArrayList<>();
        handlersInList.add(handler);
        // WebSocket handler must be the last one
        if (webSocketServletContextHandler != null) {
            handlersInList.add(webSocketServletContextHandler);
        }
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(handlersInList.toArray(new Handler[handlersInList.size()]));
        server.setHandler(handlers);
    }
    try {
        logger.info("== {} has ignited ...", NAME);
        logger.info(">> Listening on {}:{}", host, port);
        server.start();
    } catch (Exception e) {
        logger.error("ignite failed", e);
        System.exit(100);
    }
    return port;
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) HandlerList(org.eclipse.jetty.server.handler.HandlerList) ArrayList(java.util.ArrayList) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Handler(org.eclipse.jetty.server.Handler) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) IOException(java.io.IOException)

Example 17 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project graphhopper by graphhopper.

the class GHServer method start.

public void start(Injector injector) throws Exception {
    ResourceHandler resHandler = new ResourceHandler();
    resHandler.setDirectoriesListed(false);
    resHandler.setWelcomeFiles(new String[] { "index.html" });
    resHandler.setResourceBase(args.get("jetty.resourcebase", "./web/src/main/webapp"));
    server = new Server();
    // getSessionHandler and getSecurityHandler should always return null
    ServletContextHandler servHandler = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
    servHandler.setErrorHandler(new GHErrorHandler());
    servHandler.setContextPath("/");
    servHandler.addServlet(new ServletHolder(new InvalidRequestServlet()), "/*");
    FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
    servHandler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));
    ServerConnector connector0 = new ServerConnector(server);
    int httpPort = args.getInt("jetty.port", 8989);
    String host = args.get("jetty.host", "");
    connector0.setPort(httpPort);
    int requestHeaderSize = args.getInt("jetty.request_header_size", -1);
    if (requestHeaderSize > 0)
        connector0.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration().setRequestHeaderSize(requestHeaderSize);
    if (!host.isEmpty())
        connector0.setHost(host);
    server.addConnector(connector0);
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { resHandler, servHandler });
    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setIncludedMethods("GET", "POST");
    // Note: gzip only affects the response body like our previous 'GHGZIPHook' behaviour: http://stackoverflow.com/a/31565805/194609
    // If no mimeTypes are defined the content-type is "not 'application/gzip'", See also https://github.com/graphhopper/directions-api/issues/28 for pitfalls
    // gzipHandler.setIncludedMimeTypes();
    gzipHandler.setHandler(handlers);
    server.setHandler(gzipHandler);
    server.start();
    logger.info("Started server at HTTP " + host + ":" + httpPort);
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) GuiceFilter(com.google.inject.servlet.GuiceFilter) GzipHandler(org.eclipse.jetty.server.handler.gzip.GzipHandler) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) DispatcherType(javax.servlet.DispatcherType)

Example 18 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project opennms by OpenNMS.

the class JUnitServer method initializeServerWithConfig.

protected void initializeServerWithConfig(final JUnitHttpServer config) {
    Server server = null;
    if (config.https()) {
        server = new Server();
        // SSL context configuration
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(config.keystore());
        sslContextFactory.setKeyStorePassword(config.keystorePassword());
        sslContextFactory.setKeyManagerPassword(config.keyPassword());
        sslContextFactory.setTrustStorePath(config.keystore());
        sslContextFactory.setTrustStorePassword(config.keystorePassword());
        // HTTP Configuration
        HttpConfiguration http_config = new HttpConfiguration();
        http_config.setSecureScheme("https");
        http_config.setSecurePort(config.port());
        http_config.setOutputBufferSize(32768);
        http_config.setRequestHeaderSize(8192);
        http_config.setResponseHeaderSize(8192);
        http_config.setSendServerVersion(true);
        http_config.setSendDateHeader(false);
        // SSL HTTP Configuration
        HttpConfiguration https_config = new HttpConfiguration(http_config);
        https_config.addCustomizer(new SecureRequestCustomizer());
        // SSL Connector
        ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
        sslConnector.setPort(config.port());
        server.addConnector(sslConnector);
    } else {
        server = new Server(config.port());
    }
    m_server = server;
    final ContextHandler context1 = new ContextHandler();
    context1.setContextPath("/");
    context1.setWelcomeFiles(new String[] { "index.html" });
    context1.setResourceBase(config.resource());
    context1.setClassLoader(Thread.currentThread().getContextClassLoader());
    context1.setVirtualHosts(config.vhosts());
    final ContextHandler context = context1;
    Handler topLevelHandler = null;
    final HandlerList handlers = new HandlerList();
    if (config.basicAuth()) {
        // check for basic auth if we're configured to do so
        LOG.debug("configuring basic auth");
        final HashLoginService loginService = new HashLoginService("MyRealm", config.basicAuthFile());
        loginService.setHotReload(true);
        m_server.addBean(loginService);
        final ConstraintSecurityHandler security = new ConstraintSecurityHandler();
        final Set<String> knownRoles = new HashSet<String>();
        knownRoles.add("user");
        knownRoles.add("admin");
        knownRoles.add("moderator");
        final Constraint constraint = new Constraint();
        constraint.setName("auth");
        constraint.setAuthenticate(true);
        constraint.setRoles(knownRoles.toArray(new String[0]));
        final ConstraintMapping mapping = new ConstraintMapping();
        mapping.setPathSpec("/*");
        mapping.setConstraint(constraint);
        security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
        security.setAuthenticator(new BasicAuthenticator());
        security.setLoginService(loginService);
        security.setRealmName("MyRealm");
        security.setHandler(context);
        topLevelHandler = security;
    } else {
        topLevelHandler = context;
    }
    final Webapp[] webapps = config.webapps();
    if (webapps != null) {
        for (final Webapp webapp : webapps) {
            final WebAppContext wac = new WebAppContext();
            String path = null;
            if (!"".equals(webapp.pathSystemProperty()) && System.getProperty(webapp.pathSystemProperty()) != null) {
                path = System.getProperty(webapp.pathSystemProperty());
            } else {
                path = webapp.path();
            }
            if (path == null || "".equals(path)) {
                throw new IllegalArgumentException("path or pathSystemProperty of @Webapp points to a null or blank value");
            }
            wac.setWar(path);
            wac.setContextPath(webapp.context());
            handlers.addHandler(wac);
        }
    }
    final ResourceHandler rh = new ResourceHandler();
    rh.setWelcomeFiles(new String[] { "index.html" });
    rh.setResourceBase(config.resource());
    handlers.addHandler(rh);
    // fall through to default
    handlers.addHandler(new DefaultHandler());
    context.setHandler(handlers);
    m_server.setHandler(topLevelHandler);
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) JUnitHttpServer(org.opennms.core.test.http.annotations.JUnitHttpServer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) Constraint(org.eclipse.jetty.util.security.Constraint) Handler(org.eclipse.jetty.server.Handler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) 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) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HashLoginService(org.eclipse.jetty.security.HashLoginService) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) HashSet(java.util.HashSet) Webapp(org.opennms.core.test.http.annotations.Webapp)

Example 19 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project async-http-client by AsyncHttpClient.

the class RedirectTest method setUpGlobal.

@BeforeClass
@Override
public void setUpGlobal() throws Exception {
    server = new Server();
    ServerConnector connector1 = addHttpConnector(server);
    ServerConnector connector2 = addHttpConnector(server);
    HandlerList list = new HandlerList();
    list.addHandler(new AbstractHandler() {

        @Override
        public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
            if (request.getLocalPort() == port2) {
                httpServletResponse.sendRedirect(getTargetUrl());
            }
        }
    });
    list.addHandler(getWebSocketHandler());
    server.setHandler(list);
    server.start();
    port1 = connector1.getLocalPort();
    port2 = connector2.getLocalPort();
    logger.info("Local HTTP server started successfully");
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) HandlerList(org.eclipse.jetty.server.handler.HandlerList) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Server(org.eclipse.jetty.server.Server) 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) BeforeClass(org.testng.annotations.BeforeClass)

Example 20 with HandlerList

use of org.eclipse.jetty.server.handler.HandlerList in project calcite-avatica by apache.

the class HttpServer method internalStart.

protected void internalStart() {
    if (server != null) {
        throw new RuntimeException("Server is already started");
    }
    final QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setDaemon(true);
    server = new Server(threadPool);
    server.manage(threadPool);
    final ServerConnector connector = configureConnector(getConnector(), port);
    ConstraintSecurityHandler securityHandler = null;
    if (null != this.config) {
        switch(config.getAuthenticationType()) {
            case SPNEGO:
                // Get the Handler for SPNEGO authentication
                securityHandler = configureSpnego(server, connector, this.config);
                break;
            case BASIC:
                securityHandler = configureBasicAuthentication(server, connector, config);
                break;
            case DIGEST:
                securityHandler = configureDigestAuthentication(server, connector, config);
                break;
            default:
                // Pass
                break;
        }
    }
    server.setConnectors(new Connector[] { connector });
    // Default to using the handler that was passed in
    final HandlerList handlerList = new HandlerList();
    Handler avaticaHandler = handler;
    // Wrap the provided handler for security if we made one
    if (null != securityHandler) {
        securityHandler.setHandler(handler);
        avaticaHandler = securityHandler;
    }
    handlerList.setHandlers(new Handler[] { avaticaHandler, new DefaultHandler() });
    server.setHandler(handlerList);
    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    port = connector.getLocalPort();
    LOG.info("Service listening on port {}.", getPort());
    // Set the information about the address for this server
    try {
        this.handler.setServerRpcMetadata(createRpcServerMetadata(connector));
    } catch (UnknownHostException e) {
        // Failed to do the DNS lookup, bail out.
        throw new RuntimeException(e);
    }
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) HandlerList(org.eclipse.jetty.server.handler.HandlerList) Server(org.eclipse.jetty.server.Server) UnknownHostException(java.net.UnknownHostException) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) Handler(org.eclipse.jetty.server.Handler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) LoginException(javax.security.auth.login.LoginException) UnknownHostException(java.net.UnknownHostException) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler)

Aggregations

HandlerList (org.eclipse.jetty.server.handler.HandlerList)35 Server (org.eclipse.jetty.server.Server)19 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)17 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)13 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)11 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)8 Handler (org.eclipse.jetty.server.Handler)7 IOException (java.io.IOException)6 Test (org.junit.Test)6 ServerConnector (org.eclipse.jetty.server.ServerConnector)5 DefaultServlet (org.eclipse.jetty.servlet.DefaultServlet)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 File (java.io.File)3 URI (java.net.URI)3 ArrayList (java.util.ArrayList)3 ServletException (javax.servlet.ServletException)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)3 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)3