@BeforeMethod public void start() throws Exception { JOptionPane.showConfirmDialog(null, "Start"); Handler handler = new AbstractHandler() { private int[] ints = new int[1024 * 1024]; public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int[] cache = ints; ints = null; ints = cache; cache = null; response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hello</h1>"); ((Request) request).setHandled(true); } }; server = new Server(8080); server.setHandler(handler); server.setStopAtShutdown(true); server.start(); }
public String decodeUrl(final String path) throws Exception { ServerSocket serverSocket = new ServerSocket(0); final int port = serverSocket.getLocalPort(); serverSocket.close(); Server server = new Server(port); server.setStopAtShutdown(true); ServletContextHandler ctx = new ServletContextHandler(server, "/", true, false); ctx.addServlet(new ServletHolder(new DecodeServlet()), "/*"); server.start(); ThreadUtils.sleep(500); new Thread() { @Override public void run() { try { ThreadUtils.sleep(500); InputStream is = new URL("http://localhost:" + port + path).openStream(); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); synchronized (this) { wait(); } return this.decodedPath; }
@BeforeClass public static void setup() throws Exception { server.setStopAtShutdown(true); ResourceHandler handler = new ResourceHandler(); handler.setBaseResource(Resource.newClassPathResource("/ontologies/import/")); server.setHandler(handler); server.start(); }
protected Server buildServer(LifecycleEnvironment lifecycle, ThreadPool threadPool) { final Server server = new Server(threadPool); server.addLifeCycleListener(buildSetUIDListener()); lifecycle.attach(server); final ErrorHandler errorHandler = new ErrorHandler(); errorHandler.setServer(server); errorHandler.setShowStacks(false); server.addBean(errorHandler); server.setStopAtShutdown(true); server.setStopTimeout(shutdownGracePeriod.toMilliseconds()); return server; }
/** * Main entry point to application. Sets up the resources and launches the Jetty server. * * @param args The command line arguments. * @throws Exception When there is an issue launching the application. */ public static void main(String[] args) { // set up command line options Options options = new Options(); options.addOption("p", "port", true, "Port to bind to [default: 8080]"); // parse command line parameters CommandLine commandLine = null; try { commandLine = new PosixParser().parse(options, args); } catch (ParseException e) { LOG.error("Could not parse command line args: ", e); printUsageAndExit(options, -1); } int port = 8080; // user provided value precedes config value if (commandLine != null && commandLine.hasOption("port")) { String val = commandLine.getOptionValue("port"); // get port to bind to port = Integer.parseInt(val); LOG.debug("Port set to: " + val); } LOG.info("DNS Web server setup."); // create server and configure basic settings Server server = new Server(); server.setStopAtShutdown(true); // set up connector Connector connector = new SelectChannelConnector(); connector.setPort(port); // connector.setHost("127.0.0.1"); server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new DnsServ()), "/*"); // context.addServlet(new ServletHolder(new // HelloServlet("TYPE1 Request")), "/TYPE1/*"); // start the server try { server.start(); server.join(); } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } }
private boolean init(Handler handler, int port) { try { Server server = new Server(); SocketConnector connector = new SocketConnector(); connector.setPort(port); connector.setHost("127.0.0.1"); server.addConnector(connector); server.setHandler(handler); server.setStopAtShutdown(true); server.start(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
private Server createNewServer(String[] args) { int port = args.length > 0 ? Integer.parseInt(args[0]) : DEFAULT_PORT; Enviroment env = args.length > 0 ? Enviroment.valueOf(args[1]) : Enviroment.desa; WebAppContext webHandler = this.buildWebAppContext(args, env); HandlerList handlers = new HandlerList(); handlers.addHandler(webHandler); Server server = new Server(port); server.setHandler(handlers); server.setStopAtShutdown(true); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); return server; }
/** 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录. */ public static Server createServerInSource(int port, String contextPath) { Server server = new Server(); // 设置在JVM退出时关闭Jetty的钩子。 server.setStopAtShutdown(true); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); // 解决Windows下重复启动Jetty居然不报告端口冲突的问题. connector.setReuseAddress(false); server.setConnectors(new Connector[] {connector}); WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, contextPath); // 修改webdefault.xml,解决Windows下Jetty Lock住静态文件的问题. webContext.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH); server.setHandler(webContext); return server; }
@Override protected void setUp() throws Exception { try { WebAppContext fakeSteam = new WebAppContext(); fakeSteam.setWar("src/test/webapp"); fakeSteam.setContextPath("/"); statsServlet = new StatsServlet(); ServletHolder statsHolder = new ServletHolder(statsServlet); statsHolder.setInitOrder(1); fakeSteam.addServlet(statsHolder, "/*"); server = new Server(port); server.setStopAtShutdown(false); server.setHandler(fakeSteam); server.start(); Steamer.steamcommunity = "localhost:" + port; } catch (Exception e) { server = null; fail("Failing while stating server"); } super.setUp(); }
private static Server createServer(String contextPath, int port) { // use Eclipse JDT compiler System.setProperty("org.apache.jasper.compiler.disablejsr199", "true"); Server server = new Server(port); server.setStopAtShutdown(true); ProtectionDomain protectionDomain = Main.class.getProtectionDomain(); URL location = protectionDomain.getCodeSource().getLocation(); String warFile = location.toExternalForm(); WebAppContext context = new WebAppContext(warFile, contextPath); context.setServer(server); // 设置work dir,war包将解压到该目录,jsp编译后的文件也将放入其中。 String currentDir = new File(location.getPath()).getParent(); File workDir = new File(currentDir, "work"); context.setTempDirectory(workDir); server.setHandler(context); return server; }
public void start() throws Exception { server = new Server(serverPort); File keystore = TestFileUtil.createUniqueTempFile("keystore"); File truststore = TestFileUtil.createUniqueTempFile("truststore"); File agentKeystore = TestFileUtil.createUniqueTempFile("agentstore"); createX509Certificate(keystore, truststore, agentKeystore); server.addConnector(sslConnector(keystore, truststore, sslPort)); WebAppContext wac = new WebAppContext("testdata/goserverstub", "/go"); wac.setConfigurationClasses( new String[] { WebInfConfiguration.class.getCanonicalName(), WebXmlConfiguration.class.getCanonicalName(), JettyWebXmlConfiguration.class.getCanonicalName() }); addFakeArtifactiPublisherServlet(wac); addFakeAgentCertificateServlet(wac); server.setHandler(wac); server.setStopAtShutdown(true); server.start(); }
public static void main(String[] args) throws Exception { // When run from app-runner, you must use the port set in the environment variable web.port int port = Integer.parseInt(firstNonNull(System.getenv("web.port"), "8080")); InetSocketAddress addr = new InetSocketAddress("localhost", port); Server jettyServer = new Server(addr); jettyServer.setStopAtShutdown(true); HandlerList handlers = new HandlerList(); // TODO: set your own handlers handlers.addHandler(resourceHandler()); // you must serve everything from a directory named after your app ContextHandler ch = new ContextHandler(); ch.setContextPath("/maven"); ch.setHandler(handlers); jettyServer.setHandler(ch); jettyServer.start(); log.info("Started app at http://localhost:" + port + ch.getContextPath()); jettyServer.join(); }
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; }
/** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { CommandLineParser parser = new PosixParser(); String warcDir = null; String workDir = null; String host = "localhost"; Options options = new Options(); options.addOption("h", "help", false, "Show this help message."); options.addOption( "i", "index-folder", true, "Specify a custom directory for caching the web archiving index files. Indexes are usually re-built every time you start WaybackPlayer, which might be cumbersome for large indexes. Use this option to specify a folder in which to cache the indexes."); options.addOption( "s", "server-name", true, "Specify a server name to use, defaults to 'localhost'"); try { CommandLine line = parser.parse(options, args); String cli_args[] = line.getArgs(); // Check there is an argument for the warcs folder: if (!(cli_args.length > 0)) { printUsage(options); return; } warcDir = cli_args[0]; // Show help if required: if (line.hasOption("h")) { printUsage(options); return; } // Allow index folder to be overridden (and thus cached): if (line.hasOption("i")) { workDir = line.getOptionValue("i"); } // Allow the host to be overridden: if (line.hasOption("s")) { host = line.getOptionValue("s"); } } catch (ParseException e1) { e1.printStackTrace(); return; } // Avoid requiring the JDK for Jetty JSP compilation. // See http://www.eclipse.org/jetty/documentation/current/configuring-jsp.html System.setProperty("org.apache.jasper.compiler.disablejsr199", "true"); // An embedded server: Server server = new Server(); // Default connector for playback: SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(18080); connector.setHost(host); // Connector for Proxy mode: SelectChannelConnector connector2 = new SelectChannelConnector(); connector2.setPort(18090); connector2.setHost(host); // Attach the two connectors: server.setConnectors(new Connector[] {connector, connector2}); // Set a property so Wayback Spring can find the WARCs etc. System.setProperty("wayback.warc.dir", warcDir); // Set a propery so the host and ports are known: System.setProperty("wayback.host", host); System.setProperty("wayback.port", "" + 18080); System.setProperty("wayback.proxy.port", "" + 18090); // TODO Option to wipe it if it's there and looks like ours? File waywork = null; if (workDir == null) { waywork = File.createTempFile("wayback-play", ""); waywork.delete(); waywork.mkdir(); System.setProperty("wayback.work.dir", waywork.getAbsolutePath()); waywork.deleteOnExit(); } else { waywork = new File(workDir); System.setProperty("wayback.work.dir", workDir); } System.err.println("Indexes held in: " + System.getProperty("wayback.work.dir")); // Prior to start up, generate CDX files and path-index.txt file and put them in // wayback.work.dir: File wdf = new File(warcDir); List<String> paths = new ArrayList<String>(); for (File wf : wdf.listFiles()) { paths.add(wf.getName() + "\t" + wf.getAbsolutePath()); System.out.println("LINE: " + wf.getAbsolutePath()); // CDX generation: File cdxFile = new File(waywork, wf.getName() + ".cdx"); if (!cdxFile.exists()) { System.out.println("Generating " + cdxFile.getPath() + " from " + wf.getPath() + "..."); IndexWorker.main(new String[] {wf.getAbsolutePath(), cdxFile.getAbsolutePath()}); } else { System.out.println( "The CDX " + cdxFile.getPath() + " for " + wf.getPath() + " already exists."); } } // For path-index.txt: Collections.sort(paths); PrintWriter writer = new PrintWriter(new File(waywork, "path-index.txt"), "UTF-8"); for (String path : paths) { writer.println(path); } writer.close(); // Set up the Wayback web app: WebAppContext wac = new WebAppContext(); wac.setContextPath("/"); // this is path to .war OR TO expanded, existing webapp; WILL FIND web.xml and parse it // wac.setWar("/Users/andy/Documents/workspace/waybacks/wayback-play/target/wayback-play"); URL resourceUrl = ClassLoader.getSystemClassLoader().getResource("lib/warc-explorer-player.war"); // Copy to tmp space: File tmpWar = File.createTempFile("wayback-player", ".war"); tmpWar.deleteOnExit(); IOUtils.copy(resourceUrl.openStream(), new FileOutputStream(tmpWar)); // Fire it up: wac.setWar(tmpWar.getAbsolutePath()); server.setHandler(wac); server.setStopAtShutdown(true); // Launch the server: try { server.start(); server.join(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // connector.close(); try { server.stop(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if (waywork != null) { if (waywork.exists()) { waywork.delete(); } } } System.err.println("Bye."); }
JawrIntegrationServer() { Properties prop = new Properties(); InputStream inStream = getClass().getClassLoader().getResourceAsStream(PROP_FILE_NAME); if (inStream != null) { try { prop.load(inStream); } catch (IOException e) { throw new RuntimeException(e); } IOUtils.closeQuietly(inStream); } serverPort = Integer.parseInt(prop.getProperty(PORT_PROPERTY_NAME, DEFAULT_PORT)); server = new Server(serverPort); // Setup JMX MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); server.addEventListener(mbContainer); server.addBean(mbContainer); try { String host = "localhost"; int jmxPort = 1099; String urlPath = String.format("/jndi/rmi://%s:%s/jmxrmi", host, jmxPort); JMXServiceURL serviceURL = new JMXServiceURL("rmi", host, jmxPort, urlPath); ConnectorServer connectorServer = new ConnectorServer(serviceURL, "org.eclipse.jetty.jmx:name=rmiconnectorserver"); connectorServer.start(); } catch (Exception e) { throw new RuntimeException(e); } server.setStopAtShutdown(true); String webappName = prop.getProperty(WEBAPP_PROPERTY_NAME, DEFAULT_WEBAPP_NAME); try { webAppRootDir = new File(TARGET_ROOT_DIR + webappName).getCanonicalFile().getAbsolutePath(); } catch (IOException e) { throw new RuntimeException(e); } boolean useEmptyContextPath = Boolean.parseBoolean( prop.getProperty( USE_DEFAULT_CONTEXT_PATH_PROPERTY_NAME, DONT_USE_DEFAULT_CONTEXT_PATH)); String webAppCtx = ""; if (!useEmptyContextPath) { webAppCtx = "/" + webappName; } jettyWebAppContext = new WebAppContext(webAppRootDir, webAppCtx); jettyWebAppContext.setConfigurationClasses( new String[] { "org.eclipse.jetty.webapp.WebInfConfiguration", "org.eclipse.jetty.webapp.WebXmlConfiguration", "org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration" }); ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection(); contextHandlerCollection.setHandlers(new Handler[] {jettyWebAppContext}); server.setHandler(contextHandlerCollection); }
static { List<String> allowedUserHostsList = Nxt.getStringListProperty("nxt.allowedUserHosts"); if (!allowedUserHostsList.contains("*")) { allowedUserHosts = Collections.unmodifiableSet(new HashSet<>(allowedUserHostsList)); } else { allowedUserHosts = null; } boolean enableUIServer = Nxt.getBooleanProperty("nxt.enableUIServer"); if (enableUIServer) { final int port = Constants.isTestnet ? TESTNET_UI_PORT : Nxt.getIntProperty("nxt.uiServerPort"); final String host = Nxt.getStringProperty("nxt.uiServerHost"); userServer = new Server(); ServerConnector connector; boolean enableSSL = Nxt.getBooleanProperty("nxt.uiSSL"); if (enableSSL) { Logger.logMessage("Using SSL (https) for the user interface server"); HttpConfiguration https_config = new HttpConfiguration(); https_config.setSecureScheme("https"); https_config.setSecurePort(port); https_config.addCustomizer(new SecureRequestCustomizer()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(Nxt.getStringProperty("nxt.keyStorePath")); sslContextFactory.setKeyStorePassword( Nxt.getStringProperty("nxt.keyStorePassword", null, true)); 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"); sslContextFactory.setExcludeProtocols("SSLv3"); connector = new ServerConnector( userServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config)); } else { connector = new ServerConnector(userServer); } connector.setPort(port); connector.setHost(host); connector.setIdleTimeout(Nxt.getIntProperty("nxt.uiServerIdleTimeout")); connector.setReuseAddress(true); userServer.addConnector(connector); HandlerList userHandlers = new HandlerList(); ResourceHandler userFileHandler = new ResourceHandler(); userFileHandler.setDirectoriesListed(false); userFileHandler.setWelcomeFiles(new String[] {"index.html"}); userFileHandler.setResourceBase(Nxt.getStringProperty("nxt.uiResourceBase")); userHandlers.addHandler(userFileHandler); String javadocResourceBase = Nxt.getStringProperty("nxt.javadocResourceBase"); if (javadocResourceBase != null) { ContextHandler contextHandler = new ContextHandler("/doc"); ResourceHandler docFileHandler = new ResourceHandler(); docFileHandler.setDirectoriesListed(false); docFileHandler.setWelcomeFiles(new String[] {"index.html"}); docFileHandler.setResourceBase(javadocResourceBase); contextHandler.setHandler(docFileHandler); userHandlers.addHandler(contextHandler); } ServletHandler userHandler = new ServletHandler(); ServletHolder userHolder = userHandler.addServletWithMapping(UserServlet.class, "/nxt"); userHolder.setAsyncSupported(true); if (Nxt.getBooleanProperty("nxt.uiServerCORS")) { FilterHolder filterHolder = userHandler.addFilterWithMapping(CrossOriginFilter.class, "/*", FilterMapping.DEFAULT); filterHolder.setInitParameter("allowedHeaders", "*"); filterHolder.setAsyncSupported(true); } userHandlers.addHandler(userHandler); userHandlers.addHandler(new DefaultHandler()); userServer.setHandler(userHandlers); userServer.setStopAtShutdown(true); ThreadPool.runBeforeStart( () -> { try { userServer.start(); Logger.logMessage("Started user interface server at " + host + ":" + port); } catch (Exception e) { Logger.logErrorMessage("Failed to start user interface server", e); throw new RuntimeException(e.toString(), e); } }, true); } else { userServer = null; Logger.logMessage("User interface server not enabled"); } }
public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser("p:f:c:r:H:s:t:h"); OptionSet options = null; try { options = parser.parse(args); } catch (OptionException ex) { System.err.println(ex.getMessage()); System.exit(1); } if (options.has("h")) { printHelp(System.out); System.exit(0); } final int port; if (options.has("p")) { String portStr = options.valueOf("p").toString(); try { port = Integer.parseInt(portStr); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Invalid port number: " + portStr, ex); } } else { port = -1; System.err.println("Mandatory parameter port not given."); System.exit(1); } AnyUrlServlet servlet = new AnyUrlServlet(); if (options.has("f")) { String fileStr = options.valueOf("f").toString(); servlet.setFile(new File(fileStr)); } if (options.has("c")) { servlet.setContentType(options.valueOf("c").toString()); } if (options.has("r")) { servlet.setCharset(options.valueOf("r").toString()); } if (options.has("H")) { MultiValueMap headers = new MultiValueMapLinkedHashSet(); for (Object t : options.valuesOf("H")) { final String headerLine = t.toString().trim(); final int sepIdx = headerLine.indexOf(':'); if ((sepIdx > 0) && (sepIdx < headerLine.length())) { final String header = headerLine.substring(0, sepIdx).trim(); final String value = headerLine.substring(sepIdx + 1).trim(); // System.out.printf("\nHeader: Value => %s:%s\n", header, value); headers.put(header, value); } } servlet.setHeaders(headers); } if (options.has("s")) { try { int statusCode = Integer.parseInt(options.valueOf("s").toString()); servlet.setStatusCode(statusCode); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Param -s must be a valid status code."); } } if (options.has("t")) { try { long throttleMillis = Long.parseLong(options.valueOf("t").toString()); if (throttleMillis > 1) { servlet.setThrottleMillis(throttleMillis); } else { throw new NumberFormatException(); } } catch (NumberFormatException ex) { throw new IllegalArgumentException("Param -t must be a valid number."); } } Server server = new Server(port); server.setStopAtShutdown(true); // Attach the servlet: ServletContextHandler ctx = new ServletContextHandler(); ctx.setContextPath("/"); server.setHandler(ctx); ctx.addServlet(new ServletHolder(servlet), "/*"); server.start(); }
public static void main(String[] args) throws Exception { // load main configuration String configLoc = System.getProperty(CONFIG_LOCATION_SYS_VAR, CONFIG_LOCATION_DEFAULT); System.setProperty(CONFIG_LOCATION_SYS_VAR, configLoc); Properties configProps = new Properties(); try { configProps.load(new FileInputStream(ResourceUtils.getFile(configLoc))); logger.info("Successfully loaded main configuration."); } catch (Exception ex) { logger.error("Fail to start in early part", ex); throw ex; } Config config = new Config(configProps); // load log4j configuration // @todo review the effect and final configuration when -Dlog4j.properties is specified with // command line String log4jConfigLoc = config.getValue(ItemMeta.BOOTSTRAP_LOG4J_CONFIG_LOCATION); if (log4jConfigLoc != null) { Properties log4jConfig = new Properties(); try { log4jConfig.load(new FileInputStream(ResourceUtils.getFile(log4jConfigLoc))); org.apache.log4j.LogManager.resetConfiguration(); org.apache.log4j.PropertyConfigurator.configure(log4jConfig); logger.info("Successfully loaded log4j configuration at {}", log4jConfigLoc); } catch (Exception ex) { logger.error("Faile to load specified log4j configuration", ex); throw ex; } } ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS); sch.setContextPath(config.getValue(ItemMeta.ROOT_SERVLET_CONTEXT_PATH)); sch.getSessionHandler() .getSessionManager() .setSessionCookie(config.getValue(ItemMeta.ROOT_SERVLET_SESSION_ID)); ServletHolder dsh = sch.addServlet(DefaultServlet.class, "/"); dsh.setInitOrder(1); ServletHolder jsh = new ServletHolder(JerseySpringServlet.class); jsh.setInitParameter( JerseySpringServlet.INIT_PARM_SPRING_CONFIG_LOCATION, config.getValue(ItemMeta.BOOTSTRAP_SPRING_CONFIG_LOCATION)); // Refer https://jersey.java.net/apidocs/1.18/jersey/index.html?constant-values.html jsh.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true"); jsh.setInitParameter( ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, "com.sun.jersey.api.container.filter.LoggingFilter"); jsh.setInitParameter( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, "com.sun.jersey.api.container.filter.LoggingFilter"); jsh.setInitParameter(ResourceConfig.FEATURE_TRACE, "true"); // jsh.setInitParameter(JSONMarshaller.FORMATTED, "true"); // jsh.setInitParameter(FeaturesAndProperties.FEATURE_FORMATTED, "true"); // jsh.setInitParameter(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true"); sch.addServlet(jsh, config.getValue(ItemMeta.JERSEY_SERVLET_URL_PATTEN)); jsh.setInitOrder(config.getIntValue(ItemMeta.JERSEY_SERVLET_INIT_ORDER)); // For more, refer // http://download.eclipse.org/jetty/stable-7/apidocs/index.html?org/eclipse/jetty/servlets/CrossOriginFilter.html FilterHolder fh = new FilterHolder(CrossOriginFilter.class); fh.setName("crossOriginFilter"); fh.setInitParameter( CrossOriginFilter.ALLOWED_ORIGINS_PARAM, config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_ORIGINS)); fh.setInitParameter( CrossOriginFilter.ALLOWED_METHODS_PARAM, config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_METHODS)); fh.setInitParameter( CrossOriginFilter.ALLOWED_HEADERS_PARAM, config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_HEADERS)); sch.addFilter(fh, "/*", FilterMapping.DEFAULT); Server jetty = new Server(); HandlerList hl = new HandlerList(); hl.addHandler(sch); jetty.setHandler(hl); jetty.setThreadPool( new QueuedThreadPool(config.getIntValue(ItemMeta.WEB_SERVER_THREAD_POOL_SIZE))); SelectChannelConnector conn = new SelectChannelConnector(); conn.setPort(config.getIntValue(ItemMeta.WEB_SERVER_PORT)); conn.setMaxIdleTime(config.getIntValue(ItemMeta.WEB_SERVER_MAX_IDLE_TIME)); MBeanContainer mbc = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); mbc.setDomain(config.getValue(ItemMeta.JMX_DOMAIN) + ".jetty"); jetty.getContainer().addEventListener(mbc); jetty.addBean(mbc); jetty.addConnector(conn); jetty.setStopAtShutdown(true); try { jetty.start(); logger.info("Jetty started at port {} on {}", conn.getPort(), "127.0.0.1"); } catch (Exception ex) { logger.error("Fail to start Jetty.", ex); System.exit(-1); } }
/** * 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); } }
/** * Loads jetty configuration from the given URL. * * @param cfgUrl URL to load configuration from. * @throws GridException if load failed. */ private void loadJettyConfiguration(@Nullable URL cfgUrl) throws GridException { if (cfgUrl == null) { HttpConfiguration httpCfg = new HttpConfiguration(); httpCfg.setSecureScheme("https"); httpCfg.setSecurePort(8443); httpCfg.setSendServerVersion(true); httpCfg.setSendDateHeader(true); String srvPortStr = System.getProperty(GG_JETTY_PORT, "8080"); int srvPort; try { srvPort = Integer.valueOf(srvPortStr); } catch (NumberFormatException ignore) { throw new GridException( "Failed to start Jetty server because GRIDGAIN_JETTY_PORT system property " + "cannot be cast to integer: " + srvPortStr); } httpSrv = new Server(new QueuedThreadPool(20, 200)); ServerConnector srvConn = new ServerConnector(httpSrv, new HttpConnectionFactory(httpCfg)); srvConn.setHost(System.getProperty(GG_JETTY_HOST, "localhost")); srvConn.setPort(srvPort); srvConn.setIdleTimeout(30000L); srvConn.setReuseAddress(true); httpSrv.addConnector(srvConn); httpSrv.setStopAtShutdown(false); } else { XmlConfiguration cfg; try { cfg = new XmlConfiguration(cfgUrl); } catch (FileNotFoundException e) { throw new GridSpiException("Failed to find configuration file: " + cfgUrl, e); } catch (SAXException e) { throw new GridSpiException("Failed to parse configuration file: " + cfgUrl, e); } catch (IOException e) { throw new GridSpiException("Failed to load configuration file: " + cfgUrl, e); } catch (Exception e) { throw new GridSpiException( "Failed to start HTTP server with configuration file: " + cfgUrl, e); } try { httpSrv = (Server) cfg.configure(); } catch (Exception e) { throw new GridException("Failed to start Jetty HTTP server.", e); } } assert httpSrv != null; httpSrv.setHandler(jettyHnd); override(getJettyConnector()); }
@Test public void checkBasicAuthAccess() throws Throwable { final Server server = new Server(); final SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(/* any */ 0); connector.setReuseAddress(false); connector.setSoLingerTime(0); server.addConnector(connector); HashLoginService loginService = new HashLoginService(); loginService.putUser("username", new Password("userpass"), new String[] {"role1", "role2"}); final CountDownLatch latch = new CountDownLatch(1); WebAppContext wac = new WebAppContext(); wac.getSecurityHandler().setLoginService(loginService); wac.setContextPath("/"); connector.addLifeCycleListener( new ListenerAdapter() { public void lifeCycleStarted(LifeCycle lc) { System.out.println("Started on port: " + connector.getLocalPort()); latch.countDown(); } public void lifeCycleFailure(LifeCycle lc, Throwable t) { System.out.println("Failure: " + t); latch.countDown(); } }); wac.setParentLoaderPriority(true); URL resource = getClass().getResource("/auth/basic/kaczynski.xml"); assertThat(resource.toURI().getScheme()).isEqualTo("file"); File webapp = new File(resource.toURI()); webapp = webapp.getParentFile(); // /auth/basic webapp = webapp.getParentFile(); // /auth wac.setWar(webapp.getAbsolutePath()); wac.setClassLoader(Thread.currentThread().getContextClassLoader()); server.setHandler(wac); server.setStopAtShutdown(true); try { server.start(); latch.await(); System.setProperty(HttpAuthHub.USERNAME_PROPERTY, "username"); System.setProperty(HttpAuthHub.PASSWORD_PROPERTY, "userpass"); Controller c = ControllerFactory.createSimple(); try { Map<String, Object> attrs = new HashMap<String, Object>(); XmlDocumentSourceDescriptor.attributeBuilder(attrs) .xml( new URLResourceWithParams( new URL( "http://localhost:" + connector.getLocalPort() + "/basic/kaczynski.xml"))); ProcessingResult r = c.process(attrs, XmlDocumentSource.class); assertThat(r.getDocuments()).hasSize(50); } finally { c.dispose(); } } finally { server.stop(); } }
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(); }