org.eclipse.jetty.server.handler.HandlerList#addHandler ( )源码实例Demo

下面列出了org.eclipse.jetty.server.handler.HandlerList#addHandler ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: selenium   文件: JettyAppServer.java
protected ServletContextHandler addResourceHandler(String contextPath, Path resourceBase) {
  ServletContextHandler context = new ServletContextHandler();

  ResourceHandler staticResource = new ResourceHandler();
  staticResource.setDirectoriesListed(true);
  staticResource.setWelcomeFiles(new String[] { "index.html" });
  staticResource.setResourceBase(resourceBase.toAbsolutePath().toString());
  MimeTypes mimeTypes = new MimeTypes();
  mimeTypes.addMimeMapping("appcache", "text/cache-manifest");
  staticResource.setMimeTypes(mimeTypes);

  context.setContextPath(contextPath);
  context.setAliasChecks(Arrays.asList(new ApproveAliases(), new AllowSymLinkAliasChecker()));

  HandlerList allHandlers = new HandlerList();
  allHandlers.addHandler(staticResource);
  allHandlers.addHandler(context.getHandler());
  context.setHandler(allHandlers);

  handlers.addHandler(context);

  return context;
}
 
源代码2 项目: chaos-http-proxy   文件: ChaosHttpProxy.java
public ChaosHttpProxy(URI endpoint, ChaosConfig config)
        throws Exception {
    setChaosConfig(config);

    Supplier<Failure> supplier = new RandomFailureSupplier(
            config.getFailures());

    requireNonNull(endpoint);

    client = new HttpClient();

    server = new Server();
    HttpConnectionFactory httpConnectionFactory =
            new HttpConnectionFactory();
    // TODO: SSL
    ServerConnector connector = new ServerConnector(server,
            httpConnectionFactory);
    connector.setHost(endpoint.getHost());
    connector.setPort(endpoint.getPort());
    server.addConnector(connector);
    this.handler = new ChaosHttpProxyHandler(client, supplier);
    HandlerList handlers = new HandlerList();
    handlers.addHandler(new ChaosApiHandler(this, handler));
    handlers.addHandler(handler);
    server.setHandler(handlers);
}
 
源代码3 项目: cxf   文件: StatsServer.java
public static void main(final String[] args) throws Exception {
    final Server server = new Server(8686);

    final ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/static");
    staticContext.addServlet(staticHolder, "/*");
    staticContext.setResourceBase(StatsServer.class.getResource("/web-ui").toURI().toString());

     // Register and map the dispatcher servlet
    final CXFCdiServlet cxfServlet = new CXFCdiServlet();
    final ServletHolder cxfServletHolder = new ServletHolder(cxfServlet);
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new Listener());
    context.addEventListener(new BeanManagerResourceBindingListener());
    context.addServlet(cxfServletHolder, "/rest/*");

    HandlerList handlers = new HandlerList();
    handlers.addHandler(staticContext);
    handlers.addHandler(context);

    server.setHandler(handlers);
    server.start();
    server.join();
}
 
源代码4 项目: jslt   文件: PlaygroundServer.java
public static void main(String[] argv) throws Exception {
  Server server = new Server(Integer.parseInt(argv[0]));
  HandlerList handlers = new HandlerList();
  handlers.addHandler(new JsltHandler());
  server.setHandler(handlers);

  server.start();
  server.join();
}
 
源代码5 项目: selenium   文件: Main.java
public static void main(String[] args) throws Exception {
  Flags flags = new Flags();
  JCommander.newBuilder().addObject(flags).build().parse(args);

  Server server = new Server();
  ServerConnector connector = new ServerConnector(server);
  connector.setPort(flags.port);
  server.setConnectors(new Connector[] {connector });

  HandlerList handlers = new HandlerList();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/tests");
  ResourceHandler testHandler = new ResourceHandler();
  testHandler.setBaseResource(Resource.newClassPathResource("/tests"));
  testHandler.setDirectoriesListed(true);
  context.setHandler(testHandler);
  handlers.addHandler(context);

  ContextHandler coreContext = new ContextHandler();
  coreContext.setContextPath("/core");
  ResourceHandler coreHandler = new ResourceHandler();
  coreHandler.setBaseResource(Resource.newClassPathResource("/core"));
  coreContext.setHandler(coreHandler);
  handlers.addHandler(coreContext);

  ServletContextHandler driverContext = new ServletContextHandler();
  driverContext.setContextPath("/");
  driverContext.addServlet(WebDriverServlet.class, "/wd/hub/*");
  handlers.addHandler(driverContext);

  server.setHandler(handlers);
  server.start();
}
 
/**
 * Start server.
 *
 * @param packages restful implementation class package
 * @param resourcePath resource path
 * @param servletPath servlet path
 * @throws Exception exception when startup
 */
public void start(final String packages, final Optional<String> resourcePath, final Optional<String> servletPath) throws Exception {
    log.info("Elastic Job: Start RESTful server");
    HandlerList handlers = new HandlerList();
    if (resourcePath.isPresent()) {
        servletContextHandler.setBaseResource(Resource.newClassPathResource(resourcePath.get()));
        servletContextHandler.addServlet(new ServletHolder(DefaultServlet.class), "/*");
    }
    String servletPathStr = (servletPath.isPresent() ? servletPath.get() : "") + "/*";
    servletContextHandler.addServlet(getServletHolder(packages), servletPathStr);
    handlers.addHandler(servletContextHandler);
    server.setHandler(handlers);
    server.start();
}
 
@BeforeClass
public static void setUp() throws Exception {
    // uncomment this to debug locally in IDE
    //setConfigSystemPropertiesForDebugging();

    server = new Server();
    connector = new ServerConnector(server);
    connector.setPort(PORT);
    server.addConnector(connector);

    HandlerList handlers = new HandlerList();
    ServletContextHandler context = new ServletContextHandler();
    ServletHolder defaultServ = new ServletHolder("default",
                                                  DefaultServlet.class);
    defaultServ.setInitParameter("resourceBase",
                                 System.getProperty("builddir") + "/" +
                                         System.getProperty("artifactId") + "-" +
                                         System.getProperty("version") + "/");
    defaultServ.setInitParameter("dirAllowed",
                                 "true");
    context.addServlet(defaultServ,
                       "/");
    handlers.addHandler(context);
    server.setHandler(handlers);

    server.start();
}
 
源代码8 项目: app-runner   文件: App.java
public static void main(String[] args) throws Exception {
    Map<String, String> settings = System.getenv();

    // When run from app-runner, you must use the port set in the environment variable APP_PORT
    int port = Integer.parseInt(settings.getOrDefault("APP_PORT", "8081"));
    // All URLs must be prefixed with the app name, which is got via the APP_NAME env var.
    String appName = settings.getOrDefault("APP_NAME", "my-app");
    String env = settings.getOrDefault("APP_ENV", "local"); // "prod" or "local"
    boolean isLocal = "local".equals(env);
    log.info("Starting " + appName + " in " + env + " on port " + port);

    Server jettyServer = new Server(new InetSocketAddress("localhost", port));
    jettyServer.setStopAtShutdown(true);

    HandlerList handlers = new HandlerList();
    // TODO: set your own handlers
    handlers.addHandler(resourceHandler(isLocal));

    // you must serve everything from a directory named after your app
    ContextHandler ch = new ContextHandler();
    ch.setContextPath("/" + appName);
    ch.setHandler(handlers);
    jettyServer.setHandler(ch);

    try {
        jettyServer.start();
    } catch (Throwable e) {
        log.error("Error on start", e);
        System.exit(1);
    }

    log.info("Started app at http://localhost:" + port + ch.getContextPath());
    jettyServer.join();
}
 
源代码9 项目: warp10-platform   文件: InfluxDBWarp10Plugin.java
@Override
public void run() {
  Server server = new Server(new QueuedThreadPool(maxThreads, 8, idleTimeout, queue));
  ServerConnector connector = new ServerConnector(server, acceptors, selectors);
  connector.setIdleTimeout(idleTimeout);
  connector.setPort(port);
  connector.setHost(host);
  connector.setName("Continuum Ingress");
  
  server.setConnectors(new Connector[] { connector });

  HandlerList handlers = new HandlerList();
  
  Handler cors = new CORSHandler();
  handlers.addHandler(cors);

  handlers.addHandler(new InfluxDBHandler(url, token));
  
  server.setHandler(handlers);
  
  JettyUtil.setSendServerVersion(server, false);

  try {
    server.start();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
源代码10 项目: baleen   文件: BaleenWebApi.java
private void installSwagger(HandlerList handlers) {
  LOGGER.debug("Adding Swagger documentation");

  final ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setDirectoriesListed(true); //
  resourceHandler.setResourceBase(getClass().getResource("/swagger").toExternalForm());

  ContextHandler swaggerHandler = new ContextHandler("/swagger/*");
  swaggerHandler.setHandler(resourceHandler);
  handlers.addHandler(swaggerHandler);
}
 
源代码11 项目: scheduling   文件: JettyStarter.java
private void addWarFile(HandlerList handlerList, File file, String[] virtualHost) {
    String contextPath = "/" + FilenameUtils.getBaseName(file.getName());
    WebAppContext webApp = createWebAppContext(contextPath, virtualHost);
    webApp.setWar(file.getAbsolutePath());
    handlerList.addHandler(webApp);
    logger.debug("Deploying " + contextPath + " using war file " + file);
}
 
源代码12 项目: scheduling   文件: JettyStarter.java
private void addExplodedWebApp(HandlerList handlerList, File file, String[] virtualHost) {
    String contextPath = "/" + file.getName();
    WebAppContext webApp = createWebAppContext(contextPath, virtualHost);

    // Don't scan classes for annotations. Saves 1 second at startup.
    webApp.setAttribute("org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern", "^$");
    webApp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", "^$");

    webApp.setDescriptor(new File(file, "/WEB-INF/web.xml").getAbsolutePath());
    webApp.setResourceBase(file.getAbsolutePath());
    handlerList.addHandler(webApp);
    logger.debug("Deploying " + contextPath + " using exploded war " + file);
}
 
源代码13 项目: scheduling   文件: JettyStarter.java
private void addStaticFolder(HandlerList handlerList, File file, String[] virtualHost) {
    String contextPath = "/" + file.getName();
    WebAppContext webApp = createWebAppContext(contextPath, virtualHost);
    webApp.setWar(file.getAbsolutePath());
    handlerList.addHandler(webApp);
    logger.debug("Deploying " + contextPath + " using folder " + file);
}
 
源代码14 项目: scheduling   文件: JettyStarter.java
private void addGetStartedApplication(HandlerList handlerList, File file, String[] virtualHost) {
    if (file.exists()) {
        String contextPath = "/";
        WebAppContext webApp = createWebAppContext(contextPath, virtualHost);
        webApp.setWar(file.getAbsolutePath());
        handlerList.addHandler(webApp);
    }
}
 
源代码15 项目: p3-batchrefine   文件: TestSupport.java
private int startTransformServer() throws Exception {
    URL transforms = EngineTest.class.getClassLoader().getResource(
            "transforms");
    if (transforms == null) {
        Assert.fail();
    }

    int port = findFreePort();

    Server fileServer = new Server(port);

    ResourceHandler handler = new ResourceHandler();
    MimeTypes mimeTypes = handler.getMimeTypes();
    mimeTypes.addMimeMapping("json", "application/json; charset=UTF-8");

    handler.setDirectoriesListed(true);
    handler.setBaseResource(JarResource.newResource(transforms));

    HandlerList handlers = new HandlerList();
    handlers.addHandler(handler);
    handlers.addHandler(new DefaultHandler());

    fileServer.setHandler(handlers);
    fileServer.start();

    return port;
}
 
源代码16 项目: graphicsfuzz   文件: FuzzerServer.java
public void start() throws Exception {

    FuzzerServiceImpl fuzzerService = new FuzzerServiceImpl(
        Paths.get(workingDir, processingDir).toString(),
        executorService);

    FuzzerService.Processor processor =
        new FuzzerService.Processor<FuzzerService.Iface>(fuzzerService);

    FuzzerServiceManagerImpl fuzzerServiceManager = new FuzzerServiceManagerImpl(fuzzerService,
          new PublicServerCommandDispatcher());
    FuzzerServiceManager.Processor managerProcessor =
        new FuzzerServiceManager.Processor<FuzzerServiceManager.Iface>(fuzzerServiceManager);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    {
      ServletHolder sh = new ServletHolder();
      sh.setServlet(new TServlet(processor, new TBinaryProtocol.Factory()));
      context.addServlet(sh, "/request");
    }
    {
      ServletHolder serveltHolderJson = new ServletHolder();
      serveltHolderJson.setServlet(new TServlet(processor, new TJSONProtocol.Factory()));
      context.addServlet(serveltHolderJson, "/requestJSON");
    }

    {
      ServletHolder shManager = new ServletHolder();
      shManager.setServlet(new TServlet(managerProcessor, new TBinaryProtocol.Factory()));
      context.addServlet(shManager, "/manageAPI");
    }

    final String staticDir = ToolPaths.getStaticDir();
    context.addServlet(
          new ServletHolder(
                new FileDownloadServlet(
                    (pathInfo, worker) -> Paths.get(staticDir, pathInfo).toFile(), staticDir)),
          "/static/*");

    HandlerList handlerList = new HandlerList();
    handlerList.addHandler(context);

    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setHandler(handlerList);

    Server server = new Server(port);

    server.setHandler(gzipHandler);
    server.start();
    server.join();
  }
 
源代码17 项目: emissary   文件: EmissaryServer.java
/**
 * Creates and starts a server that is bound into the local Namespace using DEFAULT_NAMESPACE_NAME and returned
 *
 * 
 */
public Server startServer() {
    // do what StartJetty and then JettyServer did to start
    try {
        // Resource.setDefaultUseCaches(false);

        // needs to be loaded first into the server as it setups up Emissary stuff
        ContextHandler emissaryHandler = buildEmissaryHandler();
        // TODO: rework this, no need for it be set with a context path but if this
        // is left out, it matches / and nothing works correctly
        emissaryHandler.setContextPath("/idontreallyservecontentnowdoi");
        ContextHandler lbConfigHandler = buildLogbackConfigHandler();
        lbConfigHandler.setContextPath("/lbConfig");
        ContextHandler apiHandler = buildApiHandler();
        apiHandler.setContextPath("/api");
        ContextHandler mvcHandler = buildMVCHandler();
        mvcHandler.setContextPath("/emissary");
        // needs to be loaded last into the server so other contexts can match or fall through
        ContextHandler staticHandler = buildStaticHandler();
        staticHandler.setContextPath("/");

        LoginService loginService = buildLoginService();
        ConstraintSecurityHandler security = buildSecurityHandler();
        security.setLoginService(loginService);

        // secure some of the contexts
        final HandlerList securedHandlers = new HandlerList();
        securedHandlers.addHandler(lbConfigHandler);
        securedHandlers.addHandler(apiHandler);
        securedHandlers.addHandler(mvcHandler);
        securedHandlers.addHandler(staticHandler);
        security.setHandler(securedHandlers);

        final HandlerList handlers = new HandlerList();
        handlers.addHandler(emissaryHandler); // not secured, no endpoints and must be loaded first
        handlers.addHandler(security);

        Server server = configureServer();
        server.setHandler(handlers);
        server.addBean(loginService);
        server.setStopAtShutdown(true);
        server.setStopTimeout(10000l);
        if (this.cmd.shouldDumpJettyBeans()) {
            server.dump(System.out);
        }
        this.server = server;
        bindServer(); // emissary specific

        server.start();
        // server.join(); // don't join so we can shutdown

        String serverLocation = cmd.getScheme() + "://" + cmd.getHost() + ":" + cmd.getPort();

        // write out env.sh file here
        Path envsh = Paths.get(ConfigUtil.getProjectBase() + File.separator + "env.sh");
        if (Files.exists(envsh)) {
            LOG.debug("Removing old {}", envsh.toAbsolutePath());
            Files.delete(envsh);
        }
        String envURI = serverLocation + "/api/env.sh";
        EmissaryResponse er = new EmissaryClient().send(new HttpGet(envURI));
        String envString = er.getContentString();
        Files.createFile(envsh);
        Files.write(envsh, envString.getBytes());
        LOG.info("Wrote {}", envsh.toAbsolutePath());
        LOG.debug(" with \n{}", envString);

        if (cmd.isPause()) {
            pause(true);
        } else {
            unpause(true);
        }

        LOG.info("Started EmissaryServer at {}", serverLocation);
        return server;
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        throw new RuntimeException("Emissary server didn't start", t);
    }
}
 
源代码18 项目: o2oa   文件: CenterServerTools.java
public static Server start(CenterServer centerServer) throws Exception {

		cleanWorkDirectory();

		HandlerList handlers = new HandlerList();

		File war = new File(Config.dir_store(), x_program_center.class.getSimpleName() + ".war");
		File dir = new File(Config.dir_servers_centerServer_work(true), x_program_center.class.getSimpleName());
		if (war.exists()) {
			modified(war, dir);
			QuickStartWebApp webApp = new QuickStartWebApp();
			webApp.setAutoPreconfigure(false);
			webApp.setDisplayName(x_program_center.class.getSimpleName());
			webApp.setContextPath("/" + x_program_center.class.getSimpleName());
			webApp.setResourceBase(dir.getAbsolutePath());
			webApp.setDescriptor(new File(dir, "WEB-INF/web.xml").getAbsolutePath());
			webApp.setExtraClasspath(calculateExtraClassPath(x_program_center.class));
			webApp.getInitParams().put("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
			webApp.getInitParams().put("org.eclipse.jetty.jsp.precompiled", "true");
			webApp.getInitParams().put("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
			/* stat */
			if (centerServer.getStatEnable()) {
				FilterHolder statFilterHolder = new FilterHolder(new WebStatFilter());
				statFilterHolder.setInitParameter("exclusions", centerServer.getStatExclusions());
				webApp.addFilter(statFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
				ServletHolder statServletHolder = new ServletHolder(StatViewServlet.class);
				statServletHolder.setInitParameter("sessionStatEnable", "false");
				webApp.addServlet(statServletHolder, "/druid/*");
			}
			/* stat end */
			handlers.addHandler(webApp);
		} else {
			throw new Exception("centerServer war not exist.");
		}

		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMinThreads(CENTERSERVER_THREAD_POOL_SIZE_MIN);
		threadPool.setMaxThreads(CENTERSERVER_THREAD_POOL_SIZE_MAX);
		Server server = new Server(threadPool);
		server.setAttribute("maxFormContentSize", centerServer.getMaxFormContent() * 1024 * 1024);

		if (centerServer.getSslEnable()) {
			addHttpsConnector(server, centerServer.getPort());
		} else {
			addHttpConnector(server, centerServer.getPort());
		}

		GzipHandler gzipHandler = new GzipHandler();
		gzipHandler.setHandler(handlers);
		server.setHandler(gzipHandler);

		server.setDumpAfterStart(false);
		server.setDumpBeforeStop(false);
		server.setStopAtShutdown(true);

		server.start();
		Thread.sleep(1000);
		System.out.println("****************************************");
		System.out.println("* center server start completed.");
		System.out.println("* port: " + centerServer.getPort() + ".");
		System.out.println("****************************************");
		return server;
	}
 
源代码19 项目: dexter   文件: Main.java
private void start() {
	// Start a Jetty server with some sensible(?) defaults
	try {
		Server srv = new Server();
		srv.setStopAtShutdown(true);

		// Allow 5 seconds to complete.
		// Adjust this to fit with your own webapp needs.
		// Remove this if you wish to shut down immediately (i.e. kill <pid>
		// or Ctrl+C).
		srv.setGracefulShutdown(5000);

		// Increase thread pool
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMaxThreads(100);
		srv.setThreadPool(threadPool);

		// Ensure using the non-blocking connector (NIO)
		Connector connector = new SelectChannelConnector();
		connector.setPort(port);
		connector.setMaxIdleTime(30000);
		srv.setConnectors(new Connector[] { connector });

		// Get the war-file
		ProtectionDomain protectionDomain = Main.class
				.getProtectionDomain();
		String warFile = protectionDomain.getCodeSource().getLocation()
				.toExternalForm();
		String currentDir = new File(protectionDomain.getCodeSource()
				.getLocation().getPath()).getParent();

		// Handle signout/signin in BigIP-cluster

		// Add the warFile (this jar)
		WebAppContext context = new WebAppContext(warFile, contextPath);
		context.setServer(srv);
		resetTempDirectory(context, currentDir);

		// Add the handlers
		HandlerList handlers = new HandlerList();
		handlers.addHandler(context);
		handlers.addHandler(new ShutdownHandler(srv, context, secret));
		handlers.addHandler(new BigIPNodeHandler(secret));
		srv.setHandler(handlers);

		srv.start();
		srv.join();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
源代码20 项目: CardFantasy   文件: CardFantasyJettyServer.java
public static void main(String[] args) throws Exception {
    int port = 7878;
    if (args.length > 1) {
        if ("-port".equalsIgnoreCase(args[0])) {
            try {
                port = Integer.parseInt(args[1]);
            } catch (Exception e) {
                throw new IllegalArgumentException("Invalid port number " + args[1]);
            }
        }
    }
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(128);
    threadPool.setMinThreads(32);
    Server server = new Server(threadPool);
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    server.addConnector(connector);

    HandlerList handlers = new HandlerList();

    handlers.addHandler(new AbstractHandler() {
        @Override
        public void handle(String s, Request jettyRequest,
                HttpServletRequest servletRequest, HttpServletResponse servletResponse)
                throws IOException, ServletException {
            servletResponse.setCharacterEncoding("UTF-8");
            jettyRequest.setHandled(false); 
        }
    });

    ServletHandler servletHandler = new ServletHandler();
    servletHandler.addServletWithMapping(BossGameJettyServlet.class, "/PlayBossMassiveGame");
    servletHandler.addServletWithMapping(ArenaGameJettyServlet.class, "/PlayAutoMassiveGame");
    servletHandler.addServletWithMapping(MapGameJettyServlet.class, "/PlayMapMassiveGame");
    servletHandler.addServletWithMapping(LilithGameJettyServlet.class, "/PlayLilithMassiveGame");
    servletHandler.addServletWithMapping(PingJettyServlet.class, "/Ping");
    handlers.addHandler(servletHandler);

    server.setHandler(handlers);
    server.start();
    server.join();
}