Java Code Examples for org.eclipse.jetty.server.Server#setStopTimeout()

The following examples show how to use org.eclipse.jetty.server.Server#setStopTimeout() . 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: 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 2
Source File: JettyConfigurationHelper.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
static void configureServer( Server server, JettyConfiguration config )
{
    // Shutdown
    Integer gracefullShudownTimeout = config.gracefullShutdownTimeout().get();
    if( gracefullShudownTimeout != null )
    {
        server.setStopTimeout( gracefullShudownTimeout );
    }

    // Low resource max idle time
    Integer lowResourceMaxIdleTime = config.lowResourceMaxIdleTime().get();
    if( lowResourceMaxIdleTime != null )
    {
        LowResourceMonitor lowResourceMonitor = new LowResourceMonitor( server );
        lowResourceMonitor.setLowResourcesIdleTimeout( lowResourceMaxIdleTime );
        server.addBean( lowResourceMonitor );
    }

    // Statistics
    if( config.statistics().get() )
    {
        server.addBean( new ConnectorStatistics() );
    }
}
 
Example 3
Source File: JettyOpenTsdb.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
public void startServer() {
    jettyServer_ = new Server(port_);
    jettyServer_.setStopAtShutdown(true);
    jettyServer_.setStopTimeout(stopServerTimeout_);
    ServletHandler handler = new ServletHandler();
    jettyServer_.setHandler(handler);
    handler.addServletWithMapping(OpenTsdb_Put.class, "/api/put");
    
    try {
        jettyServer_.start();
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
}
 
Example 4
Source File: JettyInfluxdb.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
public void startServer() {
    jettyServer_ = new Server(port_);
    jettyServer_.setStopAtShutdown(true);
    jettyServer_.setStopTimeout(stopServerTimeout_);
    ServletHandler handler = new ServletHandler();
    jettyServer_.setHandler(handler);
    handler.addServletWithMapping(InfluxdbV1_Write.class, "/db/*");
    
    try {
        jettyServer_.start();
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
}
 
Example 5
Source File: JettyServer.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
public static Server start(int port) throws Exception {
    Server server = new Server(port);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    String resourcePath = JettyServer.class.getPackage().getName().replace('.', '/');
    webapp.setBaseResource(Resource.newClassPathResource(resourcePath));
    webapp.setParentLoaderPriority(true);

    server.setHandler(webapp);
    server.setStopTimeout(5000);
    server.start();
    return server;
}
 
Example 6
Source File: EmbeddedJetty.java    From junit-servers with MIT License 5 votes vote down vote up
private Server initServer() {
	log.debug("Initialize jetty server");
	Server server = new Server(configuration.getPort());
	server.setStopAtShutdown(configuration.isStopAtShutdown());
	server.setStopTimeout(configuration.getStopTimeout());
	return server;
}
 
Example 7
Source File: JettyServer.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
public static Server start(int port) throws Exception {
    Server server = new Server(port);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    String resourcePath = JettyServer.class.getPackage().getName().replace('.', '/');
    webapp.setBaseResource(Resource.newClassPathResource(resourcePath));
    webapp.setParentLoaderPriority(true);

    server.setHandler(webapp);
    server.setStopTimeout(5000);
    server.start();
    return server;
}
 
Example 8
Source File: HttpServer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static void start() {
   try {
      DefaultContext main = new DefaultContext();
      String base = StorageService.getFile("agent:///www").getPath();
      
      org.eclipse.jetty.servlet.DefaultServlet defServlet = new org.eclipse.jetty.servlet.DefaultServlet();
      main.addServlet("/", defServlet, ImmutableMap.<String,String>of(
         "dirAllowed", "false",
         "welcomeServlets", "true",
         "resourceBase", base
      ));

      main.context.setWelcomeFiles(new String[] { "index.html" });
      main.addServlet("/index.html", new DefaultServlet());
      if (SpyService.INSTANCE.isActive()) {
      	main.addServlet("/spy/api", new SpyApiServlet());
      	main.addServlet("/spy", new SpyServlet());
      }

      main.context.setErrorHandler(new ErrorPage());

      ContextHandlerCollection ctxs = new ContextHandlerCollection();
      ctxs.addHandler(main.context);

      ThreadFactory tf = new HttpThreadFactory();
      BlockingQueue<Runnable> queue = new SynchronousQueue<>();
      ThreadPoolExecutor exec = new ThreadPoolExecutor(4,16,60,TimeUnit.SECONDS,queue,tf);

      Server srv = new Server(new ExecutorThreadPool(exec));
      srv.setHandler(ctxs);
      srv.setStopAtShutdown(false);
      srv.setStopTimeout(500);

      Map<String,Map<Integer,Connector>> conns = new LinkedHashMap<>();
      Map<Integer,Connector> dconns = new LinkedHashMap<>();
      conns.put("", dconns);

      DefaultConnector conn = new DefaultConnector(srv,PORT);
      srv.setConnectors(new ServerConnector[] { conn.connector });
      dconns.put(PORT, conn);

      mainConnector = conn;
      connectors = conns;

      mainContext = main;
      contexts = ctxs;

      server = srv;
      srv.start();
   } catch (Exception ex) {
      log.warn("failed to start http server:", ex);
   }
}
 
Example 9
Source File: EmissaryServer.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
    }
}
 
Example 10
Source File: JettyHttpServer.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Inject
public JettyHttpServer(
        final CurrentContainer container,
        final Metric metric,
        final ServerConfig serverConfig,
        final ServletPathsConfig servletPathsConfig,
        final ThreadFactory threadFactory,
        final FilterBindings filterBindings,
        final ComponentRegistry<ConnectorFactory> connectorFactories,
        final ComponentRegistry<ServletHolder> servletHolders,
        final FilterInvoker filterInvoker,
        final AccessLog accessLog) {
    super(container);
    if (connectorFactories.allComponents().isEmpty())
        throw new IllegalArgumentException("No connectors configured.");
    this.metric = metric;

    initializeJettyLogging();

    server = new Server();
    server.setStopTimeout((long)(serverConfig.stopTimeout() * 1000.0));
    server.setRequestLog(new AccessLogRequestLog(accessLog));
    setupJmx(server, serverConfig);
    ((QueuedThreadPool)server.getThreadPool()).setMaxThreads(serverConfig.maxWorkerThreads());

    for (ConnectorFactory connectorFactory : connectorFactories.allComponents()) {
        ConnectorConfig connectorConfig = connectorFactory.getConnectorConfig();
        server.addConnector(connectorFactory.createConnector(metric, server));
        listenedPorts.add(connectorConfig.listenPort());
    }

    janitor = newJanitor(threadFactory);

    JDiscContext jDiscContext = new JDiscContext(
            filterBindings.getRequestFilters().activate(),
            filterBindings.getResponseFilters().activate(),
            container,
            janitor,
            metric,
            serverConfig);

    ServletHolder jdiscServlet = new ServletHolder(new JDiscHttpServlet(jDiscContext));
    FilterHolder jDiscFilterInvokerFilter = new FilterHolder(new JDiscFilterInvokerFilter(jDiscContext, filterInvoker));

    List<JDiscServerConnector> connectors = Arrays.stream(server.getConnectors())
            .map(JDiscServerConnector.class::cast)
            .collect(toList());

    server.setHandler(
            getHandlerCollection(
                    serverConfig,
                    servletPathsConfig,
                    connectors,
                    jdiscServlet,
                    servletHolders,
                    jDiscFilterInvokerFilter));

    int numMetricReporterThreads = 1;
    metricReporterExecutor = Executors.newScheduledThreadPool(
            numMetricReporterThreads,
            new ThreadFactoryBuilder()
                    .setDaemon(true)
                    .setNameFormat(JettyHttpServer.class.getName() + "-MetricReporter-%d")
                    .setThreadFactory(threadFactory)
                    .build()
    );
    metricReporterExecutor.scheduleAtFixedRate(new MetricTask(), 0, 2, TimeUnit.SECONDS);
}
 
Example 11
Source File: JettyServiceBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a newly-created {@link JettyService} based on the properties of this builder.
 */
public JettyService build() {
    final JettyServiceConfig config = new JettyServiceConfig(
            hostname, dumpAfterStart, dumpBeforeStop, stopTimeoutMillis, handler, requestLog,
            sessionIdManagerFactory, attrs, beans, handlerWrappers, eventListeners, lifeCycleListeners,
            configurators);

    final Function<ScheduledExecutorService, Server> serverFactory = blockingTaskExecutor -> {
        final Server server = new Server(new ArmeriaThreadPool(blockingTaskExecutor));

        if (config.dumpAfterStart() != null) {
            server.setDumpAfterStart(config.dumpAfterStart());
        }
        if (config.dumpBeforeStop() != null) {
            server.setDumpBeforeStop(config.dumpBeforeStop());
        }
        if (config.stopTimeoutMillis() != null) {
            server.setStopTimeout(config.stopTimeoutMillis());
        }

        if (config.handler() != null) {
            server.setHandler(config.handler());
        }
        if (config.requestLog() != null) {
            server.setRequestLog(requestLog);
        }
        if (config.sessionIdManagerFactory() != null) {
            server.setSessionIdManager(config.sessionIdManagerFactory().apply(server));
        }

        config.handlerWrappers().forEach(server::insertHandler);
        config.attrs().forEach(server::setAttribute);
        config.beans().forEach(bean -> {
            final Boolean managed = bean.isManaged();
            if (managed == null) {
                server.addBean(bean.bean());
            } else {
                server.addBean(bean.bean(), managed);
            }
        });

        config.eventListeners().forEach(server::addEventListener);
        config.lifeCycleListeners().forEach(server::addLifeCycleListener);

        config.configurators().forEach(c -> c.accept(server));

        return server;
    };

    final Consumer<Server> postStopTask = server -> {
        try {
            JettyService.logger.info("Destroying an embedded Jetty: {}", server);
            server.destroy();
        } catch (Exception e) {
            JettyService.logger.warn("Failed to destroy an embedded Jetty: {}", server, e);
        }
    };

    return new JettyService(config.hostname(), serverFactory, postStopTask);
}
 
Example 12
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();

    }

}