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

The following examples show how to use org.eclipse.jetty.server.Server#setDumpBeforeStop() . 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: WebServerTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Server start(WebServer webServer) throws Exception {

		/**
		 * 更新x_desktop的center指向
		 */
		updateCenterConfigJson();
		/**
		 * 更新 favicon.ico
		 */
		updateFavicon();
		/**
		 * 创建index.html
		 */
		createIndexPage();

		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMinThreads(WEBSERVER_THREAD_POOL_SIZE_MIN);
		threadPool.setMaxThreads(WEBSERVER_THREAD_POOL_SIZE_MAX);
		Server server = new Server(threadPool);
		if (webServer.getSslEnable()) {
			addHttpsConnector(server, webServer.getPort());
		} else {
			addHttpConnector(server, webServer.getPort());
		}
		WebAppContext context = new WebAppContext();
		context.setContextPath("/");
		context.setBaseResource(Resource.newResource(new File(Config.base(), "servers/webServer")));
		// context.setResourceBase(".");
		context.setParentLoaderPriority(true);
		context.setExtractWAR(false);
		// context.setDefaultsDescriptor(new File(Config.base(),
		// "commons/webdefault_w.xml").getAbsolutePath());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "" + webServer.getDirAllowed());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
		if (webServer.getCacheControlMaxAge() > 0) {
			context.setInitParameter("org.eclipse.jetty.servlet.Default.cacheControl",
					"max-age=" + webServer.getCacheControlMaxAge());
		}
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCacheSize", "256000000");
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCachedFileSize", "200000000");
		context.setWelcomeFiles(new String[] { "default.html", "index.html" });
		context.setGzipHandler(new GzipHandler());
		context.setParentLoaderPriority(true);
		context.getMimeTypes().addMimeMapping("wcss", "application/json");
		/* stat */
		if (webServer.getStatEnable()) {
			FilterHolder statFilterHolder = new FilterHolder(new WebStatFilter());
			statFilterHolder.setInitParameter("exclusions", webServer.getStatExclusions());
			context.addFilter(statFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
			ServletHolder statServletHolder = new ServletHolder(StatViewServlet.class);
			statServletHolder.setInitParameter("sessionStatEnable", "false");
			context.addServlet(statServletHolder, "/druid/*");
		}
		/* stat end */
		server.setHandler(context);
		server.setDumpAfterStart(false);
		server.setDumpBeforeStop(false);
		server.setStopAtShutdown(true);
		server.start();

		context.setMimeTypes(Config.mimeTypes());
		System.out.println("****************************************");
		System.out.println("* web server start completed.");
		System.out.println("* port: " + webServer.getPort() + ".");
		System.out.println("****************************************");
		return server;
	}
 
Example 2
Source File: CenterServerTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Server start(CenterServer centerServer) throws Exception {

		cleanWorkDirectory();

		HandlerList handlers = new HandlerList();

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

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

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

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

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

		server.start();
		Thread.sleep(1000);
		System.out.println("****************************************");
		System.out.println("* center server start completed.");
		System.out.println("* port: " + centerServer.getPort() + ".");
		System.out.println("****************************************");
		return server;
	}
 
Example 3
Source File: JettyLauncher.java    From JobX with Apache License 2.0 4 votes vote down vote up
@Override
public void start(boolean devMode, int port) throws Exception {

    Server server = new Server(new QueuedThreadPool(Constants.WEB_THREADPOOL_SIZE));

    WebAppContext appContext = new WebAppContext();
    String resourceBasePath = "";
    //开发者模式
    if (devMode) {
        String artifact = MavenUtils.get(Thread.currentThread().getContextClassLoader()).getArtifactId();
        resourceBasePath = artifact + "/src/main/webapp";
    }
    appContext.setDescriptor(resourceBasePath + "WEB-INF/web.xml");
    appContext.setResourceBase(resourceBasePath);
    appContext.setExtractWAR(true);

    //init param
    appContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    if (CommonUtils.isWindows()) {
        appContext.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
    }

    //for jsp support
    appContext.addBean(new JettyJspParser(appContext));
    appContext.addServlet(JettyJspServlet.class, "*.jsp");

    appContext.setContextPath("/");
    appContext.getServletContext().setExtendedListenerTypes(true);
    appContext.setParentLoaderPriority(true);
    appContext.setThrowUnavailableOnStartupException(true);
    appContext.setConfigurationDiscovered(true);
    appContext.setClassLoader(Thread.currentThread().getContextClassLoader());


    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);

    server.setConnectors(new Connector[]{connector});
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1024 * 1024 * 1024);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);
    server.setHandler(appContext);
    logger.info("[JobX] JettyLauncher starting...");
    server.start();
}
 
Example 4
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 5
Source File: JettyServer.java    From artifactory_ssh_proxy with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"resource", "boxing"})
public static Server newServer(int jettyPort, String jettyWebAppDir, JettyServiceSetting jettyServiceSetting) throws Exception {

    if (jettyPort == 0 || jettyWebAppDir == null) {
        throw new IllegalArgumentException("Jetty port and resource dir may not be empty");
    }

    // server setup
    Server server = new Server();
    server.addBean(new ScheduledExecutorScheduler());
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);


    // http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html#d0e19050
    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);


    //setup handlers according to the jetty settings
    HandlerCollection handlerCollection = new HandlerCollection();

    if (jettyServiceSetting == JettyServiceSetting.ARTIFACTORY || jettyServiceSetting == JettyServiceSetting.BOTH) {

        // The WebAppContext is the entity that controls the environment in
        // which a web application lives and breathes. In this example the
        // context path is being set to "/" so it is suitable for serving root
        // context requests and then we see it setting the location of the war.
        // A whole host of other configurations are available, ranging from
        // configuring to support annotation scanning in the webapp (through
        // PlusConfiguration) to choosing where the webapp will unpack itself.
        WebAppContext webapp = new WebAppContext();
        File warFile = new File(jettyWebAppDir + File.separator + "artifactory.war");
        webapp.setContextPath("/artifactory");
        webapp.setWar(warFile.getAbsolutePath());

        // A WebAppContext is a ContextHandler as well so it needs to be set to
        // the server so it is aware of where to send the appropriate requests.
        handlerCollection.addHandler(webapp);

    }

    if (jettyServiceSetting == JettyServiceSetting.VIP || jettyServiceSetting == JettyServiceSetting.BOTH) {

        // Serve resource files which reside in the jettyWebAppDir
        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirectoriesListed(false);
        resourceHandler.setResourceBase(jettyWebAppDir);

        handlerCollection.addHandler(resourceHandler);
    }

    server.setHandler(handlerCollection);


    // http configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSendServerVersion(true);

    // HTTP connector
    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(jettyPort);
    server.addConnector(http);

    // start server
    server.start();

    LOG.info("Started jetty server on port: {}, resource dir: {} ", jettyPort, jettyWebAppDir);
    return server;
}