/** * Insert a HandlerWrapper before the first Session,Security or ServletHandler * but after any other HandlerWrappers. */ public void insertHandler(HandlerWrapper handler) { HandlerWrapper h=this; // Skip any injected handlers while (h.getHandler() instanceof HandlerWrapper) { HandlerWrapper wrapper = (HandlerWrapper)h.getHandler(); if (wrapper instanceof SessionHandler || wrapper instanceof SecurityHandler || wrapper instanceof ServletHandler) break; h=wrapper; } h.setHandler(handler); relinkHandlers(); }
protected void addJettyHandlers(Server server, List<Handler> handlers) { if (handlers != null && !handlers.isEmpty()) { for (Handler handler : handlers) { if (handler instanceof HandlerWrapper) { // avoid setting the security handler more than once if (!handler.equals(server.getHandler())) { ((HandlerWrapper) handler).setHandler(server.getHandler()); server.setHandler(handler); } } else { HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.addHandler(server.getHandler()); handlerCollection.addHandler(handler); server.setHandler(handlerCollection); } } } }
@Override public HandlerWrapper createGzipHandler(Compression compression) { try { Class<?> handlerClass = ClassUtils.forName(GZIP_HANDLER_JETTY_8, getClass().getClassLoader()); HandlerWrapper handler = (HandlerWrapper) handlerClass.newInstance(); ReflectionUtils.findMethod(handlerClass, "setMinGzipSize", int.class) .invoke(handler, compression.getMinResponseSize()); ReflectionUtils.findMethod(handlerClass, "setMimeTypes", Set.class) .invoke(handler, new HashSet<String>( Arrays.asList(compression.getMimeTypes()))); if (compression.getExcludedUserAgents() != null) { ReflectionUtils.findMethod(handlerClass, "setExcluded", Set.class) .invoke(handler, new HashSet<String>( Arrays.asList(compression.getExcludedUserAgents()))); } return handler; } catch (Exception ex) { throw new RuntimeException("Failed to configure Jetty 8 gzip handler", ex); } }
@Override public HandlerWrapper createGzipHandler(Compression compression) { try { Class<?> handlerClass = ClassUtils.forName(GZIP_HANDLER_JETTY_9_2, getClass().getClassLoader()); HandlerWrapper gzipHandler = (HandlerWrapper) handlerClass.newInstance(); ReflectionUtils.findMethod(handlerClass, "setMinGzipSize", int.class) .invoke(gzipHandler, compression.getMinResponseSize()); ReflectionUtils .findMethod(handlerClass, "addIncludedMimeTypes", String[].class) .invoke(gzipHandler, new Object[] { compression.getMimeTypes() }); if (compression.getExcludedUserAgents() != null) { ReflectionUtils.findMethod(handlerClass, "setExcluded", Set.class) .invoke(gzipHandler, new HashSet<String>( Arrays.asList(compression.getExcludedUserAgents()))); } return gzipHandler; } catch (Exception ex) { throw new RuntimeException("Failed to configure Jetty 9.2 gzip handler", ex); } }
@Test public void wrappedHandlers() throws Exception { JettyEmbeddedServletContainerFactory factory = getFactory(); factory.setServerCustomizers(Arrays.asList(new JettyServerCustomizer() { @Override public void customize(Server server) { Handler handler = server.getHandler(); HandlerWrapper wrapper = new HandlerWrapper(); wrapper.setHandler(handler); HandlerCollection collection = new HandlerCollection(); collection.addHandler(wrapper); server.setHandler(collection); } })); this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); assertThat(getResponse(getLocalUrl("/hello"))).isEqualTo("Hello World"); }
@Override public HandlerWrapper createGzipHandler(Compression compression) { try { Class<?> handlerClass = ClassUtils.forName(GZIP_HANDLER_JETTY_9_3, getClass().getClassLoader()); HandlerWrapper handler = (HandlerWrapper) handlerClass.newInstance(); ReflectionUtils.findMethod(handlerClass, "setMinGzipSize", int.class) .invoke(handler, compression.getMinResponseSize()); ReflectionUtils .findMethod(handlerClass, "setIncludedMimeTypes", String[].class) .invoke(handler, new Object[] { compression.getMimeTypes() }); if (compression.getExcludedUserAgents() != null) { ReflectionUtils .findMethod(handlerClass, "setExcludedAgentPatterns", String[].class) .invoke(handler, new Object[] { compression.getExcludedUserAgents() }); } return handler; } catch (Exception ex) { throw new RuntimeException("Failed to configure Jetty 9.3 gzip handler", ex); } }
protected ServletContextHandler createContext(Server server, Connector connector, List<Handler> handlers) throws Exception { ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS); server.addConnector(connector); if (handlers != null && !handlers.isEmpty()) { for (Handler handler : handlers) { if (handler instanceof HandlerWrapper) { ((HandlerWrapper) handler).setHandler(server.getHandler()); server.setHandler(handler); } else { HandlerCollection handlerCollection = new HandlerCollection(); handlerCollection.addHandler(server.getHandler()); handlerCollection.addHandler(handler); server.setHandler(handlerCollection); } } } return context; }
@Test public void wrappedHandlers() throws Exception { JettyEmbeddedServletContainerFactory factory = getFactory(); factory.setServerCustomizers(Arrays.asList(new JettyServerCustomizer() { @Override public void customize(Server server) { Handler handler = server.getHandler(); HandlerWrapper wrapper = new HandlerWrapper(); wrapper.setHandler(handler); HandlerCollection collection = new HandlerCollection(); collection.addHandler(wrapper); server.setHandler(collection); } })); this.container = factory .getEmbeddedServletContainer(exampleServletRegistration()); this.container.start(); assertThat(getResponse(getLocalUrl("/hello")), equalTo("Hello World")); }
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(); }
/** * Hook up Jetty handlers. Do this before start() is called. */ public void registerHandlers(HandlerWrapper s) { GateHandler gh = new GateHandler(); AddCommonResponseHeadersHandler rhh = new AddCommonResponseHeadersHandler(); ExtensionHandler1 eh1 = new ExtensionHandler1(); ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS ); context.setContextPath("/"); context.addServlet(H2oNpsBinServlet.class, "/3/NodePersistentStorage.bin/*"); context.addServlet(H2oPostFileServlet.class, "/3/PostFile.bin"); context.addServlet(H2oPostFileServlet.class, "/3/PostFile"); context.addServlet(H2oDatasetServlet.class, "/3/DownloadDataset"); context.addServlet(H2oDatasetServlet.class, "/3/DownloadDataset.bin"); context.addServlet(H2oDefaultServlet.class, "/"); Handler[] handlers = {gh, rhh, eh1, context}; HandlerCollection hc = new HandlerCollection(); hc.setHandlers(handlers); s.setHandler(hc); }
/** * Hook up Jetty handlers. Do this before start() is called. */ public void registerHandlers(HandlerWrapper handlerWrapper) { // Both security and session handlers are already created (Note: we don't want to create a new separate session // handler just for ServletContextHandler - we want to have just one SessionHandler & SessionManager) ServletContextHandler context = new ServletContextHandler( ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS ); if(null != _args.context_path && ! _args.context_path.isEmpty()) { context.setContextPath(_args.context_path); } else { context.setContextPath("/"); } registerHandlers(handlerWrapper, context); }
@Override protected void registerHandlers(HandlerWrapper handlerWrapper, ServletContextHandler context) { // setup authenticating proxy servlet (each request is forwarded with BASIC AUTH) ServletHolder proxyServlet = new ServletHolder(Transparent.class); proxyServlet.setInitParameter("ProxyTo", _proxyTo); proxyServlet.setInitParameter("Prefix", "/"); proxyServlet.setInitParameter("BasicAuth", _credentials.toBasicAuth()); context.addServlet(proxyServlet, "/*"); // authHandlers assume the user is already authenticated HandlerCollection authHandlers = new HandlerCollection(); authHandlers.setHandlers(new Handler[]{ new AuthenticationHandler(), context, }); // handles requests of login form and delegates the rest to the authHandlers LoginHandler loginHandler = new LoginHandler("/login", "/loginError"); loginHandler.setHandler(authHandlers); // login handler is the root handler handlerWrapper.setHandler(loginHandler); }
public ServletContextHandler(HandlerContainer parent, String contextPath, SessionHandler sessionHandler, SecurityHandler securityHandler, ServletHandler servletHandler, ErrorHandler errorHandler,int options) { super((ContextHandler.Context)null); _options=options; _scontext = new Context(); _sessionHandler = sessionHandler; _securityHandler = securityHandler; _servletHandler = servletHandler; if (contextPath!=null) setContextPath(contextPath); if (parent instanceof HandlerWrapper) ((HandlerWrapper)parent).setHandler(this); else if (parent instanceof HandlerCollection) ((HandlerCollection)parent).addHandler(this); // Link the handlers relinkHandlers(); if (errorHandler!=null) setErrorHandler(errorHandler); this.addFilter(new FilterHolder(new HTTPAuthFilter()), "/v2/*", EnumSet.allOf(DispatcherType.class)); }
private HandlerWrapper createGzipHandler() { ClassLoader classLoader = getClass().getClassLoader(); if (ClassUtils.isPresent(GZIP_HANDLER_JETTY_9_2, classLoader)) { return new Jetty92GzipHandlerFactory().createGzipHandler(getCompression()); } if (ClassUtils.isPresent(GZIP_HANDLER_JETTY_8, getClass().getClassLoader())) { return new Jetty8GzipHandlerFactory().createGzipHandler(getCompression()); } if (ClassUtils.isPresent(GZIP_HANDLER_JETTY_9_3, getClass().getClassLoader())) { return new Jetty93GzipHandlerFactory().createGzipHandler(getCompression()); } throw new IllegalStateException( "Compression is enabled, but GzipHandler is not on the classpath"); }
@Override public HandlerWrapper createGzipHandler(Compression compression) { GzipHandler handler = new GzipHandler(); handler.setMinGzipSize(compression.getMinResponseSize()); handler.setIncludedMimeTypes(compression.getMimeTypes()); if (compression.getExcludedUserAgents() != null) { handler.setExcludedAgentPatterns(compression.getExcludedUserAgents()); } return handler; }
private void handleDeferredInitialize(Handler... handlers) throws Exception { for (Handler handler : handlers) { if (handler instanceof JettyEmbeddedWebAppContext) { ((JettyEmbeddedWebAppContext) handler).deferredInitialize(); } else if (handler instanceof HandlerWrapper) { handleDeferredInitialize(((HandlerWrapper) handler).getHandler()); } else if (handler instanceof HandlerCollection) { handleDeferredInitialize(((HandlerCollection) handler).getHandlers()); } } }
@Override public HandlerWrapper createGzipHandler(Compression compression) { GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setMinGzipSize(compression.getMinResponseSize()); gzipHandler.addIncludedMimeTypes(compression.getMimeTypes()); if (compression.getExcludedUserAgents() != null) { gzipHandler.setExcluded(new HashSet<String>( Arrays.asList(compression.getExcludedUserAgents()))); } return gzipHandler; }
public JettyStarter() { HttpConnectionFactory httpFactory = new HttpConnectionFactory(config); HTTP2ServerConnectionFactory http2Factory = new HTTP2ServerConnectionFactory( config); ALPNServerConnectionFactory alpn = createAlpnProtocolFactory(httpFactory); Server server = createServer(httpFactory, http2Factory, alpn); HandlerWrapper servletHandler = createServletHandlerWithServlet(); HandlerWrapper gzipHandler = createGzipHandler(); gzipHandler.setHandler(servletHandler); server.setHandler(gzipHandler); this.server = server; }
@Override public EmbeddedServletContainer getEmbeddedServletContainer( ServletContextInitializer... initializers) { JettyEmbeddedWebAppContext context = new JettyEmbeddedWebAppContext(); int port = (getPort() >= 0 ? getPort() : 0); Server server = new Server(new InetSocketAddress(getAddress(), port)); configureWebAppContext(context, initializers); if (getCompression() != null && getCompression().getEnabled()) { HandlerWrapper gzipHandler = createGzipHandler(); gzipHandler.setHandler(context); server.setHandler(gzipHandler); } else { server.setHandler(context); } this.logger.info("Server initialized with port: " + port); if (getSsl() != null && getSsl().isEnabled()) { SslContextFactory sslContextFactory = new SslContextFactory(); configureSsl(sslContextFactory, getSsl()); AbstractConnector connector = getSslServerConnectorFactory() .getConnector(server, sslContextFactory, port); server.setConnectors(new Connector[] { connector }); } for (JettyServerCustomizer customizer : getServerCustomizers()) { customizer.customize(server); } if (this.useForwardHeaders) { new ForwardHeadersCustomizer().customize(server); } return getJettyEmbeddedServletContainer(server); }
@Override public HandlerWrapper createGzipHandler(Compression compression) { GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setMinGzipSize(compression.getMinResponseSize()); gzipHandler.setMimeTypes( new HashSet<String>(Arrays.asList(compression.getMimeTypes()))); if (compression.getExcludedUserAgents() != null) { gzipHandler.setExcluded(new HashSet<String>( Arrays.asList(compression.getExcludedUserAgents()))); } return gzipHandler; }
@Override protected void registerHandlers(HandlerWrapper handlerWrapper, ServletContextHandler context) { context.addServlet(NpsBinServlet.class, "/3/NodePersistentStorage.bin/*"); context.addServlet(PostFileServlet.class, "/3/PostFile.bin"); context.addServlet(PostFileServlet.class, "/3/PostFile"); context.addServlet(DatasetServlet.class, "/3/DownloadDataset"); context.addServlet(DatasetServlet.class, "/3/DownloadDataset.bin"); context.addServlet(PutKeyServlet.class, "/3/PutKey.bin"); context.addServlet(PutKeyServlet.class, "/3/PutKey"); context.addServlet(RequestServer.class, "/"); // Handlers that can only be invoked for an authenticated user (if auth is enabled) HandlerCollection authHandlers = new HandlerCollection(); authHandlers.setHandlers(new Handler[]{ new AuthenticationHandler(), new ExtensionHandler1(), context, }); // LoginHandler handles directly login requests and delegates the rest to the authHandlers LoginHandler loginHandler = new LoginHandler("/login", "/loginError"); loginHandler.setHandler(authHandlers); HandlerCollection hc = new HandlerCollection(); hc.setHandlers(new Handler[]{ new GateHandler(), loginHandler }); handlerWrapper.setHandler(hc); }
@Test public void shouldSetHeadersAndBaseDirectory() throws IOException { assertThat(handler.getContextPath(), is("/go/assets")); assertThat(((HandlerWrapper) handler.getHandler()).getHandler() instanceof AssetsContextHandler.AssetsHandler, is(true)); AssetsContextHandler.AssetsHandler assetsHandler = (AssetsContextHandler.AssetsHandler) ((HandlerWrapper) handler.getHandler()).getHandler(); ResourceHandler resourceHandler = (ResourceHandler) ReflectionUtil.getField(assetsHandler, "resourceHandler"); assertThat(resourceHandler.getCacheControl(), is("max-age=31536000,public")); assertThat(resourceHandler.getResourceBase(), isSameFileAs(new File("WEB-INF/rails.root/public/assets").toURI().toString())); }
@Test public void shouldNotHandleForRails4DevelopmentMode() throws IOException, ServletException { when(systemEnvironment.useCompressedJs()).thenReturn(false); String target = "/go/assets/junk"; Request request = mock(Request.class); HttpServletResponse response = mock(HttpServletResponse.class); Request baseRequest = mock(Request.class); ResourceHandler resourceHandler = mock(ResourceHandler.class); ReflectionUtil.setField(((HandlerWrapper) handler.getHandler()).getHandler(), "resourceHandler", resourceHandler); handler.getHandler().handle(target, baseRequest, request, response); verify(resourceHandler, never()).handle(any(String.class), any(Request.class), any(HttpServletRequest.class), any(HttpServletResponse.class)); }
private Handler applyWrapper(Handler handler, HandlerWrapper wrapper) { wrapper.setHandler(handler); return wrapper; }
static Handler wrapUrlMapping(Handler handler, File file) { final HandlerWrapper wrapper = new UrlRemapping(file); wrapper.setHandler(handler); return wrapper; }
List<HandlerWrapper> handlerWrappers() { return handlerWrappers; }
HandlerWrapper createGzipHandler(Compression compression);