/** * @param gzipHandler The {@link GzipHandler} to set on this context. */ public void setGzipHandler(GzipHandler gzipHandler) { if (isStarted()) throw new IllegalStateException("STARTED"); Handler next=null; if (_gzipHandler!=null) { next=_gzipHandler.getHandler(); _gzipHandler.setHandler(null); replaceHandler(_gzipHandler,gzipHandler); } _gzipHandler = gzipHandler; if (next!=null && _gzipHandler.getHandler()==null) _gzipHandler.setHandler(next); relinkHandlers(); }
private void addStaticResourceConfig(ServletContextHandler context) { URL webappLocation = getClass().getResource("/webapp/index.html"); if (webappLocation == null) { System.err.println("Couldn't get webapp location."); } else { try { URI webRootUri = URI.create(webappLocation.toURI().toASCIIString().replaceFirst("/index.html$", "/")); context.setBaseResource(Resource.newResource(webRootUri)); context.setWelcomeFiles(new String[]{"index.html"}); GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setIncludedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name()); context.setGzipHandler(gzipHandler); context.addFilter(TryFilesFilter.class, "*", EnumSet.of(DispatcherType.REQUEST)); } catch (URISyntaxException | MalformedURLException e) { e.printStackTrace(); } } }
private Handler createRestService() { ResourceConfig rc = new ResourceConfig(); rc.register(systemResource); rc.register(appResource); rc.register(JacksonFeature.class); rc.register(CORSFilter.class); SwaggerDocs.registerSwaggerJsonResource(rc); rc.addProperties(new HashMap<String,Object>() {{ // Turn off buffering so results can be streamed put(ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 0); }}); ServletHolder holder = new ServletHolder(new ServletContainer(rc)); ServletContextHandler sch = new ServletContextHandler(); sch.setContextPath("/api/v1"); sch.addServlet(holder, "/*"); GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setHandler(sch); return gzipHandler; }
@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.setHandler(server.getHandler()); gzipHandler.setSyncFlush(true); server.setHandler(gzipHandler); }); return factory; }
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String path = req.getPathInfo(); if (path != null && byName.matcher(path).matches()) { final String key = path.trim().substring(1); InputStream inputStream = req.getInputStream(); if (GzipHandler.GZIP.equalsIgnoreCase(req.getHeader(HttpHeaders.CONTENT_ENCODING))) { inputStream = new GZIPInputStream(inputStream); } try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { final String body = CharStreams.toString(reader); writeResponse(resp, circuitBreakersResource.modifyCircuitBreaker(key, body)); } } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
/** * Calling this method will cause the server to compress the responses if the client supports GZIP responses and the resource mime type is not of a known compressed type. *In most cases it should be enabled. */ public void setGzipEnabled(boolean b) { if (b) { gzipHandler = new GzipHandler(); gzipHandler.setIncludedMethods(HttpMethod.POST.toString(), HttpMethod.GET.toString()); } else { gzipHandler = null; } }
@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; }
public JettyServer(List<HttpServerConnectorCreator> connectors, List<Object> resources) { server=new org.eclipse.jetty.server.Server(); currentConnectors.addAll(connectors); for (HttpServerConnectorCreator creator : currentConnectors) { creator.addToServer(server); } rootServlet = new UpdateableServlet(new ServletContainer(jerseySetup(resources))); ServletHolder holder = new ServletHolder(rootServlet); ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); contextHandler.addServlet( holder, "/*"); ErrorHandler errorHandler = new ErrorHandler(); errorHandler.setShowStacks(true); contextHandler.setErrorHandler(errorHandler); GzipHandler gzipHandler = new GzipHandler(); // HashSet<String> mimeTypes = new HashSet<>(); // mimeTypes.add("text/html"); // mimeTypes.add("text/plain"); // mimeTypes.add("text/css"); // mimeTypes.add("application/x-javascript"); // mimeTypes.add("application/json"); gzipHandler.setMinGzipSize(0); gzipHandler.setHandler(contextHandler); HandlerCollection handlers = new HandlerList(); additionalHandlers().forEach(handler -> handlers.addHandler(handler)); handlers.addHandler(gzipHandler); server.setHandler(handlers); }
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 GzipHandler newGzipHandler(ServerConfig serverConfig) { GzipHandler gzipHandler = new GzipHandlerWithVaryHeaderFixed(); gzipHandler.setCompressionLevel(serverConfig.responseCompressionLevel()); gzipHandler.setCheckGzExists(false); gzipHandler.setIncludedMethods("GET", "POST"); return gzipHandler; }
private GzipHandler createGzipHandler() { GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setIncludedPaths("/*"); gzipHandler.setMinGzipSize(0); gzipHandler.setIncludedMimeTypes("text/plain", "text/html"); return gzipHandler; }
protected String startImpl(ServletHolder holder, int port) throws Exception { holder.setInitOrder(0); { MultipartConfig multipartConfig = frontServletClass.getAnnotation(MultipartConfig.class); if (multipartConfig != null) holder.getRegistration().setMultipartConfig(new MultipartConfigElement(multipartConfig)); else holder.getRegistration().setMultipartConfig(new MultipartConfigElement("")); } ServletContextHandler ctx = new ServletContextHandler(ServletContextHandler.SESSIONS); ctx.setContextPath(""); ctx.addServlet(holder, "/*"); ctx.setResourceBase(Paths.get("").toString()); server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(port); server.setConnectors(new Connector[] { connector }); GzipHandler gzip = new GzipHandler(); gzip.setHandler(ctx); server.setHandler(gzip); server.start(); this.servlet = (FrontServletBase) holder.getServlet(); String host = connector.getHost(); if (host == null) { host = "localhost"; } return String.format("http://%s:%d", host, connector.getLocalPort()); }
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; }
private Handler getGzipHandler(Handler handler) { GzipHandler gzipHandler = new GzipHandler(); gzipHandler.addIncludedMethods("GET", "POST", "PUT", "DELETE", "PATCH"); gzipHandler.addIncludedPaths("/*"); gzipHandler.setHandler(handler); return gzipHandler; }
@Provides(type = Type.SET) ContextConfigurator provideGzipHandler() { return new ContextConfigurator() { @Override public void init(ServletContextHandler context) { context.setGzipHandler(new GzipHandler()); } }; }
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); }
private static Handler getGzipHandler(Handler wrapped) { GzipHandler gzip = new GzipHandler(); gzip.addIncludedMethods(HttpMethod.POST); gzip.setHandler(wrapped); return gzip; }
/** * Wraps the whole web app in a gzip handler to make Jetty return compressed content * * http://www.eclipse.org/jetty/documentation/current/gzip-filter.html */ private Handler enableGzip(WebAppContext ctx) { GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setHandler(ctx); return gzipHandler; }
private Handler gzipped(Handler handler) { GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setHandler(handler); return gzipHandler; }
public void start() { System.setProperty("java.net.preferIPv4Stack", "true");//TODO optional? server = new org.eclipse.jetty.server.Server(); // HashSessionIdManager sessionIdManager = new HashSessionIdManager(); // server.setSessionIdManager(sessionIdManager); connector = new NetworkTrafficServerConnector(server); connector.setPort(httpPort); connector.setHost(host); server.addConnector(connector); ServletContextHandler contextHandler = new ServletContextHandler(); SessionHandler sessionHandler = new SessionHandler(); // HashSessionManager sessionManager = new HashSessionManager(); // sessionManager.setMaxInactiveInterval(sessionTimeoutS); // sessionManager.setSessionCookie(sessionManager.getSessionCookie()+httpPort); //avoid session mix up for 2 server running as localhost // sessionHandler.setSessionManager(sessionManager); contextHandler.setSessionHandler(sessionHandler); contextHandler.addServlet(new ServletHolder(new ServletContainer(jerseySetup(restResource))), "/applicationServer/*"); ErrorHandler errorHandler = new ErrorHandler(); errorHandler.setShowStacks(true); contextHandler.setErrorHandler(errorHandler); GzipHandler gzipHandler = new GzipHandler(); // HashSet<String> mimeTypes = new HashSet<>(); // mimeTypes.add("text/html"); // mimeTypes.add("text/plain"); // mimeTypes.add("text/css"); // mimeTypes.add("application/x-javascript"); // mimeTypes.add("application/json"); gzipHandler.setMinGzipSize(0); // gzipHandler.setMimeTypes(mimeTypes); HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[]{resourceHandler, contextHandler}); gzipHandler.setHandler(handlers); server.setHandler(gzipHandler); try { server.start(); } catch (Exception e) { throw new RuntimeException(e); } }
protected GzipHandler createGzipHandler() { GzipHandler gzipHandler = new GzipHandler(); gzipHandler.setCheckGzExists(false); return gzipHandler; }
public static void main(String[] args) throws Exception { try { // Set up the configuration configuration = new Configuration(); // Create the Jetty server server = new Server(configuration.port); // Create the handlers mainHandler = new MainHandler(); gzipHandler = new GzipHandler(); gzipHandler.setHandler(mainHandler); // Select the handler to be used Handler handler; if (configuration.authenticationEnabled) { securityHandler = new BasicAuth(); securityHandler.setHandler(gzipHandler); handler = securityHandler; } else { handler = gzipHandler; } // Graceful shutdown statisticsHandler = new StatisticsHandler(); statisticsHandler.setHandler(handler); server.setHandler(statisticsHandler); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { try { log.info("Initiating graceful shutdown..."); //server.getHandler().stop(); server.stop(); log.info("Shutdown completed gracefully."); } catch (Exception e) { log.info("Shutdown error:"); e.printStackTrace(); } } })); // And we're good to go server.start(); System.out.println(configuration); log.info("Completed startup process."); server.join(); } finally { ClassReloader.shutdown(); } }
@Signature public void __construct() { gzipHandler = new GzipHandler(); }