org.eclipse.jetty.server.handler.ContextHandlerCollection#setHandlers ( )源码实例Demo

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

源代码1 项目: incubator-iotdb   文件: JettyUtil.java
public static Server getJettyServer(List<ServletContextHandler> handlers, int port) {
  Server server = new Server(port);
  ErrorHandler errorHandler = new ErrorHandler();
  errorHandler.setShowStacks(true);
  errorHandler.setServer(server);
  server.addBean(errorHandler);

  ContextHandlerCollection collection = new ContextHandlerCollection();
  ServletContextHandler[] sch = new ServletContextHandler[handlers.size()];
  for (int i = 0; i < handlers.size(); i++) {
    sch[i] = handlers.get(i);
  }
  collection.setHandlers(sch);
  server.setHandler(collection);
  return server;
}
 
源代码2 项目: pulsar   文件: ProxyServer.java
public void start() throws PulsarServerException {
    log.info("Starting web socket proxy at port {}", conf.getWebServicePort().get());
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(true);
    requestLog.setLogTimeZone(TimeZone.getDefault().getID());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    handlers.add(0, new ContextHandlerCollection());
    handlers.add(requestLogHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    server.setHandler(handlerCollection);

    try {
        server.start();
    } catch (Exception e) {
        throw new PulsarServerException(e);
    }
}
 
源代码3 项目: JVoiceXML   文件: DocumentStorage.java
/**
 * Starts the document storage. Afterwards it will be ready to serve
 * documents.
 * 
 * @throws Exception
 *             error starting the web server
 * 
 * @since 0.7.8
 */
public void start() throws Exception {
    if (storagePort < 0) {
        return;
    }
    server = new Server(storagePort);
    ContextHandler rootContext = new ContextHandler();
    rootContext.setHandler(internalGrammarHandler);
    ContextHandler internalGrammarContext = new ContextHandler(
            InternalGrammarDocumentHandler.CONTEXT_PATH);
    internalGrammarContext.setHandler(internalGrammarHandler);
    ContextHandler builtinGrammarContext = new ContextHandler(
            BuiltinGrammarHandler.CONTEXT_PATH);
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    builtinGrammarContext.setHandler(builtinGrammarHandler);
    ContextHandler[] handlers = new ContextHandler[] { rootContext,
            internalGrammarContext, builtinGrammarContext };
    contexts.setHandlers(handlers);
    server.setHandler(contexts);
    server.start();
    LOGGER.info("document storage started on port " + storagePort);
}
 
源代码4 项目: joynr   文件: ServersUtil.java
public static Server startControlledBounceproxy(String bpId) throws Exception {

        final int port = ServletUtil.findFreePort();
        final String bpUrl = "http://localhost:" + port + "/bounceproxy/";

        System.setProperty("joynr.bounceproxy.id", bpId);
        System.setProperty("joynr.bounceproxy.controller.baseurl",
                           System.getProperty(MessagingPropertyKeys.BOUNCE_PROXY_URL));
        System.setProperty("joynr.bounceproxy.url4cc", bpUrl);
        System.setProperty("joynr.bounceproxy.url4bpc", bpUrl);

        ContextHandlerCollection contexts = new ContextHandlerCollection();
        contexts.setHandlers(new Handler[]{ createControlledBounceproxyWebApp("", null) });
        Server server = startServer(contexts, port);

        System.clearProperty("joynr.bounceproxy.id");
        System.clearProperty("joynr.bounceproxy.controller.baseurl");
        System.clearProperty("joynr.bounceproxy.url4cc");
        System.clearProperty("joynr.bounceproxy.url4bpc");

        return server;
    }
 
源代码5 项目: rest-utils   文件: ApplicationServer.java
private void finalizeHandlerCollection(HandlerCollection handlers, HandlerCollection wsHandlers) {
  /* DefaultHandler must come last eo ensure all contexts
   * have a chance to handle a request first */
  handlers.addHandler(new DefaultHandler());
  /* Needed for graceful shutdown as per `setStopTimeout` documentation */
  StatisticsHandler statsHandler = new StatisticsHandler();
  statsHandler.setHandler(handlers);

  ContextHandlerCollection contexts = new ContextHandlerCollection();
  contexts.setHandlers(new Handler[]{
      statsHandler,
      wsHandlers
  });

  super.setHandler(wrapWithGzipHandler(contexts));
}
 
源代码6 项目: binlake   文件: TowerServer.java
/**
 * bind handler for right url
 */
private void bindHandler() {
    logger.debug("bindHandler");
    CreateZNodesHandler.register();
    RemoveNodeHandler.register();
    ExistNodeHandler.register();
    ResetCounterHandler.register();
    SetInstanceOffline.register();
    SetInstanceOnline.register();
    SetBinlogPosHandler.register();
    SetLeaderHandler.register();
    SetCandidateHandler.register();
    SetTerminalHandler.register();
    GetSlaveBinlogHandler.register();
    SetAdminHandler.register();

    ContextHandlerCollection contexts = new ContextHandlerCollection();

    Handler[] handlers = new Handler[ApiCenter.CONTEXTS.size()];
    int index = 0;

    for (ContextHandler handler : ApiCenter.CONTEXTS) {
        handlers[index++] = handler;
    }
    contexts.setHandlers(handlers);
    server.setHandler(contexts);
}
 
源代码7 项目: kylin-on-parquet-v2   文件: StreamingReceiver.java
private void startHttpServer() throws Exception {
    KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
    createAndConfigHttpServer(kylinConfig);

    ContextHandlerCollection contexts = new ContextHandlerCollection();

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

    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    ctx.setConfigLocation("classpath:applicationContext.xml");
    ctx.refresh();
    DispatcherServlet dispatcher = new DispatcherServlet(ctx);
    context.addServlet(new ServletHolder(dispatcher), "/api/*");

    ContextHandler logContext = new ContextHandler("/kylin/logs");
    String logDir = getLogDir(kylinConfig);
    ResourceHandler logHandler = new ResourceHandler();
    logHandler.setResourceBase(logDir);
    logHandler.setDirectoriesListed(true);
    logContext.setHandler(logHandler);

    contexts.setHandlers(new Handler[] { context, logContext });
    httpServer.setHandler(contexts);
    httpServer.start();
    httpServer.join();
}
 
源代码8 项目: joynr   文件: ServersUtil.java
public static Server startSSLServers(SSLSettings settings, int port) throws Exception {
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[]{ createBounceproxyWebApp(), discoveryWebApp(), accessControlWebApp() });
    Server server = startSSLServer(contexts, settings, port);
    setBounceProxyUrl();
    setDirectoriesUrl();

    return server;
}
 
源代码9 项目: apollo   文件: BaseIntegrationTest.java
/**
 * init and start a jetty server, remember to call server.stop when the task is finished
 *
 * @param handlers
 * @throws Exception
 */
protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception {
  server = new Server(PORT);

  ContextHandlerCollection contexts = new ContextHandlerCollection();
  contexts.setHandlers(handlers);
  contexts.addHandler(mockMetaServerHandler());

  server.setHandler(contexts);
  server.start();

  return server;
}
 
源代码10 项目: joynr   文件: ServersUtil.java
public static Server startServers() throws Exception {
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[]{ createBounceproxyWebApp(), discoveryWebApp(), accessControlWebApp() });

    System.setProperty("log4j.configuration",
                       Thread.currentThread()
                             .getContextClassLoader()
                             .getResource("log4j_backend.properties")
                             .toString());

    Server server = startServer(contexts);
    return server;
}
 
源代码11 项目: joynr   文件: ServersUtil.java
private static Server startBounceproxyController(String warFileName) throws Exception {
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[]{ createBounceproxyControllerWebApp(warFileName, "", null) });

    final int port = ServletUtil.findFreePort();
    Server server = startServer(contexts, port);
    String serverUrl = "http://localhost:" + port;
    String bounceProxyUrl = serverUrl + "/controller/";
    System.setProperty(MessagingPropertyKeys.BOUNCE_PROXY_URL, bounceProxyUrl);
    return server;
}
 
源代码12 项目: nifi   文件: AtlasAPIV2ServerEmulator.java
private void createServer() throws Exception {
    server = new Server();
    final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/");

    final ServletContextHandler atlasApiV2Context = new ServletContextHandler();
    atlasApiV2Context.setContextPath("/api/atlas/v2/");

    handlerCollection.setHandlers(new Handler[]{staticContext, atlasApiV2Context});

    server.setHandler(handlerCollection);

    final ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newClassPathResource("public", false, false));
    staticContext.setHandler(resourceHandler);

    final ServletHandler servletHandler = new ServletHandler();
    atlasApiV2Context.insertHandler(servletHandler);

    httpConnector = new ServerConnector(server);
    httpConnector.setPort(21000);

    server.setConnectors(new Connector[]{httpConnector});

    servletHandler.addServletWithMapping(TypeDefsServlet.class, "/types/typedefs/");
    servletHandler.addServletWithMapping(EntityBulkServlet.class, "/entity/bulk/");
    servletHandler.addServletWithMapping(EntityGuidServlet.class, "/entity/guid/*");
    servletHandler.addServletWithMapping(SearchByUniqueAttributeServlet.class, "/entity/uniqueAttribute/type/*");
    servletHandler.addServletWithMapping(SearchBasicServlet.class, "/search/basic/");
    servletHandler.addServletWithMapping(LineageServlet.class, "/debug/lineage/");

    notificationServerEmulator = new AtlasNotificationServerEmulator();
}
 
源代码13 项目: kylin   文件: StreamingReceiver.java
private void startHttpServer() throws Exception {
    KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
    createAndConfigHttpServer(kylinConfig);

    ContextHandlerCollection contexts = new ContextHandlerCollection();

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

    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    ctx.setConfigLocation("classpath:applicationContext.xml");
    ctx.refresh();
    DispatcherServlet dispatcher = new DispatcherServlet(ctx);
    context.addServlet(new ServletHolder(dispatcher), "/api/*");

    ContextHandler logContext = new ContextHandler("/kylin/logs");
    String logDir = getLogDir(kylinConfig);
    ResourceHandler logHandler = new ResourceHandler();
    logHandler.setResourceBase(logDir);
    logHandler.setDirectoriesListed(true);
    logContext.setHandler(logHandler);

    contexts.setHandlers(new Handler[] { context, logContext });
    httpServer.setHandler(contexts);
    httpServer.start();
    httpServer.join();
}
 
源代码14 项目: raccoon4   文件: ServerManager.java
/**
 * Start the webserver.
 * 
 * @param lm
 *          the {@link Lifecycle} to notify when a client initiates a transfer
 *          the user should know about.
 */
public void startup(LifecycleManager lm) {
	this.appListHandler = new AppListHandler(layout, lm);
	this.focusedAppHandler = new AppListHandler(layout, lm);
	this.fileHandler = new FileHandler(lm);
	this.resourceHandler = new ResourceHandler();

	ContextHandler list = new ContextHandler(APPCOLLECTIONPATH);
	list.setHandler(appListHandler);

	ContextHandler focused = new ContextHandler(APPSINGLEPATH);
	focused.setHandler(focusedAppHandler);

	ContextHandler files = new ContextHandler(FILEPATH);
	files.setHandler(fileHandler);

	ContextHandler rsrc = new ContextHandler(RSRCPATH);
	rsrc.setHandler(resourceHandler);

	AbstractHandler[] tmp = { list, focused, files, rsrc };

	ContextHandlerCollection handlers = new ContextHandlerCollection();
	handlers.setHandlers(tmp);

	server = new Server(0);
	server.setHandler(handlers);

	try {
		server.start();
	}
	catch (Exception e) {
		e.printStackTrace();
	}

	synchronized (lock) {
		lock.notifyAll();
	}
}
 
源代码15 项目: lancoder   文件: ApiServer.java
@Override
public void run() {
	try {
		Properties jettyShutUpProperties = new Properties();
		jettyShutUpProperties.setProperty("org.eclipse.jetty.LEVEL", "WARN");
		StdErrLog.setProperties(jettyShutUpProperties);

		server = new Server(master.getConfig().getApiServerPort());

		// static resources handler
		ContextHandler ctxStatic = new ContextHandler("/");
		ResourceHandler staticHandler = new ResourceHandler();
		staticHandler.setResourceBase(this.getClass().getClassLoader().getResource(WEB_DIR).toExternalForm());
		// staticHandler.setResourceBase("src/main/web/web_resources");
		staticHandler.setDirectoriesListed(true);
		ctxStatic.setHandler(staticHandler);

		// api handler
		ContextHandler ctxApi = buildServletContextHandler();
		ctxApi.setContextPath("/api");

		ContextHandlerCollection contexts = new ContextHandlerCollection();
		contexts.setHandlers(new Handler[] { ctxStatic, ctxApi });
		server.setHandler(contexts);

		server.start();
		server.join();
	} catch (Exception e) {
		// TODO alert master api server api crashed
		e.printStackTrace();
	}
}
 
源代码16 项目: localization_nifi   文件: TestHttpClient.java
@BeforeClass
public static void setup() throws Exception {
    // Create embedded Jetty server
    // Use less threads to mitigate Gateway Timeout (504) with proxy test
    // Minimum thread pool size = (acceptors=2 + selectors=8 + request=1), defaults to max=200
    final QueuedThreadPool threadPool = new QueuedThreadPool(20);
    server = new Server(threadPool);

    final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setContextPath("/nifi-api");

    final ServletContextHandler wrongPathContextHandler = new ServletContextHandler();
    wrongPathContextHandler.setContextPath("/wrong/nifi-api");

    handlerCollection.setHandlers(new Handler[]{contextHandler, wrongPathContextHandler});

    server.setHandler(handlerCollection);

    final ServletHandler servletHandler = new ServletHandler();
    contextHandler.insertHandler(servletHandler);

    final ServletHandler wrongPathServletHandler = new ServletHandler();
    wrongPathContextHandler.insertHandler(wrongPathServletHandler);

    final SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath("src/test/resources/certs/localhost-ks.jks");
    sslContextFactory.setKeyStorePassword("localtest");
    sslContextFactory.setKeyStoreType("JKS");

    httpConnector = new ServerConnector(server);

    final HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());
    sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https));

    server.setConnectors(new Connector[] { httpConnector, sslConnector });

    wrongPathServletHandler.addServletWithMapping(WrongSiteInfoServlet.class, "/site-to-site");

    servletHandler.addServletWithMapping(SiteInfoServlet.class, "/site-to-site");
    servletHandler.addServletWithMapping(PeersServlet.class, "/site-to-site/peers");

    servletHandler.addServletWithMapping(PortTransactionsAccessDeniedServlet.class, "/data-transfer/input-ports/input-access-denied-id/transactions");
    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-running-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-running-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesServlet.class, "/data-transfer/input-ports/input-running-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutAfterDataExchangeServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-running-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-running-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesServlet.class, "/data-transfer/output-ports/output-running-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutAfterDataExchangeServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions/transaction-id/flow-files");

    server.start();

    logger.info("Starting server on port {} for HTTP, and {} for HTTPS", httpConnector.getLocalPort(), sslConnector.getLocalPort());

    startProxyServer();
    startProxyServerWithAuth();
}
 
源代码17 项目: incubator-sentry   文件: SentryWebServer.java
public SentryWebServer(List<EventListener> listeners, int port, Configuration conf) {
  this.port = port;
  server = new Server(port);
  ServletContextHandler servletContextHandler = new ServletContextHandler();
  ServletHolder servletHolder = new ServletHolder(AdminServlet.class);
  servletContextHandler.addServlet(servletHolder, "/*");

  for(EventListener listener:listeners) {
    servletContextHandler.addEventListener(listener);
  }

  ServletHolder confServletHolder = new ServletHolder(ConfServlet.class);
  servletContextHandler.addServlet(confServletHolder, "/conf");
  servletContextHandler.getServletContext()
      .setAttribute(ConfServlet.CONF_CONTEXT_ATTRIBUTE, conf);

  ResourceHandler resourceHandler = new ResourceHandler();
  resourceHandler.setDirectoriesListed(true);
  URL url = this.getClass().getResource(RESOURCE_DIR);
  try {
    resourceHandler.setBaseResource(Resource.newResource(url.toString()));
  } catch (IOException e) {
    LOGGER.error("Got exception while setBaseResource for Sentry Service web UI", e);
  }
  resourceHandler.setWelcomeFiles(new String[]{WELCOME_PAGE});
  ContextHandler contextHandler= new ContextHandler();
  contextHandler.setHandler(resourceHandler);

  ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
  contextHandlerCollection.setHandlers(new Handler[]{contextHandler, servletContextHandler});

  String authMethod = conf.get(ServerConfig.SENTRY_WEB_SECURITY_TYPE);
  if (!ServerConfig.SENTRY_WEB_SECURITY_TYPE_NONE.equals(authMethod)) {
    /**
     * SentryAuthFilter is a subclass of AuthenticationFilter and
     * AuthenticationFilter tagged as private and unstable interface:
     * While there are not guarantees that this interface will not change,
     * it is fairly stable and used by other projects (ie - Oozie)
     */
    FilterHolder filterHolder = servletContextHandler.addFilter(SentryAuthFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    filterHolder.setInitParameters(loadWebAuthenticationConf(conf));
  }

  server.setHandler(contextHandlerCollection);
}
 
源代码18 项目: pulsar   文件: WorkerServer.java
private void init() {
    server = new Server(webServerExecutor);

    List<ServerConnector> connectors = new ArrayList<>();
    httpConnector = new ServerConnector(server, 1, 1);
    httpConnector.setPort(this.workerConfig.getWorkerPort());
    connectors.add(httpConnector);

    List<Handler> handlers = new ArrayList<>(4);
    handlers.add(
            newServletContextHandler("/admin", new ResourceConfig(Resources.getApiV2Resources()), workerService));
    handlers.add(
            newServletContextHandler("/admin/v2", new ResourceConfig(Resources.getApiV2Resources()), workerService));
    handlers.add(
            newServletContextHandler("/admin/v3", new ResourceConfig(Resources.getApiV3Resources()), workerService));
    // don't require auth for metrics or config routes
    handlers.add(newServletContextHandler("/", new ResourceConfig(Resources.getRootResources()), workerService, workerConfig.isAuthenticateMetricsEndpoint()));

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(true);
    requestLog.setLogTimeZone(TimeZone.getDefault().getID());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    handlers.add(0, new ContextHandlerCollection());
    handlers.add(requestLogHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    server.setHandler(handlerCollection);

    if (this.workerConfig.getWorkerPortTls() != null) {
        try {
            SslContextFactory sslCtxFactory = SecurityUtility.createSslContextFactory(
                    this.workerConfig.isTlsAllowInsecureConnection(), this.workerConfig.getTlsTrustCertsFilePath(),
                    this.workerConfig.getTlsCertificateFilePath(), this.workerConfig.getTlsKeyFilePath(),
                    this.workerConfig.isTlsRequireTrustedClientCertOnConnect(),
                    true,
                    this.workerConfig.getTlsCertRefreshCheckDurationSec());
            httpsConnector = new ServerConnector(server, 1, 1, sslCtxFactory);
            httpsConnector.setPort(this.workerConfig.getWorkerPortTls());
            connectors.add(httpsConnector);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Limit number of concurrent HTTP connections to avoid getting out of file descriptors
    connectors.forEach(c -> c.setAcceptQueueSize(MAX_CONCURRENT_REQUESTS / connectors.size()));
    server.setConnectors(connectors.toArray(new ServerConnector[connectors.size()]));
}
 
源代码19 项目: Explorer   文件: ExplorerServer.java
public static void main(String[] args) throws Exception {
    ExplorerConfiguration conf = ExplorerConfiguration.create(ConstantsFolder.CT_NAME_FILE_INTERPRETERS_CONFIGURE);
    conf.setProperty("args", args);

    int port = conf.getInt(ExplorerConfiguration.ConfVars.EXPLORER_PORT);
    final Server server = setupJettyServer(port);
    websocket = new ExplorerWebSocketServer(port + 1);

    //REST api
    final ServletContextHandler restApi = setupRestApiContextHandler();
    /** NOTE: Swagger-core is included via the web.xml in web
     * But the rest of swagger is configured here
     */
    final ServletContextHandler swagger = setupSwaggerContextHandler(port);
    //Web UI
    final WebAppContext webApp = setupWebAppContext(conf);
    final WebAppContext webAppSwagg = setupWebAppSwagger(conf);

    //Add all handlers
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] { swagger, restApi, webApp, webAppSwagg });
    server.setHandler(contexts);

    websocket.start();
    LOG.info("Start explorer server");
    server.start();
    LOG.info("Started");

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override public void run() {
            LOG.info("Shutting down explorer Server ... ");
            try {
                server.stop();
                websocket.stop();
            } catch (Exception e) {
                LOG.error("Error while stopping servlet container", e);
            }
            LOG.info("Bye");
        }
    });
    server.join();
}
 
源代码20 项目: nifi   文件: WebSocketServerExample.java
@BeforeClass
public static void setup() throws Exception {
    server = new Server(0);

    final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ServletContextHandler contextHandler = new ServletContextHandler();
    servletHandler = new ServletHandler();
    contextHandler.insertHandler(servletHandler);

    handlerCollection.setHandlers(new Handler[]{contextHandler});

    server.setHandler(handlerCollection);

    httpConnector = new ServerConnector(server);
    httpConnector.setPort(50010);

    final SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath("src/test/resources/certs/keystore.jks");
    sslContextFactory.setKeyStorePassword("passwordpassword");
    sslContextFactory.setKeyStoreType("JKS");

    // Need to set SslContextFactory's endpointIdentificationAlgorithm to null; this is a server,
    // not a client.  Server does not need to perform hostname verification on the client.
    // Previous to Jetty 9.4.15.v20190215, this defaulted to null, and now defaults to "HTTPS".
    sslContextFactory.setEndpointIdentificationAlgorithm(null);

    final HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());
    sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https));
    sslConnector.setPort(50011);


    server.setConnectors(new Connector[]{httpConnector, sslConnector});

    servletHolder = servletHandler.addServletWithMapping(WSServlet.class, "/test");
    servletHolder = servletHandler.addServletWithMapping(ConnectionCheckServlet.class, "/check");

    server.start();

    logger.info("Starting server on port {} for HTTP, and {} for HTTPS", httpConnector.getLocalPort(), sslConnector.getLocalPort());


}