org.eclipse.jetty.util.thread.QueuedThreadPool Java Examples

The following examples show how to use org.eclipse.jetty.util.thread.QueuedThreadPool. 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: 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 #3
Source File: AbstractService.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
public void startJettyContainer() throws Exception {
    jettyServer = new Server(serviceProperties.getServicePort());
    org.eclipse.jetty.util.thread.ThreadPool threadPool = jettyServer.getThreadPool();
    if (threadPool instanceof QueuedThreadPool) {
        ((QueuedThreadPool) threadPool).setMaxThreads(FeatureFlags.getMaxJettyThreads(serviceProperties));
        ((QueuedThreadPool) threadPool).setMinThreads(FeatureFlags.getMinJettyThreads(serviceProperties));
    } else {
        logger.warn("Expected ThreadPool to be instance of QueuedThreadPool, but was {}",
                jettyServer.getThreadPool().getClass().getName());
    }
    JettyComposer.compose(jettyServer);
    jettyServer.start();
    int port = ((ServerConnector) jettyServer.getConnectors()[0]).getLocalPort();
    logger.info("Jetty has started on port {}", port);
    serviceProperties.setServicePort(port);
}
 
Example #4
Source File: LegacyHttpServer.java    From grpc-proxy with Apache License 2.0 6 votes vote down vote up
private LegacyHttpServer(int port, int threads) {
  this.server = new Server(new QueuedThreadPool(threads));
  server.setHandler(
      new AbstractHandler() {
        @Override
        public void handle(
            String target,
            Request baseRequest,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {
          final String method = baseRequest.getParameter("method");
          if ("helloworld.Greeter/SayHello".equals(method)) {
            baseRequest.setHandled(true);
            sayHello(baseRequest, response);
          }
        }
      });

  final ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);
}
 
Example #5
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 #6
Source File: ExecutionContainerModule.java    From flux with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the Jetty server instance for the admin Dashboard and configures it with the @Named("ExecutionDashboardContext").
 * @param port where the service is available
 * @param acceptorThreads no. of acceptors
 * @param maxWorkerThreads max no. of worker threads
 * @return Jetty Server instance
 */
@Named("ExecutionDashboardJettyServer")
@Provides
@javax.inject.Singleton
Server getExecutionDashboardJettyServer(@Named("ExecutionDashboard.service.port") int port,
                               @Named("ExecutionDashboard.service.acceptors") int acceptorThreads,
                               @Named("ExecutionDashboard.service.selectors") int selectorThreads,
                               @Named("ExecutionDashboard.service.workers") int maxWorkerThreads,
                               @Named("ExecutionDashboardContext") WebAppContext webappContext) {
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxWorkerThreads);
    Server server = new Server(threadPool);
    ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
    http.setPort(port);
    server.addConnector(http);
    server.setHandler(webappContext);
    server.setStopAtShutdown(true);
    return server;
}
 
Example #7
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 #8
Source File: PitchforkService.java    From haystack-agent with Apache License 2.0 6 votes vote down vote up
public PitchforkService(final Config config, final ZipkinSpanProcessorFactory processorFactory) {
    this.cfg = HttpConfig.from(config);
    final QueuedThreadPool threadPool = new QueuedThreadPool(cfg.getMaxThreads(), cfg.getMinThreads(), cfg.getIdleTimeout());
    server = new Server(threadPool);

    final ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration()));
    httpConnector.setPort(cfg.getPort());
    httpConnector.setIdleTimeout(cfg.getIdleTimeout());
    server.addConnector(httpConnector);

    final ServletContextHandler context = new ServletContextHandler(server, "/");
    addResources(context, processorFactory);

    if (cfg.isGzipEnabled()) {
        final GzipHandler gzipHandler = new GzipHandler();
        gzipHandler.setInflateBufferSize(cfg.getGzipBufferSize());
        context.setGzipHandler(gzipHandler);
    }

    server.setStopTimeout(cfg.getStopTimeout());
    logger.info("pitchfork has been initialized successfully !");
}
 
Example #9
Source File: EmissaryServer.java    From emissary with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected Server configureServer() throws IOException, GeneralSecurityException {
    int maxThreads = 250;
    int minThreads = 10;
    int lowThreads = 50;
    int threadsPriority = 9;
    int idleTimeout = new Long(TimeUnit.MINUTES.toMillis(15)).intValue();

    QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
    threadPool.setLowThreadsThreshold(lowThreads);
    threadPool.setThreadsPriority(threadsPriority);

    Server server = new Server(threadPool);

    ServerConnector connector = cmd.isSslEnabled() ? getServerConnector(server) : new ServerConnector(server);
    connector.setHost(cmd.getHost());
    connector.setPort(cmd.getPort());

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

    return server;
}
 
Example #10
Source File: WebsocketMultipleConnectionTest.java    From knox with Apache License 2.0 6 votes vote down vote up
/**
 * Start Mock Websocket server that acts as backend.
 * @throws Exception exception on websocket server start
 */
private static void startWebsocketServer() throws Exception {

  backendServer = new Server(new QueuedThreadPool(254));
  ServerConnector connector = new ServerConnector(backendServer);
  backendServer.addConnector(connector);

  final WebsocketEchoHandler handler = new WebsocketEchoHandler();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(handler);
  backendServer.setHandler(context);

  // Start Server
  backendServer.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  backendServerUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/ws", host, port));
}
 
Example #11
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 #12
Source File: EmbeddedServerConfig.java    From secrets-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the embedded jetty server. The values are configured in <b>application.yaml</b>
 * file.
 *
 * @param port jetty server port
 * @param maxThreads thread pool min thread
 * @param minThreads thread pool max thread
 * @param idleTimeout maximum thread idle time
 * @param jmxEnabled true, if jetty jmx is enabled.
 * @return {@link JettyEmbeddedServletContainerFactory}
 */
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(
    @Value("${server.port:8443}") final int port,
    @Value("${jetty.thread-pool.max-threads:200}") final int maxThreads,
    @Value("${jetty.thread-pool.min-threads:8}") final int minThreads,
    @Value("${jetty.thread-pool.idle-timeout:60000}") final int idleTimeout,
    @Value("${jetty.jmx.enabled:true}") final boolean jmxEnabled) {
  log.info("Configuring Jetty server.");
  final JettyEmbeddedServletContainerFactory factory =
      new JettyEmbeddedServletContainerFactory(port);
  factory.addServerCustomizers(
      server -> {
        final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
        threadPool.setMinThreads(minThreads);
        threadPool.setMaxThreads(maxThreads);
        threadPool.setIdleTimeout(idleTimeout);
        log.info("Server thread pool config:  " + server.getThreadPool());
        // Jetty JMX config.
        if (jmxEnabled) {
          log.info("Exposing Jetty managed beans to the JMX platform server.");
          server.addBean(new MBeanContainer(ManagementFactory.getPlatformMBeanServer()));
        }
      });
  return factory;
}
 
Example #13
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 #14
Source File: ContainerModule.java    From flux with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the Jetty server instance for the admin Dashboard and configures it with the @Named("DashboardContext").
 * @param port where the service is available
 * @param acceptorThreads no. of acceptors
 * @param maxWorkerThreads max no. of worker threads
 * @return Jetty Server instance
 */
@Named("DashboardJettyServer")
@Provides
@Singleton
Server getDashboardJettyServer(@Named("Dashboard.service.port") int port,
		@Named("Dashboard.service.acceptors") int acceptorThreads,
		@Named("Dashboard.service.selectors") int selectorThreads,
		@Named("Dashboard.service.workers") int maxWorkerThreads,
		@Named("DashboardContext") WebAppContext webappContext) {
	QueuedThreadPool threadPool = new QueuedThreadPool();
       threadPool.setMaxThreads(maxWorkerThreads);
	Server server = new Server(threadPool);
	ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
	http.setPort(port);
	server.addConnector(http);
	server.setHandler(webappContext);
	server.setStopAtShutdown(true);
	return server;
}
 
Example #15
Source File: JettyServer.java    From pippo with Apache License 2.0 6 votes vote down vote up
protected Server createServer() {
    if (getSettings().getMaxThreads() > 0) {
        int maxThreads = getSettings().getMaxThreads();
        int minThreads = getSettings().getMinThreads();
        if (minThreads == 0) {
            minThreads = JettySettings.DEFAULT_MIN_THREADS;
        }
        int idleTimeout = getSettings().getIdleTimeout();
        if (idleTimeout == 0) {
            idleTimeout = JettySettings.DEFAULT_IDLE_TIMEOUT;
        }

        return new Server(new QueuedThreadPool(maxThreads, minThreads, idleTimeout));
    }

    return new Server();
}
 
Example #16
Source File: ApplicationServer.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Create the thread pool with request queue.
 *
 * @return thread pool used by the server
 */
private static ThreadPool createThreadPool(RestConfig config) {
  /* Create blocking queue for the thread pool. */
  int initialCapacity = config.getInt(RestConfig.REQUEST_QUEUE_CAPACITY_INITIAL_CONFIG);
  int growBy = config.getInt(RestConfig.REQUEST_QUEUE_CAPACITY_GROWBY_CONFIG);
  int maxCapacity = config.getInt(RestConfig.REQUEST_QUEUE_CAPACITY_CONFIG);
  log.info("Initial capacity {}, increased by {}, maximum capacity {}.",
          initialCapacity, growBy, maxCapacity);

  BlockingQueue<Runnable> requestQueue =
          new BlockingArrayQueue<>(initialCapacity, growBy, maxCapacity);
  
  return new QueuedThreadPool(config.getInt(RestConfig.THREAD_POOL_MAX_CONFIG),
          config.getInt(RestConfig.THREAD_POOL_MIN_CONFIG),
          requestQueue);
}
 
Example #17
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 #18
Source File: WebsocketMultipleConnectionTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private static void startGatewayServer() throws Exception {
  /* use default Max threads */
  gatewayServer = new Server(new QueuedThreadPool(254));
  final ServerConnector connector = new ServerConnector(gatewayServer);
  gatewayServer.addConnector(connector);

  /* workaround so we can add our handler later at runtime */
  HandlerCollection handlers = new HandlerCollection(true);

  /* add some initial handlers */
  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  handlers.addHandler(context);

  gatewayServer.setHandler(handlers);

  // Start Server
  gatewayServer.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));

  /* Setup websocket handler */
  setupGatewayConfig(backendServerUri.toString());

  final GatewayWebsocketHandler gatewayWebsocketHandler = new GatewayWebsocketHandler(
      gatewayConfig, services);
  handlers.addHandler(gatewayWebsocketHandler);
  gatewayWebsocketHandler.start();
}
 
Example #19
Source File: Jetty9ServerTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);
    when(server.getThreadPool()).thenReturn(new QueuedThreadPool(1));
    Answer<Void> setHandlerMock = invocation -> {
        serverLevelHandler = (Handler) invocation.getArguments()[0];
        serverLevelHandler.setServer((Server) invocation.getMock());
        return null;
    };
    Mockito.doAnswer(setHandlerMock).when(server).setHandler(any(Handler.class));

    appCaptor = ArgumentCaptor.forClass(App.class);
    Mockito.doNothing().when(deploymentManager).addApp(appCaptor.capture());

    when(systemEnvironment.getServerPort()).thenReturn(1234);
    when(systemEnvironment.getWebappContextPath()).thenReturn("context");
    when(systemEnvironment.getCruiseWar()).thenReturn("cruise.war");
    when(systemEnvironment.getParentLoaderPriority()).thenReturn(true);
    when(systemEnvironment.useCompressedJs()).thenReturn(true);
    when(systemEnvironment.get(SystemEnvironment.RESPONSE_BUFFER_SIZE)).thenReturn(1000);
    when(systemEnvironment.get(SystemEnvironment.IDLE_TIMEOUT)).thenReturn(2000);
    when(systemEnvironment.configDir()).thenReturn(configDir = temporaryFolder.newFolder());
    when(systemEnvironment.getJettyConfigFile()).thenReturn(new File("foo"));
    when(systemEnvironment.isSessionCookieSecure()).thenReturn(false);
    when(systemEnvironment.sessionTimeoutInSeconds()).thenReturn(1234);
    when(systemEnvironment.sessionCookieMaxAgeInSeconds()).thenReturn(5678);

    when(sslSocketFactory.getSupportedCipherSuites()).thenReturn(new String[]{});
    jetty9Server = new Jetty9Server(systemEnvironment, "pwd", server, deploymentManager);
    ReflectionUtil.setStaticField(Jetty9Server.class, "JETTY_XML_LOCATION_IN_JAR", "config");
}
 
Example #20
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 #21
Source File: JettyHttpServer.java    From dubbo-rpc-jsonrpc with Apache License 2.0 5 votes vote down vote up
public JettyHttpServer(URL url, final HttpHandler handler) {
    super(url, handler);
    DispatcherServlet.addHttpHandler(url.getPort(), handler);

    int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setDaemon(true);
    threadPool.setMaxThreads(threads);
    threadPool.setMinThreads(threads);

    server = new Server(threadPool);

    // HTTP connector
    ServerConnector connector = new ServerConnector(server);
    if (!url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) {
        connector.setHost(url.getHost());
    }
    connector.setPort(url.getPort());
    // connector.setIdleTimeout(30000);
    server.addConnector(connector);

    ServletHandler servletHandler = new ServletHandler();
    ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*");
    servletHolder.setInitOrder(2);

    server.insertHandler(servletHandler);

    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + url.getAddress() + ", cause: "
                + e.getMessage(), e);
    }
}
 
Example #22
Source File: ApiServer.java    From modernmt with Apache License 2.0 5 votes vote down vote up
public ApiServer(ServerOptions options) {
    requestPool = new QueuedThreadPool(250);
    jettyServer = new Server(requestPool);

    ServerConnector connector = new ServerConnector(jettyServer);
    connector.setPort(options.port);
    jettyServer.setConnectors(new Connector[]{connector});

    Handler rootHandler;
    String contextPath = normalizeContextPath(options.contextPath);
    if (contextPath == null) {
        ServletHandler router = new ServletHandler();
        router.addServletWithMapping(Router.class, "/*");
        rootHandler = router;
    } else {
        ServletContextHandler contextHandler = new ServletContextHandler();
        contextHandler.setContextPath(contextPath);
        contextHandler.addServlet(Router.class, "/*");
        rootHandler = contextHandler;
    }

    MultipartConfigInjectionHandler multipartWrapper = new MultipartConfigInjectionHandler(
            options.temporaryDirectory, options.maxFileSize, options.maxRequestSize, options.fileSizeThreshold);
    multipartWrapper.setHandler(rootHandler);

    jettyServer.setHandler(multipartWrapper);
}
 
Example #23
Source File: ZeppelinServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static Server setupJettyServer(ZeppelinConfiguration conf) {
  ThreadPool threadPool =
    new QueuedThreadPool(conf.getInt(ConfVars.ZEPPELIN_SERVER_JETTY_THREAD_POOL_MAX),
                         conf.getInt(ConfVars.ZEPPELIN_SERVER_JETTY_THREAD_POOL_MIN),
                         conf.getInt(ConfVars.ZEPPELIN_SERVER_JETTY_THREAD_POOL_TIMEOUT));
  final Server server = new Server(threadPool);
  initServerConnector(server, conf.getServerPort(), conf.getServerSslPort());
  return server;
}
 
Example #24
Source File: JettyHTTPServerEngine.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void setupThreadPool() {
    if (isSetThreadingParameters()) {

        ThreadPool pl = getThreadPool();
        //threads for the acceptors and selectors are taken from
        //the pool so we need to have room for those
        AbstractConnector aconn = (AbstractConnector) connector;
        int acc = aconn.getAcceptors() * 2;
        if (getThreadingParameters().isSetMaxThreads()
            && getThreadingParameters().getMaxThreads() <= acc) {
            throw new Fault(new Message("NOT_ENOUGH_THREADS", LOG,
                                        port,
                                        acc + 1,
                                        getThreadingParameters().getMaxThreads(),
                                        acc));
        }
        if (!(pl instanceof QueuedThreadPool)) {
            throw new Fault(new Message("NOT_A_QUEUED_THREAD_POOL", LOG, pl.getClass()));
        }
        if (getThreadingParameters().isThreadNamePrefixSet()) {
            ((QueuedThreadPool) pl).setName(getThreadingParameters().getThreadNamePrefix());
        }
        if (getThreadingParameters().isSetMinThreads()) {
            ((QueuedThreadPool) pl).setMinThreads(getThreadingParameters().getMinThreads());
        }
        if (getThreadingParameters().isSetMaxThreads()) {
            ((QueuedThreadPool) pl).setMaxThreads(getThreadingParameters().getMaxThreads());
        }
    }
}
 
Example #25
Source File: JettyWebServer.java    From Doradus with Apache License 2.0 5 votes vote down vote up
private Server configureJettyServer() {
    LinkedBlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<Runnable>(m_maxTaskQueue); 
    QueuedThreadPool threadPool = new QueuedThreadPool(m_maxconns, m_defaultMinThreads, m_defaultIdleTimeout, 
    		taskQueue);
    Server server = new Server(threadPool);
    server.setStopAtShutdown(true);
    return server;
}
 
Example #26
Source File: JettyServer.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public final void run() throws Exception {
    final org.eclipse.jetty.server.Server s = new org.eclipse.jetty.server.Server(new QueuedThreadPool(200, Runtime.getRuntime().availableProcessors()));

    final ServerConnector http = new ServerConnector(s);
    http.setReuseAddress(true);
    http.setAcceptQueueSize(100000);
    http.setPort(8080);
    s.addConnector(http);

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

    final ServletHolder holder1 = new ServletHolder(new PlaintextServlet());
    context.addServlet(holder1, "/plaintext");
    holder1.setAsyncSupported(true);
    final ServletHolder holder2 = new ServletHolder(new JsonServlet());
    context.addServlet(holder2, "/json");
    holder2.setAsyncSupported(true);

    s.setHandler(context);

    s.start();
    System.err.println("Server is up.");

    AbstractEmbeddedServer.waitUrlAvailable("http://localhost:8080/plaintext");
    AbstractEmbeddedServer.waitUrlAvailable("http://localhost:8080/json");
    System.err.println("Server test cases are instrumented and bootstrapped.");

    s.join();
}
 
Example #27
Source File: GatewayServer.java    From hadoop-mini-clusters with Apache License 2.0 5 votes vote down vote up
private synchronized void start() throws Exception {
        // Create the global context handler.
        contexts = new ContextHandlerCollection();
        // A map to keep track of current deployments by cluster name.
        deployments = new ConcurrentHashMap<String, WebAppContext>();

        // Start Jetty.
        jetty = new Server(new QueuedThreadPool(config.getThreadPoolMax()));
        jetty.addConnector(createConnector(jetty, config));
        jetty.setHandler(createHandlers(config, services, contexts));

        // Add Annotations processing into the Jetty server to support JSPs
//        Configuration.ClassList classlist = Configuration.ClassList.setServerDefault( jetty );
//        classlist.addBefore(
//                "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
//                "org.eclipse.jetty.annotations.AnnotationConfiguration" );

        // Load the current topologies.
        File topologiesDir = calculateAbsoluteTopologiesDir();
        log.loadingTopologiesFromDirectory(topologiesDir.getAbsolutePath());
        monitor = services.getService(GatewayServices.TOPOLOGY_SERVICE);
        monitor.addTopologyChangeListener(listener);
        monitor.reloadTopologies();

        try {
            jetty.start();
        } catch (IOException e) {
            log.failedToStartGateway(e);
            throw e;
        }

        cleanupTopologyDeployments();

        // Start the topology monitor.
        log.monitoringTopologyChangesInDirectory(topologiesDir.getAbsolutePath());
        monitor.startMonitor();
    }
 
Example #28
Source File: AthenzJettyContainer.java    From athenz with Apache License 2.0 5 votes vote down vote up
public void createServer(int maxThreads) {
    
    // Setup Thread pool
    
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);

    server = new Server(threadPool);
    handlers = new HandlerCollection();
    server.setHandler(handlers);
}
 
Example #29
Source File: ContainerModule.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Jetty server instance for the Flux API endpoint.
 * @param port where the service is available.
 * @return Jetty Server instance
 */
@Named("APIJettyServer")
@Provides
@Singleton
Server getAPIJettyServer(@Named("Api.service.port") int port,
						 @Named("APIResourceConfig")ResourceConfig resourceConfig,
						 @Named("Api.service.acceptors") int acceptorThreads,
						 @Named("Api.service.selectors") int selectorThreads,
						 @Named("Api.service.workers") int maxWorkerThreads,
						 ObjectMapper objectMapper, MetricRegistry metricRegistry) throws URISyntaxException, UnknownHostException {
	JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
	provider.setMapper(objectMapper);
	resourceConfig.register(provider);
	QueuedThreadPool threadPool = new QueuedThreadPool();
	threadPool.setMaxThreads(maxWorkerThreads);
	Server server = new Server(threadPool);
	ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
	http.setPort(port);
	server.addConnector(http);
	ServletContextHandler context = new ServletContextHandler(server, "/*");
	ServletHolder servlet = new ServletHolder(new ServletContainer(resourceConfig));
	context.addServlet(servlet, "/*");

	final InstrumentedHandler handler = new InstrumentedHandler(metricRegistry);
	handler.setHandler(context);
	server.setHandler(handler);

	server.setStopAtShutdown(true);
	return server;
}
 
Example #30
Source File: InfluxDBWarp10Plugin.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@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);
  }
}