org.eclipse.jetty.server.handler.gzip.GzipHandler Java Examples

The following examples show how to use org.eclipse.jetty.server.handler.gzip.GzipHandler. 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: JettyConfig.java    From nakadi with MIT License 6 votes vote down vote up
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(
        @Value("${server.port:8080}") final String port,
        @Value("${jetty.threadPool.maxThreads:200}") final String maxThreads,
        @Value("${jetty.threadPool.minThreads:8}") final String minThreads,
        @Value("${jetty.threadPool.idleTimeout:60000}") final String idleTimeout) {
    final JettyEmbeddedServletContainerFactory factory =
            new JettyEmbeddedServletContainerFactory(Integer.valueOf(port));
    factory.addServerCustomizers((JettyServerCustomizer) server -> {
        final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
        threadPool.setMaxThreads(Integer.valueOf(maxThreads));
        threadPool.setMinThreads(Integer.valueOf(minThreads));
        threadPool.setIdleTimeout(Integer.valueOf(idleTimeout));

        final GzipHandler gzipHandler = new GzipHandler();
        gzipHandler.addIncludedMethods(HttpMethod.POST.asString());
        gzipHandler.setHandler(server.getHandler());
        gzipHandler.setSyncFlush(true);
        server.setHandler(gzipHandler);
    });
    return factory;
}
 
Example #2
Source File: NodeAgent.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void customWar(String simpleName, byte[] bytes) throws Exception {
	File war = new File(Config.dir_custom(true), simpleName + ".war");
	File dir = new File(Config.dir_servers_applicationServer_work(), simpleName);
	FileUtils.writeByteArrayToFile(war, bytes, false);
	if (Servers.applicationServerIsRunning()) {
		GzipHandler gzipHandler = (GzipHandler) Servers.applicationServer.getHandler();
		HandlerList hanlderList = (HandlerList) gzipHandler.getHandler();
		for (Handler handler : hanlderList.getHandlers()) {
			if (QuickStartWebApp.class.isAssignableFrom(handler.getClass())) {
				QuickStartWebApp app = (QuickStartWebApp) handler;
				if (StringUtils.equals("/" + simpleName, app.getContextPath())) {
					app.stop();
					this.modified(bytes, war, dir);
					app.start();
				}
			}
		}
	}
}
 
Example #3
Source File: NodeAgent.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void customJar(String simpleName, byte[] bytes) throws Exception {
	File jar = new File(Config.dir_custom_jars(true), simpleName + ".jar");
	FileUtils.writeByteArrayToFile(jar, bytes, false);
	List<String> contexts = new ArrayList<>();
	for (String s : Config.dir_custom().list(new WildcardFileFilter("*.war"))) {
		contexts.add("/" + FilenameUtils.getBaseName(s));
	}
	if (Servers.applicationServerIsRunning()) {
		GzipHandler gzipHandler = (GzipHandler) Servers.applicationServer.getHandler();
		HandlerList hanlderList = (HandlerList) gzipHandler.getHandler();
		for (Handler handler : hanlderList.getHandlers()) {
			if (QuickStartWebApp.class.isAssignableFrom(handler.getClass())) {
				QuickStartWebApp app = (QuickStartWebApp) handler;
				if (contexts.contains(app.getContextPath())) {
					app.stop();
					Thread.sleep(2000);
					app.start();
				}
			}
		}
	}
}
 
Example #4
Source File: JettyWebServerConfiguration.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Customise the Jetty web server to automatically decompress requests.
 */
@Bean
public JettyServletWebServerFactory jettyServletWebServerFactory() {

    JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
    factory.addServerCustomizers(server -> {

        GzipHandler gzipHandler = new GzipHandler();
        // Enable request decompression
        gzipHandler.setInflateBufferSize(MIN_BYTES);
        gzipHandler.setHandler(server.getHandler());

        HandlerCollection handlerCollection = new HandlerCollection(gzipHandler);
        server.setHandler(handlerCollection);
    });

    return factory;
}
 
Example #5
Source File: GzipClientDriver.java    From riptide with MIT License 6 votes vote down vote up
@Override
protected Server createAndStartJetty(int port) {
    final Server jetty = new Server();
    jetty.setHandler(handler);
    final GzipHandler gzip = new GzipHandler();
    gzip.setInflateBufferSize(1024);
    jetty.insertHandler(gzip);
    final ServerConnector connector = createConnector(jetty, port);
    jetty.addConnector(connector);
    try {
        jetty.start();
    } catch (Exception e) {
        throw new ClientDriverSetupException("Error starting jetty on port " + port, e);
    }
    this.port = connector.getLocalPort();
    return jetty;
}
 
Example #6
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 #7
Source File: DremioServer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
protected void addHandlers() {
  // root handler with request logging
  final RequestLogHandler rootHandler = new RequestLogHandler();
  embeddedJetty.insertHandler(rootHandler);
  RequestLogImpl_Jetty_Fix requestLogger = new RequestLogImpl_Jetty_Fix();
  requestLogger.setResource("/logback-access.xml");
  rootHandler.setRequestLog(requestLogger);

  // gzip handler.
  final GzipHandler gzipHandler = new GzipHandler();
  // gzip handler interferes with ChunkedOutput, so exclude the job download path
  gzipHandler.addExcludedPaths("/apiv2/job/*");
  rootHandler.setHandler(gzipHandler);

  // servlet handler for everything (to manage path mapping)
  servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  servletContextHandler.setContextPath("/");
  gzipHandler.setHandler(servletContextHandler);

  // error handler
  final ErrorHandler errorHandler = new ErrorHandler();
  errorHandler.setShowStacks(true);
  errorHandler.setShowMessageInTitle(true);
  embeddedJetty.setErrorHandler(errorHandler);
}
 
Example #8
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideGzipHandler() {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setGzipHandler(new GzipHandler());
    }
  };
}
 
Example #9
Source File: Poseidon.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
private Handler getGzipHandler(Handler handler) {
    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.addIncludedMethods("GET", "POST", "PUT", "DELETE", "PATCH");
    gzipHandler.addIncludedPaths("/*");
    gzipHandler.setHandler(handler);
    return gzipHandler;
}
 
Example #10
Source File: HttpServer.java    From heroic with Apache License 2.0 5 votes vote down vote up
private HandlerCollection setupHandler() throws Exception {
    final ResourceConfig resourceConfig = setupResourceConfig();
    final ServletContainer servlet = new ServletContainer(resourceConfig);

    final ServletHolder jerseyServlet = new ServletHolder(servlet);
    // Initialize and register Jersey ServletContainer

    jerseyServlet.setInitOrder(1);

    // statically provide injector to jersey application.
    final ServletContextHandler context =
        new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");

    GzipHandler gzip = new GzipHandler();
    gzip.setIncludedMethods("POST");
    gzip.setMinGzipSize(860);
    gzip.setIncludedMimeTypes("application/json");
    context.setGzipHandler(gzip);

    context.addServlet(jerseyServlet, "/*");
    context.addFilter(new FilterHolder(new ShutdownFilter(stopping, mapper)), "/*", null);
    context.setErrorHandler(new JettyJSONErrorHandler(mapper));

    final RequestLogHandler requestLogHandler = new RequestLogHandler();

    requestLogHandler.setRequestLog(new Slf4jRequestLog());

    final RewriteHandler rewrite = new RewriteHandler();
    makeRewriteRules(rewrite);

    final HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{rewrite, context, requestLogHandler});

    return handlers;
}
 
Example #11
Source File: JettyHttpServer.java    From vespa with Apache License 2.0 5 votes vote down vote up
private GzipHandler newGzipHandler(ServerConfig serverConfig) {
    GzipHandler gzipHandler = new GzipHandlerWithVaryHeaderFixed();
    gzipHandler.setCompressionLevel(serverConfig.responseCompressionLevel());
    gzipHandler.setInflateBufferSize(8 * 1024);
    gzipHandler.setIncludedMethods("GET", "POST", "PUT", "PATCH");
    return gzipHandler;
}
 
Example #12
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Jetty context handler that can be used to expose BOSH (HTTP-Bind) functionality.
 *
 * Note that an invocation of this method will not register the handler (and thus make the related functionality
 * available to the end user). Instead, the created handler is returned by this method, and will need to be
 * registered with the embedded Jetty webserver by the caller.
 *
 * @return A Jetty context handler (never null).
 */
protected Handler createBoshHandler()
{
    final int options;
    if(isHttpCompressionEnabled()) {
        options = ServletContextHandler.SESSIONS | ServletContextHandler.GZIP;
    } else {
        options = ServletContextHandler.SESSIONS;
    }
    final ServletContextHandler context = new ServletContextHandler( null, "/http-bind", options );

    // Ensure the JSP engine is initialized correctly (in order to be able to cope with Tomcat/Jasper precompiled JSPs).
    final List<ContainerInitializer> initializers = new ArrayList<>();
    initializers.add( new ContainerInitializer( new JasperInitializer(), null ) );
    context.setAttribute( "org.eclipse.jetty.containerInitializers", initializers );
    context.setAttribute( InstanceManager.class.getName(), new SimpleInstanceManager() );

    // Generic configuration of the context.
    context.setAllowNullPathInfo( true );

    // Add the functionality-providers.
    context.addServlet( new ServletHolder( new HttpBindServlet() ), "/*" );

    // Add compression filter when needed.
    if (isHttpCompressionEnabled()) {
        final GzipHandler gzipHandler = context.getGzipHandler();
        gzipHandler.addIncludedPaths("/*");
        gzipHandler.addIncludedMethods(HttpMethod.POST.asString());
    }

    return context;
}
 
Example #13
Source File: ApplicationServer.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
static Handler wrapWithGzipHandler(RestConfig config, Handler handler) {
  if (config.getBoolean(RestConfig.ENABLE_GZIP_COMPRESSION_CONFIG)) {
    GzipHandler gzip = new GzipHandler();
    gzip.setIncludedMethods("GET", "POST");
    gzip.setHandler(handler);
    return gzip;
  }
  return handler;
}
 
Example #14
Source File: AssetsContextHandler.java    From gocd with Apache License 2.0 5 votes vote down vote up
public AssetsContextHandler(SystemEnvironment systemEnvironment) {
    super(systemEnvironment.getWebappContextPath() + "/assets");
    this.systemEnvironment = systemEnvironment;
    handler = new AssetsHandler();

    GzipHandler gzipHandler = Jetty9Server.gzipHandler();
    gzipHandler.setHandler(this.handler);
    setHandler(gzipHandler);
}
 
Example #15
Source File: ServerDaemon.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private Pair<SessionHandler,HandlerCollection> createHandlers() {
    final WebAppContext webApp = new WebAppContext();
    webApp.setContextPath(contextPath);
    webApp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

    // GZIP handler
    final GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.addIncludedMimeTypes("text/html", "text/xml", "text/css", "text/plain", "text/javascript", "application/javascript", "application/json", "application/xml");
    gzipHandler.setIncludedMethods("GET", "POST");
    gzipHandler.setCompressionLevel(9);
    gzipHandler.setHandler(webApp);

    if (Strings.isNullOrEmpty(webAppLocation)) {
        webApp.setWar(getShadedWarUrl());
    } else {
        webApp.setWar(webAppLocation);
    }

    // Request log handler
    final RequestLogHandler log = new RequestLogHandler();
    log.setRequestLog(createRequestLog());

    // Redirect root context handler_war
    MovedContextHandler rootRedirect = new MovedContextHandler();
    rootRedirect.setContextPath("/");
    rootRedirect.setNewContextURL(contextPath);
    rootRedirect.setPermanent(true);

    // Put rootRedirect at the end!
    return new Pair<>(webApp.getSessionHandler(), new HandlerCollection(log, gzipHandler, rootRedirect));
}
 
Example #16
Source File: TestServer.java    From webtau with Apache License 2.0 5 votes vote down vote up
public void start(int port) {
    server = new Server(port);

    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setHandler(new RequestHandler());

    server.setHandler(gzipHandler);
    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: JettyServerModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
private static Handler getGzipHandler(Handler wrapped) {
  GzipHandler gzip = new GzipHandler();
  gzip.addIncludedMethods(HttpMethod.POST);
  gzip.setHandler(wrapped);
  return gzip;
}
 
Example #18
Source File: FuzzerServer.java    From graphicsfuzz with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {

    FuzzerServiceImpl fuzzerService = new FuzzerServiceImpl(
        Paths.get(workingDir, processingDir).toString(),
        executorService);

    FuzzerService.Processor processor =
        new FuzzerService.Processor<FuzzerService.Iface>(fuzzerService);

    FuzzerServiceManagerImpl fuzzerServiceManager = new FuzzerServiceManagerImpl(fuzzerService,
          new PublicServerCommandDispatcher());
    FuzzerServiceManager.Processor managerProcessor =
        new FuzzerServiceManager.Processor<FuzzerServiceManager.Iface>(fuzzerServiceManager);

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

    {
      ServletHolder sh = new ServletHolder();
      sh.setServlet(new TServlet(processor, new TBinaryProtocol.Factory()));
      context.addServlet(sh, "/request");
    }
    {
      ServletHolder serveltHolderJson = new ServletHolder();
      serveltHolderJson.setServlet(new TServlet(processor, new TJSONProtocol.Factory()));
      context.addServlet(serveltHolderJson, "/requestJSON");
    }

    {
      ServletHolder shManager = new ServletHolder();
      shManager.setServlet(new TServlet(managerProcessor, new TBinaryProtocol.Factory()));
      context.addServlet(shManager, "/manageAPI");
    }

    final String staticDir = ToolPaths.getStaticDir();
    context.addServlet(
          new ServletHolder(
                new FileDownloadServlet(
                    (pathInfo, worker) -> Paths.get(staticDir, pathInfo).toFile(), staticDir)),
          "/static/*");

    HandlerList handlerList = new HandlerList();
    handlerList.addHandler(context);

    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setHandler(handlerList);

    Server server = new Server(port);

    server.setHandler(gzipHandler);
    server.start();
    server.join();
  }
 
Example #19
Source File: PHttpGzipFilter.java    From jphp with Apache License 2.0 4 votes vote down vote up
@Signature
public void __construct() {
    gzipHandler = new GzipHandler();
}
 
Example #20
Source File: JettyHttpServer.java    From vespa with Apache License 2.0 4 votes vote down vote up
private HandlerCollection getHandlerCollection(
        ServerConfig serverConfig,
        ServletPathsConfig servletPathsConfig,
        List<JDiscServerConnector> connectors,
        ServletHolder jdiscServlet,
        ComponentRegistry<ServletHolder> servletHolders,
        FilterHolder jDiscFilterInvokerFilter) {

    ServletContextHandler servletContextHandler = createServletContextHandler();

    servletHolders.allComponentsById().forEach((id, servlet) -> {
        String path = getServletPath(servletPathsConfig, id);
        servletContextHandler.addServlet(servlet, path);
        servletContextHandler.addFilter(jDiscFilterInvokerFilter, path, EnumSet.allOf(DispatcherType.class));
    });

    servletContextHandler.addServlet(jdiscServlet, "/*");

    List<ConnectorConfig> connectorConfigs = connectors.stream().map(JDiscServerConnector::connectorConfig).collect(toList());
    var secureRedirectHandler = new SecuredRedirectHandler(connectorConfigs);
    secureRedirectHandler.setHandler(servletContextHandler);

    var proxyHandler = new HealthCheckProxyHandler(connectors);
    proxyHandler.setHandler(secureRedirectHandler);

    var authEnforcer = new TlsClientAuthenticationEnforcer(connectorConfigs);
    authEnforcer.setHandler(proxyHandler);

    GzipHandler gzipHandler = newGzipHandler(serverConfig);
    gzipHandler.setHandler(authEnforcer);

    HttpResponseStatisticsCollector statisticsCollector = new HttpResponseStatisticsCollector(serverConfig.metric().monitoringHandlerPaths());
    statisticsCollector.setHandler(gzipHandler);

    StatisticsHandler statisticsHandler = newStatisticsHandler();
    statisticsHandler.setHandler(statisticsCollector);

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { statisticsHandler });
    return handlerCollection;
}
 
Example #21
Source File: JettyHandlerSupplier.java    From sumk with Apache License 2.0 4 votes vote down vote up
public static void setGzipHandlerSupplier(Supplier<GzipHandler> h) {
	JettyHandlerSupplier.gzipHandlerSupplier = Objects.requireNonNull(h);
}
 
Example #22
Source File: JettyHandlerSupplier.java    From sumk with Apache License 2.0 4 votes vote down vote up
public static Supplier<GzipHandler> gzipHandlerSupplier() {
	return gzipHandlerSupplier;
}
 
Example #23
Source File: RegistApplicationsEvent.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public void execute() throws Exception {

		if (null != Config.resource_node_applications()) {

			Applications applications = XGsonBuilder.instance().fromJson(Config.resource_node_applications(),
					Applications.class);

			List<Application> list = new ArrayList<>();

			out: for (List<Application> o : applications.values()) {
				for (Application application : o) {
					if (StringUtils.equals(Config.node(), application.getNode())) {
						list.add(application);
						continue out;
					}
				}
			}

			if (Servers.applicationServerIsRunning()) {
				List<String> contextPaths = ListTools.extractProperty(list, "contextPath", String.class, true, true);
				List<String> removes = new ArrayList<>();
				GzipHandler gzipHandler = (GzipHandler) Servers.applicationServer.getHandler();
				HandlerList hanlderList = (HandlerList) gzipHandler.getHandler();
				for (Handler handler : hanlderList.getHandlers()) {
					if (QuickStartWebApp.class.isAssignableFrom(handler.getClass())) {
						QuickStartWebApp app = (QuickStartWebApp) handler;
						if (!contextPaths.contains(app.getContextPath())) {
							removes.add(app.getContextPath());
						}
					}
				}
				if (!removes.isEmpty()) {
					list = list.stream().filter(o -> {
						return !removes.contains(o.getContextPath());
					}).collect(Collectors.toList());
				}
			}

			Req req = new Req();

			req.setValue(XGsonBuilder.toJson(list));

			for (Entry<String, CenterServer> entry : Config.nodes().centerServers().orderedEntry()) {
				CipherConnectionAction.put(false,
						Config.url_x_program_center_jaxrs(entry, "center", "regist", "applications"), req);

			}

			Config.resource_node_eventQueue().put(XGsonBuilder.instance().toJsonTree(new UpdateApplicationsEvent()));
		}

	}
 
Example #24
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 #25
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 #26
Source File: FuzzerServer.java    From graphicsfuzz with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {

    FuzzerServiceImpl fuzzerService = new FuzzerServiceImpl(
        Paths.get(workingDir, processingDir).toString(),
        executorService);

    FuzzerService.Processor processor =
        new FuzzerService.Processor<FuzzerService.Iface>(fuzzerService);

    FuzzerServiceManagerImpl fuzzerServiceManager = new FuzzerServiceManagerImpl(fuzzerService,
          new GraphicsFuzzServerCommandDispatcher());
    FuzzerServiceManager.Processor managerProcessor =
        new FuzzerServiceManager.Processor<FuzzerServiceManager.Iface>(fuzzerServiceManager);

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

    {
      ServletHolder sh = new ServletHolder();
      sh.setServlet(new TServlet(processor, new TBinaryProtocol.Factory()));
      context.addServlet(sh, "/request");
    }
    {
      ServletHolder serveltHolderJson = new ServletHolder();
      serveltHolderJson.setServlet(new TServlet(processor, new TJSONProtocol.Factory()));
      context.addServlet(serveltHolderJson, "/requestJSON");
    }

    {
      ServletHolder shManager = new ServletHolder();
      shManager.setServlet(new TServlet(managerProcessor, new TBinaryProtocol.Factory()));
      context.addServlet(shManager, "/manageAPI");
    }

    context.addServlet(new ServletHolder(new WebUi(fuzzerServiceManager, fileOps)), "/webui/*");

    final String staticDir = ToolPaths.getStaticDir();
    context.addServlet(
        new ServletHolder(
            new FileDownloadServlet(
                (pathInfo, workerName) -> Paths.get(staticDir, pathInfo).toFile(), staticDir)),
        "/static/*");

    HandlerList handlerList = new HandlerList();
    handlerList.addHandler(context);

    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setHandler(handlerList);

    Server server = new Server(port);

    server.setHandler(gzipHandler);
    server.start();
    server.join();
  }