@Bean public EmbeddedServletContainerFactory jettyConfigBean() { DynamicPropertyFactory propertyFactory = DynamicPropertyFactory.getInstance(); String accessLogFilePath = propertyFactory.getStringProperty("server.accessLog.config.file", ACCESS_LOG_FILE_PATH).getValue(); JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory = new JettyEmbeddedServletContainerFactory(); jettyEmbeddedServletContainerFactory.addServerCustomizers(new org.springframework.boot.context.embedded.jetty.JettyServerCustomizer() { public void customize(Server server) { HandlerCollection handlers = new HandlerCollection(); for (Handler handler : server.getHandlers()) { handlers.addHandler(handler); } RequestLogHandler requestLogHandler = new RequestLogHandler(); RequestLogImpl requestLogImpl = new RequestLogImpl(); requestLogImpl.setFileName(accessLogFilePath); requestLogHandler.setRequestLog(requestLogImpl); handlers.addHandler(requestLogHandler); server.setHandler(handlers); LOGGER.info("Jetty Server Customized. Access Log Configuration File - {}", accessLogFilePath); } }); return jettyEmbeddedServletContainerFactory; }
public void start() throws Exception { RequestLogHandler requestLogHandler = new RequestLogHandler(); Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone(TimeZone.getDefault().getID()); requestLog.setLogLatency(true); requestLogHandler.setRequestLog(requestLog); handlers.add(0, new ContextHandlerCollection()); handlers.add(requestLogHandler); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(handlers.toArray(new Handler[handlers.size()])); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); server.setHandler(handlerCollection); server.start(); log.info("Server started at end point {}", getServiceUri()); }
public void start() throws PulsarServerException { log.info("Starting web socket proxy at port {}", conf.getWebServicePort()); try { RequestLogHandler requestLogHandler = new RequestLogHandler(); Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone(TimeZone.getDefault().getID()); requestLog.setLogLatency(true); requestLogHandler.setRequestLog(requestLog); handlers.add(0, new ContextHandlerCollection()); handlers.add(requestLogHandler); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(handlers.toArray(new Handler[handlers.size()])); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); server.setHandler(handlerCollection); server.start(); } catch (Exception e) { throw new PulsarServerException(e); } }
public void start() throws PulsarServerException { try { RequestLogHandler requestLogHandler = new RequestLogHandler(); Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setExtended(true); requestLog.setLogTimeZone(TimeZone.getDefault().getID()); requestLog.setLogLatency(true); requestLogHandler.setRequestLog(requestLog); handlers.add(0, new ContextHandlerCollection()); handlers.add(requestLogHandler); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.setHandlers(handlers.toArray(new Handler[handlers.size()])); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); server.setHandler(handlerCollection); server.start(); log.info("Web Service started at {}", pulsar.getWebServiceAddress()); } catch (Exception e) { throw new PulsarServerException(e); } }
public void start() throws Exception { server = new Server(); Connector connector = new SelectChannelConnector(); connector.setPort(port); server.setConnectors(new Connector[]{connector}); RequestLogHandler requestLogHandler = new RequestLogHandler(); configureRequestLogImpl(); requestLogHandler.setRequestLog(requestLogImpl); HandlerList handlers = new HandlerList(); handlers.addHandler(requestLogHandler); handlers.addHandler(getRequestHandler()); server.setHandler(handlers); server.start(); }
@Override public void customizeServer(Server server) { if(logFile != null) { HandlerCollection rootHandler = (HandlerCollection) server.getHandler(); List<Handler> handlers = new ArrayList<Handler>(); handlers.addAll(Arrays.asList(rootHandler.getHandlers())); RequestLogHandler requestLogHandler = new RequestLogHandler(); NCSARequestLog requestLog = new NCSARequestLog(logFile.getAbsolutePath()); requestLog.setRetainDays(0); requestLog.setAppend(true); requestLog.setExtended(extended); requestLog.setLogTimeZone("GMT"); requestLogHandler.setRequestLog(requestLog); handlers.add(requestLogHandler); rootHandler.setHandlers(handlers.toArray(new Handler[handlers.size()])); } }
private static RequestLogHandler setRequestLogHandler() { ConfigureAdaptor conf = ConfigureManager.getConfigure(); NCSARequestLog requestLog = new NCSARequestLog(); requestLog.setFilename("./logs/http-request-yyyy_mm_dd.log"); requestLog.setFilenameDateFormat("yyyy_MM_dd"); requestLog.setRetainDays(conf.getLogKeepDays()); requestLog.setAppend(true); requestLog.setExtended(true); requestLog.setLogCookies(false); requestLog.setLogTimeZone(TimeZone.getDefault().getID()); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); return requestLogHandler; }
private static HandlerCollection createHandlers( final GatewayConfig config, final GatewayServices services, final ContextHandlerCollection contexts) { HandlerCollection handlers = new HandlerCollection(); RequestLogHandler logHandler = new RequestLogHandler(); logHandler.setRequestLog(new AccessHandler()); TraceHandler traceHandler = new TraceHandler(); traceHandler.setHandler(contexts); traceHandler.setTracedBodyFilter(System.getProperty("org.apache.knox.gateway.trace.body.status.filter")); CorrelationHandler correlationHandler = new CorrelationHandler(); correlationHandler.setHandler(traceHandler); DefaultTopologyHandler defaultTopoHandler = new DefaultTopologyHandler(config, services, contexts); handlers.setHandlers(new Handler[]{correlationHandler, defaultTopoHandler, logHandler}); return handlers; }
@Override void customizeJetty(JettyEmbeddedServletContainerFactory container) { container.addServerCustomizers(server -> { RequestLogHandler requestLogsHandler = new RequestLogHandler(); requestLogsHandler.setServer(server); Slf4jRequestLog log = new Slf4jRequestLog(); requestLogsHandler.setRequestLog(log); HandlerCollection handlers = new HandlerCollection(server.getHandlers()); handlers.prependHandler(requestLogsHandler); server.setHandler(handlers); }); }
@Test public void test_embeddedServer_withHandlerChain() throws Exception { AtomicLong logCount = new AtomicLong(0); RequestLog requestLog = (request, response) -> logCount.incrementAndGet(); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); StatisticsHandler handlerChain = new StatisticsHandler(); handlerChain.setHandler(requestLogHandler); Javalin app = Javalin.create() .port(0) .embeddedServer(new EmbeddedJettyFactory(() -> { Server server = new Server(); server.setHandler(handlerChain); return server; })) .get("/", ctx -> ctx.result("Hello World")) .start(); String origin = "http://localhost:" + app.port(); int requests = 10; for (int i = 0; i < requests; i++) { assertThat(Unirest.get(origin + "/").asString().getBody(), is("Hello World")); assertThat(Unirest.get(origin + "/not_there").asString().getStatus(), is(404)); } assertThat(handlerChain.getDispatched(), is(requests * 2)); assertThat(handlerChain.getResponses2xx(), is(requests)); assertThat(handlerChain.getResponses4xx(), is(requests)); assertThat(logCount.get(), is((long) (requests * 2))); app.stop(); }
private HandlerCollection getHandlerCollection( ServerConfig serverConfig, ServletPathsConfig servletPathsConfig, ServletHolder jdiscServlet, ComponentRegistry<ServletHolder> servletHolders, FilterHolder jDiscFilterInvokerFilter, RequestLog requestLog) { 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, "/*"); GzipHandler gzipHandler = newGzipHandler(serverConfig); gzipHandler.setHandler(servletContextHandler); StatisticsHandler statisticsHandler = newStatisticsHandler(); statisticsHandler.setHandler(gzipHandler); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[]{statisticsHandler, requestLogHandler}); return handlerCollection; }
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; }
@Override public HandlerCollection apply(Environment environment) { HandlerCollection handlers = new HandlerCollection(); List<RequestLogHandler> requestLogHandlers = createRequestLogHandlers(environment); Collection<ServletContextHandler> servletContextHandlers = createServletContexts(environment); Collection<ContextHandler> contextHandlers = createContextHandlers(environment); ContextHandlerCollection contexts = new ContextHandlerCollection(); addContextHandlers(contexts, servletContextHandlers); addContextHandlers(contexts, contextHandlers); if (contexts.getHandlers() != null && contexts.getHandlers().length > 0) { handlers.addHandler(contexts); } // Shutdown Handler of Jetty ShutdownHandler shutdownHandler = createShutdownHandler(environment); if (shutdownHandler != null) { handlers.addHandler(shutdownHandler); } // Log handlers are created the first but processed the // last. In case there is an access log handler, the HTTP // response codes should be correct. addHandlers(handlers, requestLogHandlers); return handlers; }
@Override public List<RequestLogHandler> apply(Environment environment) { Iterable<RequestLogHandlerFactory> loader = loadFactories(); List<RequestLogHandler> handlers = new ArrayList<>(); for (RequestLogHandlerFactory factory : loader) { RequestLogHandler requestLogHandler = createRequestLogHandler(factory, environment); if (requestLogHandler != null) { handlers.add(requestLogHandler); } } return handlers; }
public static void main(String[] args) throws Exception { WebAppMain.standAloneMode = true; Logo.print(true); initializeLogDir(); final ConfigureAdaptor conf = ConfigureManager.getConfigure(); connectScouterCollector(); final Server server = new Server(conf.getNetHttpPort()); HandlerCollection handlers = new HandlerCollection(); RequestLogHandler requestLogHandler = setRequestLogHandler(); handlers.addHandler(requestLogHandler); ServletContextHandler servletContextHandler = setWebAppContext(); handlers.addHandler(servletContextHandler); server.setHandler(handlers); try { server.start(); waitOnExit(server); } catch (Exception e) { e.printStackTrace(); } }
private Handler getRequestLogHandler(Handler handler) { RequestLog requestLog = new Log4JAccessLog(configuration.getAccessLogConfigFilePath(), () -> configuration.isAccessLogEnabled()); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); requestLogHandler.setHandler(handler); return requestLogHandler; }
/** * Wraps the Jetty handler. * * @param server the Jetty server. */ private void wrapJettyHandler(Server server) { LogbackAccessJettyRequestLog requestLog = new LogbackAccessJettyRequestLog( logbackAccessProperties, environment, applicationEventPublisher); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setHandler(server.getHandler()); requestLogHandler.setRequestLog(requestLog); server.setHandler(requestLogHandler); }
/** * Start the server with a http port and optional javamelody parameters. * @param port Http port * @param parameters Optional javamelody parameters * @throws Exception e */ public static void start(int port, Map<Parameter, String> parameters) throws Exception { // Init jetty final Server server = new Server(port); final ContextHandlerCollection contexts = new ContextHandlerCollection(); final ServletContextHandler context = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS); final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter(); monitoringFilter.setApplicationType("Standalone"); final FilterHolder filterHolder = new FilterHolder(monitoringFilter); if (parameters != null) { for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) { final net.bull.javamelody.Parameter parameter = entry.getKey(); final String value = entry.getValue(); filterHolder.setInitParameter(parameter.getCode(), value); } } context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST)); final RequestLogHandler requestLogHandler = new RequestLogHandler(); contexts.addHandler(requestLogHandler); final HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] { contexts }); server.setHandler(handlers); server.start(); }
public static void main(String[] args) throws Exception { // Create a basic jetty server object that will listen on port 8080. Note that if you set this to port 0 // then a randomly available port will be assigned that you can either look in the logs for the port, // or programmatically obtain it for use in test cases. Server server = new Server(8080); HandlerCollection handlers = new HandlerCollection(); server.setHandler(handlers); ServletHandler servlet = new ServletHandler(); servlet.addServletWithMapping(HelloServlet.class, "/*"); handlers.addHandler(servlet); handlers.addHandler(new DefaultHandler()); // must be after servlet it seems // log using NCSA (common log format) // http://en.wikipedia.org/wiki/Common_Log_Format NCSARequestLog requestLog = new NCSARequestLog(); requestLog.setFilename("/tmp/yyyy_mm_dd.request.log"); requestLog.setFilenameDateFormat("yyyy_MM_dd"); requestLog.setRetainDays(90); requestLog.setAppend(true); requestLog.setExtended(true); requestLog.setLogCookies(false); requestLog.setLogTimeZone("GMT"); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); handlers.addHandler(requestLogHandler); // Start things up! By using the server.join() the server thread will join with the current thread. // See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details. server.start(); server.join(); }
@Provides @Singleton @Inject protected HandlerCollection providesHandlerCollection(ServletContextHandler servletContextHandler, RequestLogHandler requestLogHandler) { HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.setHandlers(new Handler[]{servletContextHandler, requestLogHandler}); return handlerCollection; }
@Provides @Singleton @Inject protected RequestLogHandler providesRequestLogHandler(RequestLog requestLog) { RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); return requestLogHandler; }
public WebServer(@NotNull SharedContext context, @Nullable Server server, @NotNull WebServerConfig config, @NotNull EncryptionFactory tokenFactory) { this.context = context; this.server = server; this.config = config; this.tokenFactory = tokenFactory; if (server != null) { final ServletContextHandler contextHandler = new ServletContextHandler(); contextHandler.setContextPath("/"); handler = contextHandler.getServletHandler(); //final ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); //securityHandler.addConstraintMapping(new ); //contextHandler.setSecurityHandler(securityHandler); final RequestLogHandler logHandler = new RequestLogHandler(); logHandler.setRequestLog(new RequestLog() { @Override public void log(Request request, Response response) { final User user = (User) request.getAttribute(User.class.getName()); final String userName = (user == null || user.isAnonymous()) ? "" : user.getUserName(); log.info("{}:{} - {} - \"{} {}\" {} {}", request.getRemoteHost(), request.getRemotePort(), userName, request.getMethod(), request.getHttpURI(), response.getStatus(), response.getReason()); } }); final HandlerCollection handlers = new HandlerCollection(); handlers.addHandler(contextHandler); handlers.addHandler(logHandler); server.setHandler(handlers); } else { handler = null; } }
private HandlerCollection createHandlers() { final WebAppContext webApp = new WebAppContext(); webApp.setContextPath(contextPath); webApp.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false"); webApp.getSessionHandler().setMaxInactiveInterval(sessionTimeout * 60); // 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 MovedContextHandler rootRedirect = new MovedContextHandler(); rootRedirect.setContextPath("/"); rootRedirect.setNewContextURL(contextPath); rootRedirect.setPermanent(true); // Put rootRedirect at the end! return new HandlerCollection(log, gzipHandler, rootRedirect); }
@Override public void start(FolderContext music, MountContext mount, int port, String user, String password) throws Exception { ServletContextHandler mountContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); mountContext.setContextPath(mount.getPath()); mountContext.setSecurityHandler(user == null ? null : basicAuthentication("MusicMount", user, password)); ServletHolder mountServlet = new ServletHolder(mount.getServlet()); mountContext.addServlet(mountServlet, "/*"); ServletContextHandler musicContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); musicContext.setContextPath(music.getPath()); musicContext.setSecurityHandler(user == null ? null : basicAuthentication("MusicMount", user, password)); musicContext.setBaseResource(Resource.newResource(music.getFolder())); MimeTypes musicTypes = new MimeTypes(); musicTypes.addMimeMapping("m4a", "audio/mp4"); musicTypes.addMimeMapping("mp3", "audio/mpeg"); musicContext.setMimeTypes(musicTypes); ServletHolder musicServlet = new ServletHolder(new DefaultServlet()); musicServlet.setInitParameter("dirAllowed", "false"); musicContext.addServlet(musicServlet, "/*"); GzipHandler gzipMountContext = new GzipHandler(); gzipMountContext.setMimeTypes(MimeTypes.TEXT_JSON); gzipMountContext.setHandler(mountContext); ContextHandlerCollection contexHandlers = new ContextHandlerCollection(); contexHandlers.setHandlers(new Handler[] { gzipMountContext, musicContext }); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(new ConsoleRequestLog()); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[]{ contexHandlers, new DefaultHandler(), requestLogHandler }); server = new Server(port); server.setHandler(handlers); server.setGracefulShutdown(1000); server.setStopAtShutdown(true); server.start(); }
public Handler configure() { final Logger logger = (Logger) LoggerFactory.getLogger("http.request"); logger.setAdditive(false); final LoggerContext context = logger.getLoggerContext(); final AppenderAttachableImpl<ILoggingEvent> appenders = new AppenderAttachableImpl<ILoggingEvent>(); final RequestLogLayout layout = new RequestLogLayout(); layout.start(); for (OutputStreamAppender<ILoggingEvent> appender : LogbackFactory.buildAppenders(config.getRequestLogConfiguration(), context)) { appender.stop(); appender.setLayout(layout); appender.start(); appenders.addAppender(appender); } final RequestLogHandler handler = new RequestLogHandler(); handler.setRequestLog(new AsyncRequestLog(Clock.defaultClock(), appenders, config.getRequestLogConfiguration().getTimeZone(), config.getRequestLogConfiguration().getCookies())); return handler; }
public void start(Herder herder) { log.info("Starting REST server"); ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig.register(new JacksonJsonProvider()); resourceConfig.register(RootResource.class); resourceConfig.register(new ConnectorsResource(herder)); resourceConfig.register(new ConnectorPluginsResource(herder)); resourceConfig.register(ConnectExceptionMapper.class); ServletContainer servletContainer = new ServletContainer(resourceConfig); ServletHolder servletHolder = new ServletHolder(servletContainer); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(servletHolder, "/*"); String allowedOrigins = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG); if (allowedOrigins != null && !allowedOrigins.trim().isEmpty()) { FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter()); filterHolder.setName("cross-origin"); filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins); String allowedMethods = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_METHODS_CONFIG); if (allowedMethods != null && !allowedOrigins.trim().isEmpty()) { filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods); } context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST)); } RequestLogHandler requestLogHandler = new RequestLogHandler(); Slf4jRequestLog requestLog = new Slf4jRequestLog(); requestLog.setLoggerName(RestServer.class.getCanonicalName()); requestLog.setLogLatency(true); requestLogHandler.setRequestLog(requestLog); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[]{context, new DefaultHandler(), requestLogHandler}); /* Needed for graceful shutdown as per `setStopTimeout` documentation */ StatisticsHandler statsHandler = new StatisticsHandler(); statsHandler.setHandler(handlers); jettyServer.setHandler(statsHandler); jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS); jettyServer.setStopAtShutdown(true); try { jettyServer.start(); } catch (Exception e) { throw new ConnectException("Unable to start REST server", e); } log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl()); }
private RequestLogHandler requestLog(Handler handler) { RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(new Slf4jRequestLog()); requestLogHandler.setHandler(handler); return requestLogHandler; }
@Inject JettyServer( @GerritServerConfig Config cfg, ThreadSettingsConfig threadSettingsConfig, SitePaths site, JettyEnv env, HttpLogFactory httpLogFactory) { this.site = site; httpd = new Server(threadPool(cfg, threadSettingsConfig)); httpd.setConnectors(listen(httpd, cfg)); Handler app = makeContext(env, cfg); if (cfg.getBoolean("httpd", "requestLog", !reverseProxy)) { RequestLogHandler handler = new RequestLogHandler(); handler.setRequestLog(httpLogFactory.get()); handler.setHandler(app); app = handler; } if (cfg.getBoolean("httpd", "registerMBeans", false)) { MBeanContainer mbean = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); httpd.addEventListener(mbean); httpd.addBean(Log.getRootLogger()); httpd.addBean(mbean); } httpd.setHandler(app); httpd.setStopAtShutdown(false); }
private void initializeWebServer(String name, String hostName, Configuration conf, String[] pathSpecs) throws FileNotFoundException, IOException { Preconditions.checkNotNull(webAppContext); HandlerCollection handlerCollection = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLog requestLog = HttpRequestLog.getRequestLog(name); if (requestLog != null) { RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); handlerCollection.addHandler(requestLogHandler); } final String appDir = getWebAppsPath(name); handlerCollection.addHandler(contexts); handlerCollection.addHandler(webAppContext); webServer.setHandler(handlerCollection); addDefaultApps(contexts, appDir, conf); addGlobalFilter("safety", QuotingInputFilter.class.getName(), null); Map<String, String> params = new HashMap<>(); params.put("xframeoptions", conf.get("hbase.http.filter.xframeoptions.mode", "DENY")); addGlobalFilter("clickjackingprevention", ClickjackingPreventionFilter.class.getName(), params); final FilterInitializer[] initializers = getFilterInitializers(conf); if (initializers != null) { conf = new Configuration(conf); conf.set(BIND_ADDRESS, hostName); for (FilterInitializer c : initializers) { c.initFilter(this, conf); } } addDefaultServlets(); if (pathSpecs != null) { for (String path : pathSpecs) { LOG.info("adding path spec: " + path); addFilterPathMapping(path, webAppContext); } } }
public static Server create(HttpConfiguration configuration) throws Exception { Server server = new Server(); SelectChannelConnector connector = new InstrumentedSelectChannelConnector(configuration.listenAddress.getPort()); connector.setHost(configuration.listenAddress.getHostName()); QueuedThreadPool queuedThreadPool = new InstrumentedQueuedThreadPool(); queuedThreadPool.setMaxThreads(configuration.numHttpWorkers); connector.setThreadPool(queuedThreadPool); queuedThreadPool.start(); server.setConnectors(new Connector[]{connector}); server.setSendServerVersion(true); server.setSendDateHeader(true); server.setStopAtShutdown(true); server.setGracefulShutdown((int) TimeUnit.SECONDS.toMillis(5)); ServletContextHandler root = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); root.setContextPath("/"); server.setHandler(new InstrumentedHandler(root)); // Jersey root.addServlet(buildJerseyServlet(), "/*"); NCSARequestLog requestLog = new NCSARequestLog(configuration.httpLogFileName); requestLog.setRetainDays(90); requestLog.setAppend(true); requestLog.setExtended(true); requestLog.setLogTimeZone("GMT"); requestLog.setLogLatency(true); requestLog.setLogDispatch(true); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); root.setHandler(requestLogHandler); connector.setStatsOn(true); StatisticsHandler statisticsHandler = new StatisticsHandler(); statisticsHandler.setServer(server); requestLogHandler.setHandler(statisticsHandler); // Setup JMX MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); server.getContainer().addEventListener(mbContainer); mbContainer.addBean(statisticsHandler); return server; }
/** * @return Jetty config bean */ @Bean public EmbeddedServletContainerFactory jettyConfigBean() { JettyEmbeddedServletContainerFactory jef = new JettyEmbeddedServletContainerFactory(); jef.addServerCustomizers(new JettyServerCustomizer() { public void customize(Server server) { if (Config.getConfigBoolean("access_log_enabled", true)) { // enable access log via Logback HandlerCollection handlers = new HandlerCollection(); for (Handler handler : server.getHandlers()) { handlers.addHandler(handler); } RequestLogHandler reqLogs = new RequestLogHandler(); reqLogs.setServer(server); RequestLogImpl rli = new RequestLogImpl(); rli.setResource("/logback-access.xml"); rli.setQuiet(true); rli.start(); reqLogs.setRequestLog(rli); handlers.addHandler(reqLogs); server.setHandler(handlers); } for (Connector y : server.getConnectors()) { for (ConnectionFactory cf : y.getConnectionFactories()) { if (cf instanceof HttpConnectionFactory) { HttpConnectionFactory dcf = (HttpConnectionFactory) cf; // support for X-Forwarded-Proto // redirect back to https if original request uses it if (Config.IN_PRODUCTION) { HttpConfiguration httpConfiguration = dcf.getHttpConfiguration(); httpConfiguration.addCustomizer(new ForwardedRequestCustomizer()); } // Disable Jetty version header dcf.getHttpConfiguration().setSendServerVersion(false); } } } } }); int defaultPort = NumberUtils.toInt(System.getProperty("jetty.http.port", "8080")); jef.setPort(NumberUtils.toInt(System.getProperty("server.port"), defaultPort)); logger.info("Listening on port {}...", jef.getPort()); return jef; }
@Override public void start(FolderContext music, FolderContext mount, int port, String user, String password) throws Exception { ServletContextHandler mountContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); mountContext.setContextPath(mount.getPath()); mountContext.setSecurityHandler(user == null ? null : basicAuthentication("MusicMount", user, password)); mountContext.setBaseResource(Resource.newResource(mount.getFolder())); mountContext.setWelcomeFiles(new String[] { "index.json" }); MimeTypes mountTypes = new MimeTypes(); mountTypes.addMimeMapping("json", MimeTypes.TEXT_JSON_UTF_8); mountContext.setMimeTypes(mountTypes); ServletHolder mountServlet = new ServletHolder(new DefaultServlet()); mountServlet.setInitParameter("dirAllowed", "false"); mountContext.addServlet(mountServlet, "/*"); ServletContextHandler musicContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); musicContext.setContextPath(music.getPath()); musicContext.setSecurityHandler(user == null ? null : basicAuthentication("MusicMount", user, password)); musicContext.setBaseResource(Resource.newResource(music.getFolder())); MimeTypes musicTypes = new MimeTypes(); musicTypes.addMimeMapping("m4a", "audio/mp4"); musicTypes.addMimeMapping("mp3", "audio/mpeg"); musicContext.setMimeTypes(musicTypes); ServletHolder musicServlet = new ServletHolder(new DefaultServlet()); musicServlet.setInitParameter("dirAllowed", "false"); musicContext.addServlet(musicServlet, "/*"); GzipHandler gzipMountContext = new GzipHandler(); gzipMountContext.setMimeTypes(MimeTypes.TEXT_JSON); gzipMountContext.setHandler(mountContext); ContextHandlerCollection contexHandlers = new ContextHandlerCollection(); contexHandlers.setHandlers(new Handler[] { gzipMountContext, musicContext }); RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(new ConsoleRequestLog()); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[]{ contexHandlers, new DefaultHandler(), requestLogHandler }); server = new Server(port); server.setHandler(handlers); server.setGracefulShutdown(1000); server.setStopAtShutdown(true); server.start(); }
public void run() { Runtime.getRuntime().addShutdownHook(new ShutdownHook()); final AppConfig config = AppConfig.getInstance(); final int listenerthreads = config.getInt("server.listenerthreads", 2); final org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(); final SelectChannelConnector connector = new SelectChannelConnector(); final QueuedThreadPool qtp = new QueuedThreadPool(); qtp.setName("JettyWorkerPool"); qtp.setMinThreads(5); qtp.setMaxThreads(config.getInt("server.worker", 20)); connector.setThreadPool(qtp); connector.setHost(config.getString("server.bind", "0.0.0.0")); connector.setPort(config.getInt("server.port", 8080)); connector.setMaxIdleTime(120000); connector.setLowResourcesMaxIdleTime(60000); connector.setLowResourcesConnections(20000); connector.setAcceptQueueSize(5000); connector.setName("pushrouter"); server.setConnectors(new Connector[]{(Connector) connector}); final ServletContextHandler schandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); schandler.setContextPath("/"); final ServletHolder cholder = schandler.addServlet("net.zyclonite.pushrouter.StreamServlet", "/stream/*"); cholder.setInitParameter("listenerthreads", String.valueOf(listenerthreads)); cholder.setAsyncSupported(true); final RequestLogHandler requestLogHandler = new RequestLogHandler(); if (config.getBoolean("server.accesslogs", false)) { final NCSARequestLog requestLog = new NCSARequestLog(config.getString("server.logdir", "./") + "web-yyyy_mm_dd.request.log"); requestLog.setRetainDays(90); requestLog.setAppend(true); requestLog.setExtended(false); requestLog.setLogTimeZone("GMT"); requestLogHandler.setRequestLog(requestLog); } final HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[]{schandler, new DefaultHandler(), requestLogHandler}); server.setHandler(handlers); try { server.start(); LOG.info("PushRouter started"); } catch (Exception ex) { LOG.error("PushRouter could not be started"); } }
/** * See {@link RequestLogHandlerFactoryLoader}. * * @param environment the environment * @return the {@link List} of loaded * {@link RequestLogHandler}s */ protected List<RequestLogHandler> createRequestLogHandlers(Environment environment) { RequestLogHandlerFactoryLoader rlhfl = new RequestLogHandlerFactoryLoader(); return rlhfl.apply(environment); }
/** * Creates an instance {@link RequestLogHandler} using the * provided environment. * * @param environment the environment of the embedded server * @return an instance of {@link RequestLogHandler} or * <code>null</code> if no request log handler can be * created. */ RequestLogHandler createRequestLogHandler(Environment environment);
/** * See {@link RequestLogHandlerFactory}. * * @param factory the request log handler factory * @param environment the environment * @return an instance of {@link RequestLogHandler} */ protected RequestLogHandler createRequestLogHandler(RequestLogHandlerFactory factory, Environment environment) { return factory.createRequestLogHandler(environment); }