Java Code Examples for org.eclipse.jetty.util.thread.QueuedThreadPool#setName()

The following examples show how to use org.eclipse.jetty.util.thread.QueuedThreadPool#setName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebServerTask.java    From datacollector with Apache License 2.0 8 votes vote down vote up
@SuppressWarnings("squid:S2095")
private Server createRedirectorServer() {
  int unsecurePort = conf.get(HTTP_PORT_KEY, HTTP_PORT_DEFAULT);
  String hostname = conf.get(HTTP_BIND_HOST, HTTP_BIND_HOST_DEFAULT);

  QueuedThreadPool qtp = new QueuedThreadPool(25);
  qtp.setName(serverName + "Redirector");
  qtp.setDaemon(true);
  Server server = new LimitedMethodServer(qtp);
  InetSocketAddress addr = new InetSocketAddress(hostname, unsecurePort);
  ServerConnector connector = new ServerConnector(server);
  connector.setHost(addr.getHostName());
  connector.setPort(addr.getPort());
  server.setConnectors(new Connector[]{connector});

  ServletContextHandler context = new ServletContextHandler();
  context.addServlet(new ServletHolder(new RedirectorServlet()), "/*");
  context.setContextPath("/");
  server.setHandler(context);
  return server;
}
 
Example 2
Source File: JettyResourceFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	String name = this.threadPrefix + "@" + Integer.toHexString(hashCode());
	if (this.executor == null) {
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setName(name);
		this.executor = threadPool;
	}
	if (this.byteBufferPool == null) {
		this.byteBufferPool = new MappedByteBufferPool(2048,
				this.executor instanceof ThreadPool.SizedThreadPool
						? ((ThreadPool.SizedThreadPool) executor).getMaxThreads() / 2
						: ProcessorUtils.availableProcessors() * 2);
	}
	if (this.scheduler == null) {
		this.scheduler = new ScheduledExecutorScheduler(name + "-scheduler", false);
	}

	if (this.executor instanceof LifeCycle) {
		((LifeCycle)this.executor).start();
	}
	this.scheduler.start();
}
 
Example 3
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and configures a new Jetty instance.
 *
 * @param props the configuration
 */
public JettyServer(final NiFiProperties props) {
    final QueuedThreadPool threadPool = new QueuedThreadPool(props.getWebThreads());
    threadPool.setName("NiFi Web Server");

    // create the server
    this.server = new Server(threadPool);
    this.props = props;

    // enable the annotation based configuration to ensure the jsp container is initialized properly
    final Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
    classlist.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());

    // configure server
    configureConnectors(server);

    // load wars from the nar working directories
    loadWars(locateNarWorkingDirectories());
}
 
Example 4
Source File: CampServer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static Server startServer(ContextHandler context, String summary) {
    // FIXME port hardcoded
    int port = Networking.nextAvailablePort(8080);

    // use a nice name in the thread pool (otherwise this is exactly the same as Server defaults)
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setName("camp-jetty-server-"+port+"-"+threadPool.getName());

    Server server = new Server(threadPool);

    ServerConnector httpConnector = new ServerConnector(server);
    httpConnector.setPort(port);
    server.addConnector(httpConnector);

    server.setHandler(context);

    try {
        server.start();
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    } 
    log.info("CAMP REST server started ("+summary+") on");
    log.info("  http://localhost:"+httpConnector.getLocalPort()+"/");

    return server;
}
 
Example 5
Source File: JettyCoreServer.java    From jvm-sandbox with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void initHttpServer() {

        final String serverIp = cfg.getServerIp();
        final int serverPort = cfg.getServerPort();

        // 如果IP:PORT已经被占用,则无法继续被绑定
        // 这里说明下为什么要这么无聊加个这个判断,让Jetty的Server.bind()抛出异常不是更好么?
        // 比较郁闷的是,如果这个端口的绑定是"SO_REUSEADDR"端口可重用的模式,那么这个server是能正常启动,但无法正常工作的
        // 所以这里必须先主动检查一次端口占用情况,当然了,这里也会存在一定的并发问题,BUT,我认为这种概率事件我可以选择暂时忽略
        if (isPortInUsing(serverIp, serverPort)) {
            throw new IllegalStateException(format("address[%s:%s] already in using, server bind failed.",
                    serverIp,
                    serverPort
            ));
        }

        httpServer = new Server(new InetSocketAddress(serverIp, serverPort));
        QueuedThreadPool qtp = new QueuedThreadPool();
        // jetty线程设置为daemon,防止应用启动失败进程无法正常退出
        qtp.setDaemon(true);
        qtp.setName("sandbox-jetty-qtp-" + qtp.hashCode());
        httpServer.setThreadPool(qtp);
    }
 
Example 6
Source File: JettyServer.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
public JettyServer(final NiFiRegistryProperties properties, final CryptoKeyProvider cryptoKeyProvider, final String docsLocation) {
    final QueuedThreadPool threadPool = new QueuedThreadPool(properties.getWebThreads());
    threadPool.setName("NiFi Registry Web Server");

    this.properties = properties;
    this.masterKeyProvider = cryptoKeyProvider;
    this.docsLocation = docsLocation;
    this.server = new Server(threadPool);

    // enable the annotation based configuration to ensure the jsp container is initialized properly
    final Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
    classlist.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());

    try {
        configureConnectors();
        loadWars();
    } catch (final Throwable t) {
        startUpFailure(t);
    }
}
 
Example 7
Source File: JavaNetReverseProxy.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
public JavaNetReverseProxy(File cacheFolder) throws Exception {
    this.cacheFolder = cacheFolder;
    cacheFolder.mkdirs();
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JavaNetReverseProxy)");
    server = new Server(qtp);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);

    ServletContextHandler root = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
    root.addServlet(new ServletHolder(this), "/");

    ServerConnector connector = new ServerConnector(server);
    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
}
 
Example 8
Source File: JettyResourceFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	String name = this.threadPrefix + "@" + Integer.toHexString(hashCode());
	if (this.executor == null) {
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setName(name);
		this.executor = threadPool;
	}
	if (this.byteBufferPool == null) {
		this.byteBufferPool = new MappedByteBufferPool(2048,
				this.executor instanceof ThreadPool.SizedThreadPool
						? ((ThreadPool.SizedThreadPool) executor).getMaxThreads() / 2
						: ProcessorUtils.availableProcessors() * 2);
	}
	if (this.scheduler == null) {
		this.scheduler = new ScheduledExecutorScheduler(name + "-scheduler", false);
	}

	if (this.executor instanceof LifeCycle) {
		((LifeCycle)this.executor).start();
	}
	this.scheduler.start();
}
 
Example 9
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (HudsonTestCase)");
    server = new Server(qtp);

    explodedWarDir = WarExploder.getExplodedDir();
    WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
    context.setResourceBase(explodedWarDir.getPath());
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());

    ServerConnector connector = new ServerConnector(server);

    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();

    return context.getServletContext();
}
 
Example 10
Source File: WebClientFactoryImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private QueuedThreadPool createThreadPool(String consumerName, int minThreads, int maxThreads,
        int keepAliveTimeout) {
    QueuedThreadPool queuedThreadPool = new QueuedThreadPool(maxThreads, minThreads, keepAliveTimeout * 1000);
    queuedThreadPool.setName("ESH-httpClient-" + consumerName);
    queuedThreadPool.setDaemon(true);
    return queuedThreadPool;
}
 
Example 11
Source File: WebClientFactoryImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private QueuedThreadPool createThreadPool(String consumerName, int minThreads, int maxThreads,
        int keepAliveTimeout) {
    QueuedThreadPool queuedThreadPool = new QueuedThreadPool(maxThreads, minThreads, keepAliveTimeout * 1000);
    queuedThreadPool.setName("OH-httpClient-" + consumerName);
    queuedThreadPool.setDaemon(true);
    return queuedThreadPool;
}
 
Example 12
Source File: JettyManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private ThreadPool configureThreadPool(final int port) {
	final QueuedThreadPool threadPool = new QueuedThreadPool(threadPoolCapacity);
	threadPool.setMinThreads(minThreadCount);
	threadPool.setMaxThreads(maxThreadCount);
	threadPool.setName("Jetty thread pool [" + port + "]");
	threadPool.setDetailedDump(true);
	return threadPool;
}
 
Example 13
Source File: JettyServerFactory.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
public Server getObject() throws Exception {

    // Setup ThreadPool
    QueuedThreadPool threadPool = new QueuedThreadPool(
            jettyConfiguration.getPoolMaxThreads(),
            jettyConfiguration.getPoolMinThreads(),
            jettyConfiguration.getPoolIdleTimeout(),
            new ArrayBlockingQueue<Runnable>(jettyConfiguration.getPoolQueueSize())
    );
    threadPool.setName("gravitee-listener");

    Server server = new Server(threadPool);

    // Extra options
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);

    // Setup JMX
    if (jettyConfiguration.isJmxEnabled()) {
        MBeanContainer mbContainer = new MBeanContainer(
                ManagementFactory.getPlatformMBeanServer());
        server.addBean(mbContainer);
    }

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setOutputBufferSize(32768);
    httpConfig.setRequestHeaderSize(8192);
    httpConfig.setResponseHeaderSize(8192);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendDateHeader(false);

    // Setup Jetty HTTP or HTTPS Connector
    if (jettyConfiguration.isSecured()) {
        httpConfig.setSecureScheme("https");
        httpConfig.setSecurePort(jettyConfiguration.getHttpPort());

        // SSL Context Factory
        SslContextFactory sslContextFactory = new SslContextFactory.Server();

        if (jettyConfiguration.getKeyStorePath() != null) {
            sslContextFactory.setKeyStorePath(jettyConfiguration.getKeyStorePath());
            sslContextFactory.setKeyStorePassword(jettyConfiguration.getKeyStorePassword());

            if (KEYSTORE_TYPE_PKCS12.equalsIgnoreCase(jettyConfiguration.getKeyStoreType())) {
                sslContextFactory.setKeyStoreType(KEYSTORE_TYPE_PKCS12);
            }
        }

        if (jettyConfiguration.getTrustStorePath() != null) {
            sslContextFactory.setTrustStorePath(jettyConfiguration.getTrustStorePath());
            sslContextFactory.setTrustStorePassword(jettyConfiguration.getTrustStorePassword());

            if (KEYSTORE_TYPE_PKCS12.equalsIgnoreCase(jettyConfiguration.getTrustStoreType())) {
                sslContextFactory.setTrustStoreType(KEYSTORE_TYPE_PKCS12);
            }
        }

        HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
        httpsConfig.addCustomizer(new SecureRequestCustomizer());

        ServerConnector https = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
                new HttpConnectionFactory(httpsConfig));
        https.setHost(jettyConfiguration.getHttpHost());
        https.setPort(jettyConfiguration.getHttpPort());
        server.addConnector(https);
    } else {
        ServerConnector http = new ServerConnector(server,
                jettyConfiguration.getAcceptors(),
                jettyConfiguration.getSelectors(),
                new HttpConnectionFactory(httpConfig));
        http.setHost(jettyConfiguration.getHttpHost());
        http.setPort(jettyConfiguration.getHttpPort());
        http.setIdleTimeout(jettyConfiguration.getIdleTimeout());

        server.addConnector(http);
    }

    // Setup Jetty statistics
    if (jettyConfiguration.isStatisticsEnabled()) {
        StatisticsHandler stats = new StatisticsHandler();
        stats.setHandler(server.getHandler());
        server.setHandler(stats);
    }

    if (jettyConfiguration.isAccessLogEnabled()) {
        CustomRequestLog requestLog = new CustomRequestLog(
                new AsyncRequestLogWriter(jettyConfiguration.getAccessLogPath()),
                CustomRequestLog.EXTENDED_NCSA_FORMAT);

        server.setRequestLog(requestLog);
    }

    return server;
}
 
Example 14
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Creates a web server on which Jenkins can run
 *
 * @param contextPath              the context path at which to put Jenkins
 * @param portSetter               the port on which the server runs will be set using this function
 * @param classLoader              the class loader for the {@link WebAppContext}
 * @param localPort                port on which the server runs
 * @param loginServiceSupplier     configures the {@link LoginService} for the instance
 * @param contextAndServerConsumer configures the {@link WebAppContext} and the {@link Server} for the instance, before they are started
 * @return ImmutablePair consisting of the {@link Server} and the {@link ServletContext}
 * @since 2.50
 */
public static ImmutablePair<Server, ServletContext> _createWebServer(String contextPath, Consumer<Integer> portSetter,
                                                                     ClassLoader classLoader, int localPort,
                                                                     Supplier<LoginService> loginServiceSupplier,
                                                                     @CheckForNull BiConsumer<WebAppContext, Server> contextAndServerConsumer)
        throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JenkinsRule)");
    Server server = new Server(qtp);

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(classLoader);
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(loginServiceSupplier.get());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");
    if (System.getProperty("port") != null) {
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else if (localPort != 0) {
        connector.setPort(localPort);
    }

    server.addConnector(connector);
    if (contextAndServerConsumer != null) {
        contextAndServerConsumer.accept(context, server);
    }
    server.start();

    portSetter.accept(connector.getLocalPort());

    ServletContext servletContext =  context.getServletContext();
    return new ImmutablePair<>(server, servletContext);
}
 
Example 15
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
public void start() {

        if (!isHttpBindServiceEnabled()) {
            return;
        }

        // this is the number of threads allocated to each connector/port
        final int processingThreads = JiveGlobals.getIntProperty(HTTP_BIND_THREADS, HTTP_BIND_THREADS_DEFAULT);

        final QueuedThreadPool tp = new QueuedThreadPool(processingThreads);
        tp.setName("Jetty-QTP-BOSH");

        httpBindServer = new Server(tp);
        if (JMXManager.isEnabled()) {
            JMXManager jmx = JMXManager.getInstance();
            httpBindServer.addBean(jmx.getContainer());
        }

        final Connector httpConnector = createConnector( httpBindServer );
        final Connector httpsConnector = createSSLConnector( httpBindServer);

        if (httpConnector == null && httpsConnector == null) {
            httpBindServer = null;
            return;
        }
        if (httpConnector != null) {
            httpBindServer.addConnector(httpConnector);
        }
        if (httpsConnector != null) {
            httpBindServer.addConnector(httpsConnector);
        }

        httpBindServer.setHandler( handlerList );

        try {
            httpBindServer.start();
            handlerList.start();
            extensionHandlers.start();

            CertificateManager.addListener(this);

            Log.info("HTTP bind service started");
        }
        catch (Exception e) {
            Log.error("Error starting HTTP bind service", e);
        }

        if ( JiveGlobals.getBooleanProperty( "jetty.temp-file-toucher.enabled", true ) ) {
            tempFileToucherTask = new TempFileToucherTask( httpBindServer );
            final long period = JiveGlobals.getLongProperty( "jetty.temp-file-toucher.period", JiveConstants.DAY );
            TaskEngine.getInstance().schedule( tempFileToucherTask, period, period );
        }
    }
 
Example 16
Source File: JdbcBridge.java    From clickhouse-jdbc-bridge with Apache License 2.0 4 votes vote down vote up
@Override
@SneakyThrows
public void run() {
    log.info("Starting jdbc-bridge");

    JdbcDriverLoader.load(config.getDriverPath());

    BridgeConnectionManager manager = new BridgeConnectionManager();
    if (null != config.getConnectionFile()) {
        manager.load(config.getConnectionFile());
    }

    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(new ServletHolder(new QueryHandlerServlet(manager)), "/");
    handler.addServletWithMapping(new ServletHolder(new ColumnsInfoServlet(manager, new ClickHouseConverter())), "/columns_info");
    handler.addServletWithMapping(new ServletHolder(new IdentifierQuoteServlet(manager)), "/identifier_quote");
    handler.addServletWithMapping(new ServletHolder(new PingHandlerServlet()), "/ping");
    handler.addFilterWithMapping(RequestLogger.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    InetSocketAddress address = new InetSocketAddress(config.getListenHost(), config.getHttpPort());
    log.info("Will bind to {}", address);

    // this tricks are don in order to get good thread name in logs :(
    QueuedThreadPool pool = new QueuedThreadPool(1024, 10); // @todo make configurable?
    pool.setName("HTTP Handler");
    Server jettyServer = new Server(pool);
    ServerConnector connector = new ServerConnector(jettyServer);

    // @todo a temporary solution for dealing with too long URI for some endpoints
    HttpConfiguration httpConfiguration = new HttpConfiguration();
    httpConfiguration.setRequestHeaderSize(24 * 1024);
    HttpConnectionFactory factory = new HttpConnectionFactory(httpConfiguration);
    connector.setConnectionFactories(Collections.singleton(factory));

    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    jettyServer.setConnectors(new Connector[]{connector});

    jettyServer.setHandler(handler);
    jettyServer.setErrorHandler(new ErrorHandler() {
        @Override
        protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
            writer.write(message);
        }
    });

    try {
        log.info("Starting server");
        jettyServer.start();
        log.info("Server is ready to accept connections");
        jettyServer.join();
    } finally {
        jettyServer.destroy();
    }
}
 
Example 17
Source File: EsigateServer.java    From esigate with Apache License 2.0 4 votes vote down vote up
/**
 * Create and start server.
 * 
 * @throws Exception
 *             when server cannot be started.
 */
public static void start() throws Exception {
    MetricRegistry registry = new MetricRegistry();

    QueuedThreadPool threadPool = new InstrumentedQueuedThreadPool(registry);
    threadPool.setName("esigate");
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);

    srv = new Server(threadPool);
    srv.setStopAtShutdown(true);
    srv.setStopTimeout(5000);

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setOutputBufferSize(outputBufferSize);
    httpConfig.setSendServerVersion(false);
    Timer processTime = registry.timer("processTime");

    try (ServerConnector connector =
            new InstrumentedServerConnector("main", EsigateServer.port, srv, registry,
                    new InstrumentedConnectionFactory(new HttpConnectionFactory(httpConfig), processTime));
            ServerConnector controlConnector = new ServerConnector(srv)) {

        // Main connector
        connector.setIdleTimeout(EsigateServer.idleTimeout);
        connector.setSoLingerTime(-1);
        connector.setName("main");
        connector.setAcceptQueueSize(200);

        // Control connector
        controlConnector.setHost("127.0.0.1");
        controlConnector.setPort(EsigateServer.controlPort);
        controlConnector.setName("control");

        srv.setConnectors(new Connector[] {connector, controlConnector});
        // War
        ProtectionDomain protectionDomain = EsigateServer.class.getProtectionDomain();
        String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();
        String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent();

        File workDir = resetTempDirectory(currentDir);

        WebAppContext context = new WebAppContext(warFile, EsigateServer.contextPath);
        context.setServer(srv);
        context.setTempDirectory(workDir);
        if (StringUtils.isNoneEmpty(sessionCookieName)) {
            context.getSessionHandler().getSessionCookieConfig().setName(sessionCookieName);
        }
        // Add extra classpath (allows to add extensions).
        if (EsigateServer.extraClasspath != null) {
            context.setExtraClasspath(EsigateServer.extraClasspath);
        }

        // Add the handlers
        HandlerCollection handlers = new HandlerList();
        // control handler must be the first one.
        // Work in progress, currently disabled.
        handlers.addHandler(new ControlHandler(registry));
        InstrumentedHandler ih = new InstrumentedHandler(registry);
        ih.setName("main");
        ih.setHandler(context);
        handlers.addHandler(ih);

        srv.setHandler(handlers);
        srv.start();
        srv.join();

    }

}
 
Example 18
Source File: JettyServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
public JettyServer(final NiFiProperties props, final Set<Bundle> bundles) {
    final QueuedThreadPool threadPool = new QueuedThreadPool(props.getWebThreads());
    threadPool.setName("NiFi Web Server");

    // create the server
    this.server = new Server(threadPool);
    this.props = props;

    // enable the annotation based configuration to ensure the jsp container is initialized properly
    final Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
    classlist.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());

    // configure server
    configureConnectors(server);

    // load wars from the bundle
    final Handler warHandlers = loadInitialWars(bundles);

    final HandlerList allHandlers = new HandlerList();

    // Only restrict the host header if running in HTTPS mode
    if (props.isHTTPSConfigured()) {
        // Create a handler for the host header and add it to the server
        HostHeaderHandler hostHeaderHandler = new HostHeaderHandler(props);
        logger.info("Created HostHeaderHandler [" + hostHeaderHandler.toString() + "]");

        // Add this before the WAR handlers
        allHandlers.addHandler(hostHeaderHandler);
    } else {
        logger.info("Running in HTTP mode; host headers not restricted");
    }


    final ContextHandlerCollection contextHandlers = new ContextHandlerCollection();
    contextHandlers.addHandler(warHandlers);
    allHandlers.addHandler(contextHandlers);
    server.setHandler(allHandlers);

    deploymentManager = new DeploymentManager();
    deploymentManager.setContextAttribute(CONTAINER_INCLUDE_PATTERN_KEY, CONTAINER_INCLUDE_PATTERN_VALUE);
    deploymentManager.setContexts(contextHandlers);
    server.addBean(deploymentManager);
}
 
Example 19
Source File: JettyServerWrapper.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void initialiseConnectors() throws Exception {
    threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);
    threadPool.setName("JettyThread");
    jettyServer = new Server(threadPool);

    jettyServer.setStopAtShutdown(true);

    MBeanContainer container = new MBeanContainer(mbeanServer);
    jettyServer.addBean(container);

    LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(jettyServer);
    lowResourcesMonitor.setPeriod(lowResourcesPeriod);
    lowResourcesMonitor.setLowResourcesIdleTimeout(lowResourcesIdleTime);
    lowResourcesMonitor.setMonitorThreads(lowResourcesMonitorThreads);
    lowResourcesMonitor.setMaxConnections(lowResourcesMaxConnections);
    lowResourcesMonitor.setMaxMemory(lowResourcesMaxMemory);
    lowResourcesMonitor.setMaxLowResourcesTime(lowResourcesMaxTime);
    jettyServer.addBean(lowResourcesMonitor);

    // US24803 - Needed for preventing Hashtable key collision DoS CVE-2012-2739
    jettyServer.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", maxFormContentSize);

    List<Connector> connectors = new ArrayList<Connector>();

    if (httpPort != -1) {
        httpConfiguration = createHttpConfiguration();
        setBufferSizes(httpConfiguration);
        if (httpForwarded) {
            httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpConnector = createHttpConnector(jettyServer, httpConfiguration, httpAcceptors, httpSelectors);
        httpConnector.setPort(httpPort);
        httpConnector.setReuseAddress(httpReuseAddress);
        httpConnector.setIdleTimeout(httpMaxIdle);
        httpConnector.setAcceptQueueSize(httpAcceptQueueSize);
        httpConnector.addBean(new ConnectorStatistics());

        connectors.add(httpConnector);
    }

    if (httpsPort != -1) {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(httpsKeystore.getFile().getCanonicalPath());
        sslContextFactory.setKeyStoreType(httpsKeystoreType);
        sslContextFactory.setKeyStorePassword(httpsKeyPassword);
        if (StringUtils.isNotBlank(httpsCertAlias)) {
            sslContextFactory.setCertAlias(httpsCertAlias);
        }
        sslContextFactory.setKeyManagerPassword(httpsKeyPassword);
        // if you need it then you defo want it
        sslContextFactory.setWantClientAuth(httpsNeedClientAuth || httpsWantClientAuth);
        sslContextFactory.setNeedClientAuth(httpsNeedClientAuth);
        sslContextFactory.setRenegotiationAllowed(httpsAllowRenegotiate);

        httpsConfiguration = createHttpConfiguration();
        setBufferSizes(httpsConfiguration);
        if (httpsForwarded) {
            httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }

        httpsConnector = createHttpsConnector(jettyServer, httpsConfiguration, httpsAcceptors, httpsSelectors, sslContextFactory);
        httpsConnector.setPort(httpsPort);
        httpsConnector.setReuseAddress(httpsReuseAddress);
        httpsConnector.setIdleTimeout(httpsMaxIdle);
        httpsConnector.setAcceptQueueSize(httpsAcceptQueueSize);
        httpsConnector.addBean(new ConnectorStatistics());

        mbeanServer.registerMBean(getKeystoreCertificateChains(), new ObjectName("CoUGAR.https:name=keyStore"));
        // truststore is not required if we don't want client auth
        if (httpsWantClientAuth) {
            sslContextFactory.setTrustStorePath(httpsTruststore.getFile().getCanonicalPath());
            sslContextFactory.setTrustStoreType(httpsTruststoreType);
            sslContextFactory.setTrustStorePassword(httpsTrustPassword);
            mbeanServer.registerMBean(getTruststoreCertificateChains(), new ObjectName("CoUGAR.https:name=trustStore"));
        }
        connectors.add(httpsConnector);
    }

    if (connectors.size() == 0) {
        throw new IllegalStateException("HTTP transport requires at least one port enabled to function correctly.");
    }

    jettyServer.setConnectors(connectors.toArray(new Connector[connectors.size()]));
}