@Test public void testGzipHandlerOption() throws Exception { ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.GZIP); GzipHandler gzip = context.getGzipHandler(); _server.start(); assertEquals(context.getSessionHandler(), context.getHandler()); assertEquals(gzip, context.getSessionHandler().getHandler()); assertEquals(context.getServletHandler(), gzip.getHandler()); }
@Test public void testGzipHandlerSet() throws Exception { ServletContextHandler context = new ServletContextHandler(); context.setSessionHandler(new SessionHandler()); context.setGzipHandler(new GzipHandler()); GzipHandler gzip = context.getGzipHandler(); _server.start(); assertEquals(context.getSessionHandler(), context.getHandler()); assertEquals(gzip, context.getSessionHandler().getHandler()); assertEquals(context.getServletHandler(), gzip.getHandler()); }
/** * Initialize server handlers, rest resources. * * @throws Exception */ protected void initServer() throws Exception { _server = new Server(); initThreadPool(); initConnectors(); // AuthN servlet filters servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS); servletHandler.setContextPath("/"); _server.setHandler(servletHandler); ((AbstractSessionManager) servletHandler.getSessionHandler().getSessionManager()) .setUsingCookies(false); if (_disabler != null) { final FilterHolder securityFilterHolder = new FilterHolder(new DelegatingFilterProxy(_disablingFilter)); servletHandler.addFilter(securityFilterHolder, "/*", FilterMapping.REQUEST); _log.warn("security checks are disabled... skipped adding security filters"); } else { final FilterHolder securityFilterHolder = new FilterHolder(new DelegatingFilterProxy(_secFilters)); servletHandler.addFilter(securityFilterHolder, "/*", FilterMapping.REQUEST); } // Add the REST resources if (_app != null) { ResourceConfig config = new DefaultResourceConfig(); config.add(_app); Map<String, MediaType> type = config.getMediaTypeMappings(); type.put("json", MediaType.APPLICATION_JSON_TYPE); type.put("xml", MediaType.APPLICATION_XML_TYPE); servletHandler.addServlet(new ServletHolder(new ServletContainer(config)), "/*"); // AuthZ resource filters Map<String, Object> props = new HashMap<String, Object>(); props.put(ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES, _resourceFilterFactory); // Adding the ContainerResponseFilter props.put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, _responseFilter); config.setPropertiesAndFeatures(props); } if (_dbClient != null) { // in some cases, like syssvc, we don't want the service to be blocked by dbsvc startup. // Otherwise there could be a dependency loop between services. if (startDbClientInBackground) { _log.info("starting dbclient in background"); new Thread() { public void run() { _dbClient.start(); } }.start(); } else { _log.info("starting dbclient"); _dbClient.start(); } } }
@Test public void testHandlerBeforeServletHandler() throws Exception { ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); HandlerWrapper extra = new HandlerWrapper(); context.getSessionHandler().insertHandler(extra); context.addServlet(TestServlet.class, "/test"); context.setContextPath("/"); _server.setHandler(context); _server.start(); StringBuffer request = new StringBuffer(); request.append("GET /test HTTP/1.0\n"); request.append("Host: localhost\n"); request.append("\n"); String response = _connector.getResponses(request.toString()); assertResponseContains("Test", response); assertEquals(extra, context.getSessionHandler().getHandler()); }
@Test public void testFindContainer() throws Exception { ContextHandlerCollection contexts = new ContextHandlerCollection(); _server.setHandler(contexts); ServletContextHandler root = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS); SessionHandler session = root.getSessionHandler(); ServletHandler servlet = root.getServletHandler(); SecurityHandler security = new ConstraintSecurityHandler(); root.setSecurityHandler(security); _server.start(); assertEquals( root, AbstractHandlerContainer.findContainerOf(_server, ContextHandler.class, session)); assertEquals( root, AbstractHandlerContainer.findContainerOf(_server, ContextHandler.class, security)); assertEquals( root, AbstractHandlerContainer.findContainerOf(_server, ContextHandler.class, servlet)); }
public static void main(String[] args) throws Exception { // load main configuration String configLoc = System.getProperty(CONFIG_LOCATION_SYS_VAR, CONFIG_LOCATION_DEFAULT); System.setProperty(CONFIG_LOCATION_SYS_VAR, configLoc); Properties configProps = new Properties(); try { configProps.load(new FileInputStream(ResourceUtils.getFile(configLoc))); logger.info("Successfully loaded main configuration."); } catch (Exception ex) { logger.error("Fail to start in early part", ex); throw ex; } Config config = new Config(configProps); // load log4j configuration // @todo review the effect and final configuration when -Dlog4j.properties is specified with // command line String log4jConfigLoc = config.getValue(ItemMeta.BOOTSTRAP_LOG4J_CONFIG_LOCATION); if (log4jConfigLoc != null) { Properties log4jConfig = new Properties(); try { log4jConfig.load(new FileInputStream(ResourceUtils.getFile(log4jConfigLoc))); org.apache.log4j.LogManager.resetConfiguration(); org.apache.log4j.PropertyConfigurator.configure(log4jConfig); logger.info("Successfully loaded log4j configuration at {}", log4jConfigLoc); } catch (Exception ex) { logger.error("Faile to load specified log4j configuration", ex); throw ex; } } ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS); sch.setContextPath(config.getValue(ItemMeta.ROOT_SERVLET_CONTEXT_PATH)); sch.getSessionHandler() .getSessionManager() .setSessionCookie(config.getValue(ItemMeta.ROOT_SERVLET_SESSION_ID)); ServletHolder dsh = sch.addServlet(DefaultServlet.class, "/"); dsh.setInitOrder(1); ServletHolder jsh = new ServletHolder(JerseySpringServlet.class); jsh.setInitParameter( JerseySpringServlet.INIT_PARM_SPRING_CONFIG_LOCATION, config.getValue(ItemMeta.BOOTSTRAP_SPRING_CONFIG_LOCATION)); // Refer https://jersey.java.net/apidocs/1.18/jersey/index.html?constant-values.html jsh.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true"); jsh.setInitParameter( ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, "com.sun.jersey.api.container.filter.LoggingFilter"); jsh.setInitParameter( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, "com.sun.jersey.api.container.filter.LoggingFilter"); jsh.setInitParameter(ResourceConfig.FEATURE_TRACE, "true"); // jsh.setInitParameter(JSONMarshaller.FORMATTED, "true"); // jsh.setInitParameter(FeaturesAndProperties.FEATURE_FORMATTED, "true"); // jsh.setInitParameter(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true"); sch.addServlet(jsh, config.getValue(ItemMeta.JERSEY_SERVLET_URL_PATTEN)); jsh.setInitOrder(config.getIntValue(ItemMeta.JERSEY_SERVLET_INIT_ORDER)); // For more, refer // http://download.eclipse.org/jetty/stable-7/apidocs/index.html?org/eclipse/jetty/servlets/CrossOriginFilter.html FilterHolder fh = new FilterHolder(CrossOriginFilter.class); fh.setName("crossOriginFilter"); fh.setInitParameter( CrossOriginFilter.ALLOWED_ORIGINS_PARAM, config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_ORIGINS)); fh.setInitParameter( CrossOriginFilter.ALLOWED_METHODS_PARAM, config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_METHODS)); fh.setInitParameter( CrossOriginFilter.ALLOWED_HEADERS_PARAM, config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_HEADERS)); sch.addFilter(fh, "/*", FilterMapping.DEFAULT); Server jetty = new Server(); HandlerList hl = new HandlerList(); hl.addHandler(sch); jetty.setHandler(hl); jetty.setThreadPool( new QueuedThreadPool(config.getIntValue(ItemMeta.WEB_SERVER_THREAD_POOL_SIZE))); SelectChannelConnector conn = new SelectChannelConnector(); conn.setPort(config.getIntValue(ItemMeta.WEB_SERVER_PORT)); conn.setMaxIdleTime(config.getIntValue(ItemMeta.WEB_SERVER_MAX_IDLE_TIME)); MBeanContainer mbc = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); mbc.setDomain(config.getValue(ItemMeta.JMX_DOMAIN) + ".jetty"); jetty.getContainer().addEventListener(mbc); jetty.addBean(mbc); jetty.addConnector(conn); jetty.setStopAtShutdown(true); try { jetty.start(); logger.info("Jetty started at port {} on {}", conn.getPort(), "127.0.0.1"); } catch (Exception ex) { logger.error("Fail to start Jetty.", ex); System.exit(-1); } }
@Test public void testRemoveSession() throws Exception { String contextPath = ""; String servletMapping = "/server"; int scavengePeriod = 3; AbstractTestServer server = createServer(0, 1, scavengePeriod); ServletContextHandler context = server.addContext(contextPath); context.addServlet(TestServlet.class, servletMapping); TestEventListener testListener = new TestEventListener(); context.getSessionHandler().addEventListener(testListener); AbstractSessionManager m = (AbstractSessionManager) context.getSessionHandler().getSessionManager(); try { server.start(); int port = server.getPort(); HttpClient client = new HttpClient(); client.start(); try { ContentResponse response = client.GET( "http://localhost:" + port + contextPath + servletMapping + "?action=create"); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); String sessionCookie = response.getHeaders().get("Set-Cookie"); assertTrue(sessionCookie != null); // Mangle the cookie, replacing Path with $Path, etc. sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path="); // ensure sessionCreated listener is called assertTrue(testListener.isCreated()); assertEquals(1, m.getSessions()); assertEquals(1, m.getSessionsMax()); assertEquals(1, m.getSessionsTotal()); // now delete the session Request request = client.newRequest( "http://localhost:" + port + contextPath + servletMapping + "?action=delete"); request.header("Cookie", sessionCookie); response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); // ensure sessionDestroyed listener is called assertTrue(testListener.isDestroyed()); assertEquals(0, m.getSessions()); assertEquals(1, m.getSessionsMax()); assertEquals(1, m.getSessionsTotal()); // The session is not there anymore, even if we present an old cookie request = client.newRequest( "http://localhost:" + port + contextPath + servletMapping + "?action=check"); request.header("Cookie", sessionCookie); response = request.send(); assertEquals(HttpServletResponse.SC_OK, response.getStatus()); assertEquals(0, m.getSessions()); assertEquals(1, m.getSessionsMax()); assertEquals(1, m.getSessionsTotal()); } finally { client.stop(); } } finally { server.stop(); } }