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; }
protected void prependHandler(Handler handler, HandlerCollection handlers) { if (handler == null || handlers == null) return; Handler[] existing = handlers.getChildHandlers(); Handler[] children = new Handler[existing.length + 1]; children[0] = handler; System.arraycopy(existing, 0, children, 1, existing.length); handlers.setHandlers(children); }
private Handler handlers() { HandlerList handlerList = new HandlerList(); handlerList.setHandlers(new Handler[] {webAppHandler()}); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.addHandler(handlerList); return handlerCollection; }
private ContextHandlerCollection findContextHandlerCollection(Handler[] handlers) { if (handlers == null) return null; for (Handler handler : handlers) { if (handler instanceof ContextHandlerCollection) { return (ContextHandlerCollection) handler; } if (handler instanceof HandlerCollection) { HandlerCollection hc = (HandlerCollection) handler; ContextHandlerCollection chc = findContextHandlerCollection(hc.getHandlers()); if (chc != null) return chc; } } return null; }
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(); // } } }
/* ------------------------------------------------------------ */ 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); }
@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()); }
public AuthenticationServer(Integer port) { server = new BlockingServer(port); Constraint constraint = new Constraint(); constraint.setName(Constraint.__BASIC_AUTH); constraint.setRoles(new String[] {"user", "admin", "moderator"}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); ConstraintSecurityHandler sh = new ConstraintSecurityHandler(); loginService = new HashLoginService("MyRealm"); sh.setLoginService(loginService); sh.setConstraintMappings(new ConstraintMapping[] {cm}); sh.setStrict(false); accessedUri = new ArrayList<String>(); Handler handler = new AbstractHandler() { public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hello</h1>"); ((Request) request).setHandled(true); accessedUri.add(((Request) request).getUri().toString()); } }; HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] {handler, new DefaultHandler()}); sh.setHandler(handlers); server.setHandler(sh); }
@Override public HttpServer createHttpServer(InetSocketAddress addr, int backlog) throws IOException { Server server = _server; boolean shared = true; if (server == null) { server = new Server(); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers( new Handler[] {new ContextHandlerCollection(), new DefaultHandler()}); server.setHandler(handlerCollection); shared = false; } JettyHttpServer jettyHttpServer = new JettyHttpServer(server, shared); jettyHttpServer.bind(addr, backlog); return jettyHttpServer; }
/** Hook up Jetty handlers. Do this before start() is called. */ public void registerHandlers(HandlerWrapper s) { GateHandler gh = new GateHandler(); AddCommonResponseHeadersHandler rhh = new AddCommonResponseHeadersHandler(); AuthenticationHandler authh = new AuthenticationHandler(); ExtensionHandler1 eh1 = new ExtensionHandler1(); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(H2oNpsBinServlet.class, "/3/NodePersistentStorage.bin/*"); context.addServlet(H2oPostFileServlet.class, "/3/PostFile.bin"); context.addServlet(H2oPostFileServlet.class, "/3/PostFile"); context.addServlet(H2oDatasetServlet.class, "/3/DownloadDataset"); context.addServlet(H2oDatasetServlet.class, "/3/DownloadDataset.bin"); context.addServlet(H2oDefaultServlet.class, "/"); Handler[] handlers = {gh, rhh, authh, eh1, context}; HandlerCollection hc = new HandlerCollection(); hc.setHandlers(handlers); s.setHandler(hc); }
@BeforeClass public static void startServer() throws Exception { server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(PORT); server.setConnectors(new Connector[] {connector}); WebAppContext webappcontext = new WebAppContext(); webappcontext.setContextPath("/"); String warPath = null; warPath = JAXRPCTest.class.getResource("/webapp").toURI().getPath(); webappcontext.setWar(warPath); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()}); server.setHandler(handlers); server.start(); }
public static void main(String[] args) { Server server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(8080); server.setConnectors(new Connector[] {connector}); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addServlet(HelloServlet.class, "/hello"); context.addServlet(EchoServlet.class, "/echo/*"); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] {context, new DefaultHandler()}); server.setHandler(handlers); try { server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
public static void configureJetty(Server server, HandlerCollection collection) { Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server); classlist.addBefore( "org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration"); // Set the ContainerIncludeJarPattern so that jetty examines these // container-path jars for tlds, web-fragments etc. // If you omit the jar that contains the jstl .tlds, the jsp engine will // scan for them instead. for (Handler handler : collection.getHandlers()) { if (handler instanceof WebAppContext) { ((WebAppContext) handler) .setAttribute( "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$"); } } }
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); } } }
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); } }
public Server getJettyServer(int port, int sslPort, int maxThreads) throws IOException { Server server = new Server(); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); server.setThreadPool(new QueuedThreadPool(maxThreads)); SslSocketConnector sslSocketConnector = null; if (sslPort > 0) { System.out.println("SSL is Starting on port " + sslPort + "..."); sslSocketConnector = new SslSocketConnector(); sslSocketConnector.setPort(getContainerConfig().getSSLPort()); sslSocketConnector.setKeystore("conf/servertestkeystore"); sslSocketConnector.setPassword(getContainerConfig().getSSLKeyPassword()); sslSocketConnector.setKeyPassword(getContainerConfig().getSSLKeyStorePassword()); sslSocketConnector.setTruststore("conf/servertestkeystore"); sslSocketConnector.setTrustPassword(getContainerConfig().getSSLKeyStorePassword()); } else if (getContainerConfig().isAcEnabled()) logger.error("SSL MUST be configured in the gsn.xml file when Access Control is enabled !"); AbstractConnector connector = new SelectChannelConnector(); // before was connector//new SocketConnector ();//using basic // connector for windows bug; Fast // option=>SelectChannelConnector connector.setPort(port); connector.setMaxIdleTime(30000); connector.setAcceptors(2); connector.setConfidentialPort(sslPort); if (sslSocketConnector == null) server.setConnectors(new Connector[] {connector}); else server.setConnectors(new Connector[] {connector, sslSocketConnector}); WebAppContext webAppContext = new WebAppContext(contexts, DEFAULT_WEB_APP_PATH, "/"); handlers.setHandlers(new Handler[] {contexts, new DefaultHandler()}); server.setHandler(handlers); Properties usernames = new Properties(); usernames.load(new FileReader("conf/realm.properties")); if (!usernames.isEmpty()) { HashLoginService loginService = new HashLoginService(); loginService.setName("GSNRealm"); loginService.setConfig("conf/realm.properties"); loginService.setRefreshInterval(10000); // re-reads the file every 10 seconds. Constraint constraint = new Constraint(); constraint.setName("GSN User"); constraint.setRoles(new String[] {"gsnuser"}); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping(); cm.setConstraint(constraint); cm.setPathSpec("/*"); cm.setMethod("GET"); ConstraintMapping cm2 = new ConstraintMapping(); cm2.setConstraint(constraint); cm2.setPathSpec("/*"); cm2.setMethod("POST"); ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setLoginService(loginService); securityHandler.setConstraintMappings(new ConstraintMapping[] {cm, cm2}); securityHandler.setAuthenticator(new BasicAuthenticator()); webAppContext.setSecurityHandler(securityHandler); } server.setSendServerVersion(true); server.setStopAtShutdown(true); server.setSendServerVersion(false); server.setSessionIdManager(new HashSessionIdManager(new Random())); return server; }
public static void main(String[] args) throws Exception { String jetty_home = System.getProperty("jetty.home", "../../jetty-distribution/target/distribution"); System.setProperty("jetty.home", jetty_home); // Setup Threadpool QueuedThreadPool threadPool = new QueuedThreadPool(512); Server server = new Server(threadPool); server.manage(threadPool); server.setDumpAfterStart(false); server.setDumpBeforeStop(false); // Setup JMX MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); server.addBean(mbContainer); // Common HTTP configuration HttpConfiguration config = new HttpConfiguration(); config.setSecurePort(8443); config.addCustomizer(new ForwardedRequestCustomizer()); config.addCustomizer(new SecureRequestCustomizer()); config.setSendServerVersion(true); // Http Connector HttpConnectionFactory http = new HttpConnectionFactory(config); ServerConnector httpConnector = new ServerConnector(server, http); httpConnector.setPort(8080); httpConnector.setIdleTimeout(10000); server.addConnector(httpConnector); // SSL configurations SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore"); sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g"); sslContextFactory.setTrustStorePath(jetty_home + "/etc/keystore"); sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); sslContextFactory.setExcludeCipherSuites( "SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"); // Spdy Connector SPDYServerConnectionFactory.checkNPNAvailable(); PushStrategy push = new ReferrerPushStrategy(); HTTPSPDYServerConnectionFactory spdy2 = new HTTPSPDYServerConnectionFactory(2, config, push); spdy2.setInputBufferSize(8192); spdy2.setInitialWindowSize(32768); HTTPSPDYServerConnectionFactory spdy3 = new HTTPSPDYServerConnectionFactory(3, config, push); spdy2.setInputBufferSize(8192); NPNServerConnectionFactory npn = new NPNServerConnectionFactory( spdy3.getProtocol(), spdy2.getProtocol(), http.getProtocol()); npn.setDefaultProtocol(http.getProtocol()); npn.setInputBufferSize(1024); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, npn.getProtocol()); ServerConnector spdyConnector = new ServerConnector(server, ssl, npn, spdy3, spdy2, http); spdyConnector.setPort(8443); server.addConnector(spdyConnector); // Setup handlers HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] {contexts, new DefaultHandler(), requestLogHandler}); StatisticsHandler stats = new StatisticsHandler(); stats.setHandler(handlers); server.setHandler(stats); // Setup deployers DeploymentManager deployer = new DeploymentManager(); deployer.setContexts(contexts); server.addBean(deployer); WebAppProvider webapp_provider = new WebAppProvider(); webapp_provider.setMonitoredDirName(jetty_home + "/webapps"); webapp_provider.setParentLoaderPriority(false); webapp_provider.setExtractWars(true); webapp_provider.setScanInterval(2); webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml"); deployer.addAppProvider(webapp_provider); HashLoginService login = new HashLoginService(); login.setName("Test Realm"); login.setConfig(jetty_home + "/etc/realm.properties"); server.addBean(login); NCSARequestLog requestLog = new AsyncNCSARequestLog(); requestLog.setFilename(jetty_home + "/logs/jetty-yyyy_mm_dd.log"); requestLog.setExtended(false); requestLogHandler.setRequestLog(requestLog); server.setStopAtShutdown(true); server.start(); server.dumpStdErr(); server.join(); }
@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(); } }
/** Starts the Jetty instance. */ public void startup() { restartNeeded = false; // Add listener for certificate events certificateListener = new CertificateListener(); CertificateManager.addListener(certificateListener); adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090); adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091); adminServer = new Server(); final QueuedThreadPool tp = new QueuedThreadPool(254); tp.setName("Jetty-QTP-AdminConsole"); adminServer.setThreadPool(tp); // Do not send Jetty info in HTTP headers adminServer.setSendServerVersion(false); // Create connector for http traffic if it's enabled. if (adminPort > 0) { Connector httpConnector = new SelectChannelConnector(); // Listen on a specific network interface if it has been set. String bindInterface = getBindInterface(); httpConnector.setHost(bindInterface); httpConnector.setPort(adminPort); adminServer.addConnector(httpConnector); } // Create a connector for https traffic if it's enabled. sslEnabled = false; try { if (adminSecurePort > 0 && CertificateManager.isRSACertificate(SSLConfig.getKeyStore(), "*")) { if (!CertificateManager.isRSACertificate( SSLConfig.getKeyStore(), XMPPServer.getInstance().getServerInfo().getXMPPDomain())) { Log.warn( "Admin console: Using RSA certificates but they are not valid for the hosted domain"); } JiveSslConnector httpsConnector = new JiveSslConnector(); String bindInterface = getBindInterface(); httpsConnector.setHost(bindInterface); httpsConnector.setPort(adminSecurePort); httpsConnector.setTrustPassword(SSLConfig.gets2sTrustPassword()); httpsConnector.setTruststoreType(SSLConfig.getStoreType()); httpsConnector.setTruststore(SSLConfig.gets2sTruststoreLocation()); httpsConnector.setNeedClientAuth(false); httpsConnector.setWantClientAuth(false); httpsConnector.setKeyPassword(SSLConfig.getKeyPassword()); httpsConnector.setKeystoreType(SSLConfig.getStoreType()); httpsConnector.setKeystore(SSLConfig.getKeystoreLocation()); adminServer.addConnector(httpsConnector); sslEnabled = true; } } catch (Exception e) { Log.error(e.getMessage(), e); } // Make sure that at least one connector was registered. if (adminServer.getConnectors() == null || adminServer.getConnectors().length == 0) { adminServer = null; // Log warning. log(LocaleUtils.getLocalizedString("admin.console.warning")); return; } HandlerCollection collection = new HandlerCollection(); adminServer.setHandler(collection); collection.setHandlers(new Handler[] {contexts, new DefaultHandler()}); try { adminServer.start(); } catch (Exception e) { Log.error("Could not start admin conosle server", e); } // Log the ports that the admin server is listening on. logAdminConsolePorts(); }
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); } }
@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); }