private void addWebApp(String path, String warPath) throws Exception { if (handlerCollection != null) { // boolean extractWar = warPath.endsWith(".war"); // boolean parentLoaderPriority = true; // add it to the server // boolean restartHandler = handlerCollection.isRunning(); // if (restartHandler) { // handlerCollection.stop(); // } logger.log(Level.INFO, "Adding web app: " + warPath + " to path " + path); // create a webapp WebAppContext wah = new WebAppContext(handlerCollection, warPath, path); // configure it // wah.setExtractWAR(extractWar); // wah.setParentLoaderPriority(parentLoaderPriority); wah.setClassLoader(ObjectUtility.class.getClassLoader()); // set MeemServer classloader handlerCollection.addHandler(wah); wah.start(); // if (restartHandler) { // handlerCollection.start(); // } } }
private Server createServer(final DummyServlet servlet) throws Exception { int port; try (ServerSocket socket = new ServerSocket()) { socket.bind(new InetSocketAddress(0)); port = socket.getLocalPort(); } baseUri = new URI("http", null, "127.0.0.1", port, null, null, null); HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setSendServerVersion(false); httpConfiguration.setSendXPoweredBy(false); server = new Server(); ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration)); httpConnector.setPort(port); httpConnector.setName("http"); server.addConnector(httpConnector); ServletHolder servletHolder = new ServletHolder(servlet); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); context.addServlet(servletHolder, "/*"); HandlerCollection handlers = new HandlerCollection(); handlers.addHandler(context); server.setHandler(handlers); return server; }
/* ------------------------------------------------------------ */ public ServletContextHandler( HandlerContainer parent, String contextPath, SessionHandler sessionHandler, SecurityHandler securityHandler, ServletHandler servletHandler, ErrorHandler errorHandler, int options) { super((ContextHandler.Context) null); _options = options; _scontext = new Context(); _sessionHandler = sessionHandler; _securityHandler = securityHandler; _servletHandler = servletHandler; _objFactory = new DecoratedObjectFactory(); _objFactory.addDecorator(new DeprecationWarning()); if (contextPath != null) setContextPath(contextPath); if (parent instanceof HandlerWrapper) ((HandlerWrapper) parent).setHandler(this); else if (parent instanceof HandlerCollection) ((HandlerCollection) parent).addHandler(this); // Link the handlers relinkHandlers(); if (errorHandler != null) setErrorHandler(errorHandler); }
private Handler handlers() { HandlerList handlerList = new HandlerList(); handlerList.setHandlers(new Handler[] {webAppHandler()}); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.addHandler(handlerList); return handlerCollection; }
@Override protected void startUp() { server = new Server(); ServletContextHandler servletHandler = new ServletContextHandler(server, "/", ServletContextHandler.NO_SESSIONS); servletHandler.addServlet(DefaultServlet.class, "/"); servletHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class)); servletHandler.addEventListener(servletContextListener); HandlerCollection rootHandler = new HandlerList(); RequestLogHandler logHandler = new RequestLogHandler(); logHandler.setRequestLog(new Slf4jRequestLog()); rootHandler.addHandler(logHandler); rootHandler.addHandler(servletHandler); ServerConnector connector = new ServerConnector(server); connector.setPort(HTTP_PORT.get()); server.addConnector(connector); server.setHandler(getGzipHandler(getRewriteHandler(rootHandler))); try { connector.open(); server.start(); } catch (Exception e) { throw Throwables.propagate(e); } String host; if (connector.getHost() == null) { // Resolve the local host name. try { host = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { throw new RuntimeException("Failed to resolve local host address: " + e, e); } } else { // If jetty was configured with a specific host to bind to, use that. host = connector.getHost(); } serverAddress = HostAndPort.fromParts(host, connector.getLocalPort()); }
private void addResourceHandler(String contextPath, String filePath) throws Exception { if (handlerCollection != null) { logger.log(Level.INFO, "Adding resource : " + contextPath + "=>" + filePath); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setResourceBase(filePath); logger.log(Level.INFO, "serving: " + resourceHandler.getBaseResource()); ContextHandler contextHandler = new ContextHandler(contextPath); contextHandler.setHandler(resourceHandler); handlerCollection.addHandler(contextHandler); try { resourceHandler.start(); contextHandler.start(); } catch (Exception e) { logger.log(Level.INFO, "Could not start resource context", e); } } }
public void start(String args[]) { Logger.getRootLogger().setLevel(Level.ERROR); PropertiesManager pm = new PropertiesManager(); File propFile = new File(propFileName); if (propFile.isFile()) pm.join(propFile); pm.importSystemProps(); try { pm.update(); } catch (IllegalArgumentException e) { System.err.println("invalid configuration, can't start: " + e.getMessage()); System.exit(1); } if (pm.withjmx) { doJmx(pm); } System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog"); System.setProperty("org.eclipse.jetty.LEVEL", "DEBUG"); final Server server = new Server(); ServerConnector connector = new ServerConnector(server); if (host != null) { connector.setHost(host); } connector.setPort(port); // Let's try to start the connector before the application try { connector.open(); } catch (IOException e) { connector.close(); throw new RuntimeException("Jetty server failed to start", e); } server.setConnectors(new Connector[] {connector}); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setResourceBase(webRoot); webapp.setClassLoader(getClass().getClassLoader()); webapp.setInitParameter("propertiesFile", propFileName); ResourceHandler staticFiles = new ResourceHandler(); staticFiles.setWelcomeFiles(new String[] {"index.html"}); staticFiles.setResourceBase(webRoot); if (pm.security) { LoginService loginService = new HashLoginService("jrds", pm.userfile); server.addBean(loginService); Authenticator auth = new BasicAuthenticator(); Constraint constraint = new Constraint(); constraint.setName("jrds"); constraint.setRoles(new String[] {Constraint.ANY_ROLE}); constraint.setAuthenticate(true); constraint.setDataConstraint(Constraint.DC_NONE); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler sh = new ConstraintSecurityHandler(); sh.setConstraintMappings(Collections.singletonList(cm)); sh.setAuthenticator(auth); webapp.setSecurityHandler(sh); } HandlerCollection handlers = new HandlerList(); handlers.setHandlers(new Handler[] {staticFiles, webapp}); server.setHandler(handlers); if (pm.withjmx || MBeanServerFactory.findMBeanServer(null).size() > 0) { MBeanServer mbs = java.lang.management.ManagementFactory.getPlatformMBeanServer(); server.addBean(new MBeanContainer(mbs)); handlers.addHandler(new StatisticsHandler()); } // Properties are not needed any more pm = null; Thread finish = new Thread() { public void run() { try { server.stop(); } catch (Exception e) { throw new RuntimeException("Jetty server failed to stop", e); } } }; Runtime.getRuntime().addShutdownHook(finish); try { server.start(); server.join(); } catch (Exception e) { throw new RuntimeException("Jetty server failed to start", e); } }
protected void startServer() { if (server == null) { // stop excessive logging Log.setLog(null); System.setProperty("DEBUG", "false"); System.setProperty("VERBOSE", "false"); server = new Server(); } Connector connector = null; if (useSSL) { SslContextFactory contextFactory = new SslContextFactory(); contextFactory.setKeyStore(sslKeystore); contextFactory.setKeyStorePassword(sslPassword); contextFactory.setKeyManagerPassword(sslKeyPassword); contextFactory.setNeedClientAuth(needClientAuth); connector = new SslSelectChannelConnector(contextFactory); // Setup JSSE keystore and set parameters here correctly // connector = new SslSocketConnector(); // ((SslSocketConnector)connector).setKeystore(sslKeystore); // ((SslSocketConnector)connector).setPassword(sslPassword); // ((SslSocketConnector)connector).setKeyPassword(sslKeyPassword); // ((SslSocketConnector)connector).setNeedClientAuth(needClientAuth); // uses an entry in the keystore called "jetty" } else { // connector = new SocketConnector(); connector = new SelectChannelConnector(); } connector.setPort(port); server.addConnector(connector); // set the Server's HandlerCollection. Other handlers will be added to the HandlerCollection handlerCollection = new ContextHandlerCollection(); server.setHandler(handlerCollection); // create servlet context servletContext = new ServletContextHandler( handlerCollection, servletContextString, ServletContextHandler.SESSIONS); // servletContext = new ServletContextHandler(handlerCollection, servletContextString, // ServletContextHandler.SESSIONS); // create web app context // webAppContext = new Context(handlerCollection, webAppContextString, Context.SESSIONS); try { // add ResourceHandlers addResourceHandlers(); // add servlets to the servlet context // servletContext.addHandler(new SecurityHandler()); addServletsToContext(servletContext); // addWebApps(); // add default handler to the server handlerCollection.addHandler(new DefaultHandler()); // start a Jetty server.start(); } catch (BindException ex) { logger.log( Level.INFO, "Could not start web server on port " + port + ": " + ex.getMessage(), ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (InstantiationException ex) { logger.log(Level.INFO, "Could not add servlet: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (IllegalAccessException ex) { logger.log(Level.INFO, "Could not add servlet: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (ClassNotFoundException ex) { logger.log(Level.INFO, "Could not add servlet: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (MultiException ex) { logger.log(Level.INFO, "Problem while starting the web server: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } catch (Exception ex) { logger.log(Level.INFO, "Problem while starting the web server: ", ex); lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), false); return; } lifeCycleControlConduit.vote(meemContext.getWedgeIdentifier(), true); }
/** * Configure a jetty instance and deploy the webapps presented as args * * @param args the command line arguments * @throws Exception if unable to configure */ public void configure(String[] args) throws Exception { // handle classpath bits first so we can initialize the log mechanism. for (int i = 0; i < args.length; i++) { if ("--lib".equals(args[i])) { try (Resource lib = Resource.newResource(args[++i])) { if (!lib.exists() || !lib.isDirectory()) usage("No such lib directory " + lib); _classpath.addJars(lib); } } else if ("--jar".equals(args[i])) { try (Resource jar = Resource.newResource(args[++i])) { if (!jar.exists() || jar.isDirectory()) usage("No such jar " + jar); _classpath.addPath(jar); } } else if ("--classes".equals(args[i])) { try (Resource classes = Resource.newResource(args[++i])) { if (!classes.exists() || !classes.isDirectory()) usage("No such classes directory " + classes); _classpath.addPath(classes); } } else if (args[i].startsWith("--")) i++; } initClassLoader(); LOG.info("Runner"); LOG.debug("Runner classpath {}", _classpath); String contextPath = __defaultContextPath; boolean contextPathSet = false; int port = __defaultPort; String host = null; int stopPort = 0; String stopKey = null; boolean runnerServerInitialized = false; for (int i = 0; i < args.length; i++) { switch (args[i]) { case "--port": port = Integer.parseInt(args[++i]); break; case "--host": host = args[++i]; break; case "--stop-port": stopPort = Integer.parseInt(args[++i]); break; case "--stop-key": stopKey = args[++i]; break; case "--log": _logFile = args[++i]; break; case "--out": String outFile = args[++i]; PrintStream out = new PrintStream(new RolloverFileOutputStream(outFile, true, -1)); LOG.info("Redirecting stderr/stdout to " + outFile); System.setErr(out); System.setOut(out); break; case "--path": contextPath = args[++i]; contextPathSet = true; break; case "--config": if (_configFiles == null) _configFiles = new ArrayList<>(); _configFiles.add(args[++i]); break; case "--lib": ++i; // skip break; case "--jar": ++i; // skip break; case "--classes": ++i; // skip break; case "--stats": _enableStats = true; _statsPropFile = args[++i]; _statsPropFile = ("unsecure".equalsIgnoreCase(_statsPropFile) ? null : _statsPropFile); break; default: // process contexts if (!runnerServerInitialized) // log handlers not registered, server maybe not created, // etc { if (_server == null) // server not initialized yet { // build the server _server = new Server(); } // apply jetty config files if there are any if (_configFiles != null) { for (String cfg : _configFiles) { try (Resource resource = Resource.newResource(cfg)) { XmlConfiguration xmlConfiguration = new XmlConfiguration(resource.getURL()); xmlConfiguration.configure(_server); } } } // check that everything got configured, and if not, make the handlers HandlerCollection handlers = (HandlerCollection) _server.getChildHandlerByClass(HandlerCollection.class); if (handlers == null) { handlers = new HandlerCollection(); _server.setHandler(handlers); } // check if contexts already configured _contexts = (ContextHandlerCollection) handlers.getChildHandlerByClass(ContextHandlerCollection.class); if (_contexts == null) { _contexts = new ContextHandlerCollection(); prependHandler(_contexts, handlers); } if (_enableStats) { // if no stats handler already configured if (handlers.getChildHandlerByClass(StatisticsHandler.class) == null) { StatisticsHandler statsHandler = new StatisticsHandler(); Handler oldHandler = _server.getHandler(); statsHandler.setHandler(oldHandler); _server.setHandler(statsHandler); ServletContextHandler statsContext = new ServletContextHandler(_contexts, "/stats"); statsContext.addServlet(new ServletHolder(new StatisticsServlet()), "/"); statsContext.setSessionHandler(new SessionHandler()); if (_statsPropFile != null) { HashLoginService loginService = new HashLoginService("StatsRealm", _statsPropFile); Constraint constraint = new Constraint(); constraint.setName("Admin Only"); constraint.setRoles(new String[] {"admin"}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setLoginService(loginService); securityHandler.setConstraintMappings(Collections.singletonList(cm)); securityHandler.setAuthenticator(new BasicAuthenticator()); statsContext.setSecurityHandler(securityHandler); } } } // ensure a DefaultHandler is present if (handlers.getChildHandlerByClass(DefaultHandler.class) == null) { handlers.addHandler(new DefaultHandler()); } // ensure a log handler is present _logHandler = (RequestLogHandler) handlers.getChildHandlerByClass(RequestLogHandler.class); if (_logHandler == null) { _logHandler = new RequestLogHandler(); handlers.addHandler(_logHandler); } // check a connector is configured to listen on Connector[] connectors = _server.getConnectors(); if (connectors == null || connectors.length == 0) { ServerConnector connector = new ServerConnector(_server); connector.setPort(port); if (host != null) connector.setHost(host); _server.addConnector(connector); if (_enableStats) connector.addBean(new ConnectorStatistics()); } else { if (_enableStats) { for (Connector connector : connectors) { ((AbstractConnector) connector).addBean(new ConnectorStatistics()); } } } runnerServerInitialized = true; } // Create a context try (Resource ctx = Resource.newResource(args[i])) { if (!ctx.exists()) usage("Context '" + ctx + "' does not exist"); if (contextPathSet && !(contextPath.startsWith("/"))) contextPath = "/" + contextPath; // Configure the context if (!ctx.isDirectory() && ctx.toString().toLowerCase().endsWith(".xml")) { // It is a context config file XmlConfiguration xmlConfiguration = new XmlConfiguration(ctx.getURL()); xmlConfiguration.getIdMap().put("Server", _server); ContextHandler handler = (ContextHandler) xmlConfiguration.configure(); if (contextPathSet) handler.setContextPath(contextPath); _contexts.addHandler(handler); handler.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", __containerIncludeJarPattern); } else { // assume it is a WAR file WebAppContext webapp = new WebAppContext(_contexts, ctx.toString(), contextPath); webapp.setConfigurationClasses(__plusConfigurationClasses); webapp.setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", __containerIncludeJarPattern); } } // reset contextPathSet = false; contextPath = __defaultContextPath; break; } } if (_server == null) usage("No Contexts defined"); _server.setStopAtShutdown(true); switch ((stopPort > 0 ? 1 : 0) + (stopKey != null ? 2 : 0)) { case 1: usage("Must specify --stop-key when --stop-port is specified"); break; case 2: usage("Must specify --stop-port when --stop-key is specified"); break; case 3: ShutdownMonitor monitor = ShutdownMonitor.getInstance(); monitor.setPort(stopPort); monitor.setKey(stopKey); monitor.setExitVm(true); break; } if (_logFile != null) { NCSARequestLog requestLog = new NCSARequestLog(_logFile); requestLog.setExtended(false); _logHandler.setRequestLog(requestLog); } }
@Override public void run() { try { // Set GAE SystemProperties setSystemProperties(); // Create the server, connector and associated instances QueuedThreadPool threadpool = new QueuedThreadPool(); server = new Server(threadpool); HttpConfiguration httpConfig = new HttpConfiguration(); ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); connector.setPort(port); server.addConnector(connector); MappedByteBufferPool bufferpool = new MappedByteBufferPool(); // Basic jetty.xml handler setup HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); // TODO is a context handler collection needed for a // single context? handlers.setHandlers(new Handler[] {contexts, new DefaultHandler()}); server.setHandler(handlers); // Configuration as done by gae.mod/gae.ini httpConfig.setOutputAggregationSize(32768); threadpool.setMinThreads(10); threadpool.setMaxThreads(500); threadpool.setIdleTimeout(60000); httpConfig.setOutputBufferSize(32768); httpConfig.setRequestHeaderSize(8192); httpConfig.setResponseHeaderSize(8192); httpConfig.setSendServerVersion(true); httpConfig.setSendDateHeader(false); httpConfig.setDelayDispatchUntilContent(false); // Setup Server as done by gae.xml server.addBean(bufferpool); httpConfig.setHeaderCacheSize(512); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.addHandler(requestLogHandler); File logs = File.createTempFile("logs", "logs"); logs.delete(); logs.mkdirs(); NCSARequestLog requestLog = new NCSARequestLog(logs.getCanonicalPath() + "/request.yyyy_mm_dd.log"); requestLogHandler.setRequestLog(requestLog); requestLog.setRetainDays(2); requestLog.setAppend(true); requestLog.setExtended(true); requestLog.setLogTimeZone("GMT"); requestLog.setLogLatency(true); requestLog.setPreferProxiedForAddress(true); // Ugly hack to delete possible previous run lock file new File("target/log.0.lck").delete(); new File("target/log.0.1.lck").delete(); // configuration from root.xml VmRuntimeWebAppContext context = new VmRuntimeWebAppContext(); context.setContextPath("/"); // find the sibling testwebapp target File currentDir = new File("").getAbsoluteFile(); File webAppLocation = new File(currentDir, "target/webapps/testwebapp"); context.setResourceBase(webAppLocation.getAbsolutePath()); context.init("WEB-INF/appengine-web.xml"); context.setParentLoaderPriority(true); // true in tests for easier mocking // Hack to find the webdefault.xml File webDefault = new File(currentDir.getParentFile(), "docker/etc/webdefault.xml"); context.setDefaultsDescriptor(webDefault.getAbsolutePath()); contexts.addHandler(context); // start and join server.start(); } catch (Exception e) { e.printStackTrace(); } finally { started.countDown(); } try { if (Log.getLogger(Server.class).isDebugEnabled()) server.dumpStdErr(); server.join(); } catch (Exception e) { e.printStackTrace(); } }
@SuppressWarnings({"deprecation"}) public HttpServer( HttpServerInfo httpServerInfo, NodeInfo nodeInfo, HttpServerConfig config, Servlet theServlet, Map<String, String> parameters, Set<Filter> filters, Set<HttpResourceBinding> resources, Servlet theAdminServlet, Map<String, String> adminParameters, Set<Filter> adminFilters, MBeanServer mbeanServer, LoginService loginService, TraceTokenManager tokenManager, RequestStats stats, EventClient eventClient) throws IOException { Preconditions.checkNotNull(httpServerInfo, "httpServerInfo is null"); Preconditions.checkNotNull(nodeInfo, "nodeInfo is null"); Preconditions.checkNotNull(config, "config is null"); Preconditions.checkNotNull(theServlet, "theServlet is null"); QueuedThreadPool threadPool = new QueuedThreadPool(config.getMaxThreads()); threadPool.setMinThreads(config.getMinThreads()); threadPool.setIdleTimeout(Ints.checkedCast(config.getThreadMaxIdleTime().toMillis())); threadPool.setName("http-worker"); server = new Server(threadPool); if (config.isShowStackTrace()) { server.addBean(new ErrorHandler()); } if (mbeanServer != null) { // export jmx mbeans if a server was provided MBeanContainer mbeanContainer = new MBeanContainer(mbeanServer); server.addBean(mbeanContainer); } // set up HTTP connector if (config.isHttpEnabled()) { HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setSendServerVersion(false); httpConfiguration.setSendXPoweredBy(false); if (config.getMaxRequestHeaderSize() != null) { httpConfiguration.setRequestHeaderSize( Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes())); } // if https is enabled, set the CONFIDENTIAL and INTEGRAL redirection information if (config.isHttpsEnabled()) { httpConfiguration.setSecureScheme("https"); httpConfiguration.setSecurePort(httpServerInfo.getHttpsUri().getPort()); } Integer acceptors = config.getHttpAcceptorThreads(); Integer selectors = config.getHttpSelectorThreads(); httpConnector = new ServerConnector( server, null, null, null, acceptors == null ? -1 : acceptors, selectors == null ? -1 : selectors, new HttpConnectionFactory(httpConfiguration)); httpConnector.setName("http"); httpConnector.setPort(httpServerInfo.getHttpUri().getPort()); httpConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis()); httpConnector.setHost(nodeInfo.getBindIp().getHostAddress()); httpConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize()); server.addConnector(httpConnector); } else { httpConnector = null; } // set up NIO-based HTTPS connector if (config.isHttpsEnabled()) { HttpConfiguration httpsConfiguration = new HttpConfiguration(); httpsConfiguration.setSendServerVersion(false); httpsConfiguration.setSendXPoweredBy(false); if (config.getMaxRequestHeaderSize() != null) { httpsConfiguration.setRequestHeaderSize( Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes())); } httpsConfiguration.addCustomizer(new SecureRequestCustomizer()); SslContextFactory sslContextFactory = new SslContextFactory(config.getKeystorePath()); sslContextFactory.setKeyStorePassword(config.getKeystorePassword()); SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, "http/1.1"); Integer acceptors = config.getHttpsAcceptorThreads(); Integer selectors = config.getHttpsSelectorThreads(); httpsConnector = new ServerConnector( server, null, null, null, acceptors == null ? -1 : acceptors, selectors == null ? -1 : selectors, sslConnectionFactory, new HttpConnectionFactory(httpsConfiguration)); httpsConnector.setName("https"); httpsConnector.setPort(httpServerInfo.getHttpsUri().getPort()); httpsConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis()); httpsConnector.setHost(nodeInfo.getBindIp().getHostAddress()); httpsConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize()); server.addConnector(httpsConnector); } else { httpsConnector = null; } // set up NIO-based Admin connector if (theAdminServlet != null && config.isAdminEnabled()) { HttpConfiguration adminConfiguration = new HttpConfiguration(); adminConfiguration.setSendServerVersion(false); adminConfiguration.setSendXPoweredBy(false); if (config.getMaxRequestHeaderSize() != null) { adminConfiguration.setRequestHeaderSize( Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes())); } QueuedThreadPool adminThreadPool = new QueuedThreadPool(config.getAdminMaxThreads()); adminThreadPool.setName("http-admin-worker"); adminThreadPool.setMinThreads(config.getAdminMinThreads()); adminThreadPool.setIdleTimeout(Ints.checkedCast(config.getThreadMaxIdleTime().toMillis())); if (config.isHttpsEnabled()) { adminConfiguration.addCustomizer(new SecureRequestCustomizer()); SslContextFactory sslContextFactory = new SslContextFactory(config.getKeystorePath()); sslContextFactory.setKeyStorePassword(config.getKeystorePassword()); SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, "http/1.1"); adminConnector = new ServerConnector( server, adminThreadPool, null, null, 0, -1, sslConnectionFactory, new HttpConnectionFactory(adminConfiguration)); } else { adminConnector = new ServerConnector( server, adminThreadPool, null, null, 0, -1, new HttpConnectionFactory(adminConfiguration)); } adminConnector.setName("admin"); adminConnector.setPort(httpServerInfo.getAdminUri().getPort()); adminConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis()); adminConnector.setHost(nodeInfo.getBindIp().getHostAddress()); adminConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize()); server.addConnector(adminConnector); } else { adminConnector = null; } /** * structure is: * * <p>server |--- statistics handler |--- context handler | |--- trace token filter | |--- gzip * response filter | |--- gzip request filter | |--- security handler | |--- user provided * filters | |--- the servlet (normally GuiceContainer) | |--- resource handlers |--- log * handler |-- admin context handler \ --- the admin servlet */ HandlerCollection handlers = new HandlerCollection(); for (HttpResourceBinding resource : resources) { handlers.addHandler( new ClassPathResourceHandler( resource.getBaseUri(), resource.getClassPathResourceBase(), resource.getWelcomeFiles())); } handlers.addHandler( createServletContext( theServlet, parameters, filters, tokenManager, loginService, "http", "https")); if (config.isLogEnabled()) { handlers.addHandler(createLogHandler(config, tokenManager, eventClient)); } RequestLogHandler statsRecorder = new RequestLogHandler(); statsRecorder.setRequestLog(new StatsRecordingHandler(stats)); handlers.addHandler(statsRecorder); // add handlers to Jetty StatisticsHandler statsHandler = new StatisticsHandler(); statsHandler.setHandler(handlers); HandlerList rootHandlers = new HandlerList(); if (theAdminServlet != null && config.isAdminEnabled()) { rootHandlers.addHandler( createServletContext( theAdminServlet, adminParameters, adminFilters, tokenManager, loginService, "admin")); } rootHandlers.addHandler(statsHandler); server.setHandler(rootHandlers); }