JettyServiceConfig(String hostname, Boolean dumpAfterStart, Boolean dumpBeforeStop, Long stopTimeoutMillis, Handler handler, RequestLog requestLog, Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory, Map<String, Object> attrs, List<Bean> beans, List<HandlerWrapper> handlerWrappers, List<Listener> eventListeners, List<LifeCycle.Listener> lifeCycleListeners, List<Consumer<? super Server>> configurators) { this.hostname = hostname; this.dumpAfterStart = dumpAfterStart; this.dumpBeforeStop = dumpBeforeStop; this.stopTimeoutMillis = stopTimeoutMillis; this.handler = handler; this.requestLog = requestLog; this.sessionIdManagerFactory = sessionIdManagerFactory; this.attrs = Collections.unmodifiableMap(attrs); this.beans = Collections.unmodifiableList(beans); this.handlerWrappers = Collections.unmodifiableList(handlerWrappers); this.eventListeners = Collections.unmodifiableList(eventListeners); this.lifeCycleListeners = Collections.unmodifiableList(lifeCycleListeners); this.configurators = Collections.unmodifiableList(configurators); }
static String toString( Object holder, String hostname, Boolean dumpAfterStart, Boolean dumpBeforeStop, Long stopTimeout, Handler handler, RequestLog requestLog, Function<? super Server, ? extends SessionIdManager> sessionIdManagerFactory, Map<String, Object> attrs, List<Bean> beans, List<HandlerWrapper> handlerWrappers, List<Listener> eventListeners, List<LifeCycle.Listener> lifeCycleListeners, List<Consumer<? super Server>> configurators) { return MoreObjects.toStringHelper(holder) .add("hostname", hostname) .add("dumpAfterStart", dumpAfterStart) .add("dumpBeforeStop", dumpBeforeStop) .add("stopTimeoutMillis", stopTimeout) .add("handler", handler) .add("requestLog", requestLog) .add("sessionIdManagerFactory", sessionIdManagerFactory) .add("attrs", attrs) .add("beans", beans) .add("handlerWrappers", handlerWrappers) .add("eventListeners", eventListeners) .add("lifeCycleListeners", lifeCycleListeners) .add("configurators", configurators) .toString(); }
@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; }
@Provides @Singleton @Inject protected RequestLogHandler providesRequestLogHandler(RequestLog requestLog) { RequestLogHandler requestLogHandler = new RequestLogHandler(); requestLogHandler.setRequestLog(requestLog); return requestLogHandler; }
@Test public void testAppenderDefined() { HttpRequestLogAppender requestLogAppender = new HttpRequestLogAppender(); requestLogAppender.setName("testrequestlog"); Logger.getLogger("http.requests.test").addAppender(requestLogAppender); RequestLog requestLog = HttpRequestLog.getRequestLog("test"); Logger.getLogger("http.requests.test").removeAppender(requestLogAppender); assertNotNull("RequestLog should not be null", requestLog); assertEquals("Class mismatch", NCSARequestLog.class, requestLog.getClass()); }
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 RequestLog createRequestLog() { final NCSARequestLog log = new NCSARequestLog(); final File logPath = new File(accessLogFile); final File parentFile = logPath.getParentFile(); if (parentFile != null) { parentFile.mkdirs(); } log.setFilename(logPath.getPath()); log.setAppend(true); log.setLogTimeZone("GMT"); log.setLogLatency(true); return log; }
@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 OsgiFramework osgiFramework, 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(); setupJmx(server, serverConfig); ((QueuedThreadPool)server.getThreadPool()).setMaxThreads(serverConfig.maxWorkerThreads()); for (ConnectorFactory connectorFactory : connectorFactories.allComponents()) { ServerSocketChannel preBoundChannel = getChannelFromServiceLayer(connectorFactory.getConnectorConfig().listenPort(), osgiFramework.bundleContext()); server.addConnector(connectorFactory.createConnector(metric, server, preBoundChannel)); listenedPorts.add(connectorFactory.getConnectorConfig().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)); RequestLog requestLog = new AccessLogRequestLog(accessLog); server.setHandler( getHandlerCollection( serverConfig, servletPathsConfig, jdiscServlet, servletHolders, jDiscFilterInvokerFilter, requestLog)); 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); }
Optional<RequestLog> requestLog() { return Optional.ofNullable(requestLog); }
@Override protected void configure() { bind(HttpService.class); bind(RequestLog.class).to(HttpServerRequestLog.class); }
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 RequestLog getRequestLog(String name) { String lookup = serverToComponent.get(name); if (lookup != null) { name = lookup; } String loggerName = "http.requests." + name; String appenderName = name + "requestlog"; org.apache.log4j.Logger httpLogger = getLog4jLogger(loggerName); if (httpLogger == null) { LOG.warn("Jetty request log can only be enabled using Log4j"); return null; } Appender appender = null; try { appender = httpLogger.getAppender(appenderName); } catch (LogConfigurationException e) { LOG.warn("Http request log for " + loggerName + " could not be created"); throw e; } if (appender == null) { LOG.info("Http request log for " + loggerName + " is not defined"); return null; } if (appender instanceof HttpRequestLogAppender) { HttpRequestLogAppender requestLogAppender = (HttpRequestLogAppender)appender; NCSARequestLog requestLog = new NCSARequestLog(); requestLog.setFilename(requestLogAppender.getFilename()); requestLog.setRetainDays(requestLogAppender.getRetainDays()); return requestLog; } else { LOG.warn("Jetty request log for " + loggerName + " was of the wrong class"); return null; } }
@Test public void testAppenderUndefined() { RequestLog requestLog = HttpRequestLog.getRequestLog("test"); assertNull("RequestLog should be null", requestLog); }