private void addApplication(final ServletContextHandler context, final MinijaxApplication application) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // (0) Sort the resource methods by literal length application.sortResourceMethods(); // (1) Add Minijax filter (must come before websocket!) context.addFilter(new FilterHolder(new MinijaxFilter(application)), "/*", EnumSet.of(DispatcherType.REQUEST)); // (2) WebSocket endpoints if (OptionalClasses.WEB_SOCKET_UTILS != null) { OptionalClasses.WEB_SOCKET_UTILS .getMethod("init", ServletContextHandler.class, MinijaxApplication.class) .invoke(null, context, application); } // (3) Dynamic JAX-RS content final MinijaxServlet servlet = new MinijaxServlet(application); final ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.getRegistration().setMultipartConfig(new MultipartConfigElement("")); context.addServlet(servletHolder, "/*"); }
public void testConfiguredHttpsProxy() throws Exception { File testRepo = createMyModuleRepository("testConfiguredHttpsProxy"); File emptyRepo = Files.createTempDirectory("vertx").toFile(); emptyRepo.deleteOnExit(); startRemoteServer(configureTls(createRemoteServer(testRepo))); Server server = new Server(8081); ServletHandler handler = new ServletHandler(); server.setHandler(handler); handler.addServletWithMapping(ProxyServlet.class, "/").setInitParameter("maxThreads", "10"); UrlCollectorFilter urlCollector = new UrlCollectorFilter(); handler.addFilterWithMapping(new FilterHolder(urlCollector), "/*", 0); server.start(); servers.add(server); System.setProperty(MavenVerticleFactory.HTTP_PROXY_SYS_PROP, "http://localhost:8081"); configureRepos(emptyRepo, "https://localhost:8443/"); URL expectedHost = new URL("http://localhost:8443/"); vertx.deployVerticle("maven:my:module:1.0::my.serviceA", new DeploymentOptions(), onSuccess(id -> { assertTrue("Was expecting " + urlCollector.requestedHosts + " to contain " + expectedHost, urlCollector.requestedHosts.contains(expectedHost)); testComplete(); })); await(); }
private void setFilters(JettyHttpEndpoint endpoint, Server server, String connectorKey) { ServletContextHandler context = server.getChildHandlerByClass(ServletContextHandler.class); List<Filter> filters = endpoint.getFilters(); for (Filter filter : filters) { FilterHolder filterHolder = new FilterHolder(); filterHolder.setFilter(new CamelFilterWrapper(filter)); String pathSpec = endpoint.getPath(); if (pathSpec == null || "".equals(pathSpec)) { pathSpec = "/"; } if (endpoint.isMatchOnUriPrefix()) { pathSpec = pathSpec.endsWith("/") ? pathSpec + "*" : pathSpec + "/*"; } addFilter(context, filterHolder, pathSpec); } }
public void init() { // Attach servlets for(Servlet servlet : context.servlets()) { final ServletHolder servletHolder = new ServletHolder(servlet); addServlet(servletHolder, MAPPING_URL); } // Attach event listeners for(EventListener listener : context.listeners()) { addEventListener(listener); } // Attach filters for(Filter filter : context.filters()) { addFilter(new FilterHolder(filter), MAPPING_URL, EnumSet.allOf(DispatcherType.class)); } }
public void init() { setContextPath("/management"); // REST configuration Servlet servlet = context.servlets().iterator().next(); final ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setInitParameter("javax.ws.rs.Application", "io.gravitee.am.gateway.handler.management.api.ManagementApplication"); servletHolder.setInitOrder(0); addServlet(servletHolder, "/*"); // Attach event listeners for(EventListener listener : context.listeners()) { addEventListener(listener); } // Attach filters for(Filter filter : context.filters()) { addFilter(new FilterHolder(filter), MAPPING_URL, EnumSet.allOf(DispatcherType.class)); } }
public void addServlet(String path, ServletHolder servletHolder, boolean requiresAuthentication) { ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath(path); context.addServlet(servletHolder, MATCH_ALL); context.setAttribute(WebService.ATTRIBUTE_PULSAR_NAME, pulsar); if (requiresAuthentication && pulsar.getConfiguration().isAuthenticationEnabled()) { FilterHolder filter = new FilterHolder(new AuthenticationFilter(pulsar)); context.addFilter(filter, MATCH_ALL, EnumSet.allOf(DispatcherType.class)); } FilterHolder responseFilter = new FilterHolder(new ResponseHandlerFilter(pulsar)); context.addFilter(responseFilter, MATCH_ALL, EnumSet.allOf(DispatcherType.class)); handlers.add(context); }
protected void initTracing(ServletContextHandler context) { client.register(new Builder(mockTracer).build()); ServerTracingDynamicFeature serverTracingFeature = new ServerTracingDynamicFeature.Builder(mockTracer) .withOperationNameProvider(HTTPMethodOperationName.newBuilder()) .withDecorators(Collections.singletonList(ServerSpanDecorator.STANDARD_TAGS)) .withSkipPattern("/health") .build(); // TODO clarify dispatcher types context.addFilter(new FilterHolder(new SpanFinishingFilter(mockTracer)), "/*", EnumSet.of( DispatcherType.REQUEST, DispatcherType.FORWARD, // TODO CXF does not call AsyncListener#onComplete() without this (it calls only onStartAsync) DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.INCLUDE)); context.setAttribute(CLIENT_ATTRIBUTE, client); context.setAttribute(TRACER_ATTRIBUTE, mockTracer); context.setAttribute(SERVER_TRACING_FEATURE, serverTracingFeature); }
@Override public void run(Environment environment) { SkillzFilter filter = typeFactory.create(SkillzFilter.class); filter.setPathPrefix(skillzPath.substring(0, skillzPath.length() -2)); FilterHolder holder = new FilterHolder(filter); environment.getApplicationContext().addFilter(holder, skillzPath, EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE) ); StringBuilder sb = new StringBuilder("Skillz: ") .append(System.lineSeparator()) .append(System.lineSeparator()); String filterPath = skillzPath.substring(0, skillzPath.length() -1); for(IntrospectionData data :filter.getRegistry().getAllIntrospectionData()){ String path = ((Skill) data.getType().getAnnotation(Skill.class)).path(); sb.append(String.format(" SKILL %s (%s)", filterPath+path, data.getType().getName())).append(System.lineSeparator()); } LOG.info(sb.toString()); }
private void setFilters(JettyHttpEndpoint endpoint, Server server, String connectorKey) { ServletContextHandler context = server.getChildHandlerByClass(ServletContextHandler.class); List<Filter> filters = endpoint.getFilters(); for (Filter filter : filters) { FilterHolder filterHolder = new FilterHolder(); if (endpoint.getFilterInitParameters() != null) { filterHolder.setInitParameters(endpoint.getFilterInitParameters()); } filterHolder.setFilter(new CamelFilterWrapper(filter)); String pathSpec = endpoint.getPath(); if (pathSpec == null || "".equals(pathSpec)) { pathSpec = "/"; } if (endpoint.isMatchOnUriPrefix()) { pathSpec = pathSpec.endsWith("/") ? pathSpec + "*" : pathSpec + "/*"; } addFilter(context, filterHolder, pathSpec); } }
@Test public void testCrossOriginFilterAddedWhenOn() throws Exception { // setup CometdComponent component = context.getComponent("cometd", CometdComponent.class); Server server = new Server(); when(endpoint.isCrossOriginFilterOn()).thenReturn(true); when(endpoint.getFilterPath()).thenReturn(FILTER_PATH); when(endpoint.getAllowedOrigins()).thenReturn(ALLOWED_ORIGINS); // act component.createServletForConnector(server, connector, endpoint); // assert ServletContextHandler handler = (ServletContextHandler) server.getHandler(); assertEquals(1, handler.getServletHandler().getFilters().length); FilterHolder filterHolder = handler.getServletHandler().getFilters()[0]; Filter filter = filterHolder.getFilter(); assertTrue(filter instanceof CrossOriginFilter); }
private ServletContextHandler createServletHandlerWithServlet() { ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS); FilterHolder pushCacheFilter = context.addFilter(PushCacheFilter.class, "/*", null); Map<String, String> config = new HashMap<>(); config.put("maxAssociations", "32"); config.put("ports", Objects.toString(SSL_PORT)); pushCacheFilter.setInitParameters(config); context.addServlet(NoopServlet.class, "/*"); context.setContextPath("/"); return context; }
public int run() throws Exception { org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(port); HandlerList handlerList = new HandlerList(); ServletContextHandler servletContextHandler = new ServletContextHandler(); FilterHolder cof = new FilterHolder(new CrossOriginFilter()); cof.setInitParameter( CrossOriginFilter.EXPOSED_HEADERS_PARAM, "Date"); servletContextHandler.addFilter(cof, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST)); servletContextHandler.addServlet(new ServletHolder(new SmoothStreamingServlet(dataDir)), "/*"); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setBaseResource(Resource.newClassPathResource("supportfiles")); handlerList.addHandler(resourceHandler); handlerList.addHandler(servletContextHandler); server.setHandler(handlerList); server.start(); server.dumpStdErr(); server.join(); return 0; }
public JettyRule(final Filter filter, final Trace trace) { this.server = new Server(0); final ServletContextHandler handler = new ServletContextHandler(); handler.setContextPath("/"); handler.addServlet(new ServletHolder(new AsyncServlet(trace)), "/async"); handler.addServlet(new ServletHolder(new TraceServlet(trace)), "/traced"); handler.addServlet(new ServletHolder(new TraceServlet(trace)), "/untraced"); handler.addServlet(ForwardServlet.class, "/forward"); handler.addServlet(IncludeServlet.class, "/include"); handler.addServlet(FailingServlet.class, "/failure"); handler.addServlet(DefaultServlet.class, "/"); handler.addFilter(new FilterHolder(filter), "/async", EnumSet.allOf(DispatcherType.class)); // /untraced is intentionally NOT traced! handler.addFilter(new FilterHolder(filter), "/traced", EnumSet.allOf(DispatcherType.class)); handler.addFilter(new FilterHolder(filter), "/forward", EnumSet.allOf(DispatcherType.class)); handler.addFilter(new FilterHolder(filter), "/include", EnumSet.allOf(DispatcherType.class)); handler.addFilter(new FilterHolder(filter), "/failure", EnumSet.allOf(DispatcherType.class)); server.setHandler(handler); }
private void addHttpsForward(ServletContextHandler handler) { handler.addFilter(new FilterHolder(new Filter() { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { StringBuffer uri = ((HttpServletRequest) request).getRequestURL(); if (uri.toString().startsWith("http://")) { String location = "https://" + uri.substring("http://".length()); ((HttpServletResponse) response).sendRedirect(location); } else { chain.doFilter(request, response); } } public void destroy() { } }), "/*", EnumSet.of(DispatcherType.REQUEST)); }
/** * Initializes the Jersey Servlet. */ private void initJerseyServlet() { servletContext = new ServletContextHandler(ServletContextHandler.SESSIONS); servletContext.setContextPath("/"); // This is used for allowing access to different domains/ports. FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class); filterHolder.setInitParameter("allowedOrigins", "*"); filterHolder.setInitParameter("allowedMethods", "GET, POST"); servletContext.addFilter(filterHolder, "/*", null); jerseyServlet = servletContext.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*"); jerseyServlet.setInitOrder(0); // Tell the Jersey Servlet which REST class to load. jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", ProvisioningAction.class.getCanonicalName()); }
@Override public void run(final ZucchiniUIConfiguration configuration, final Environment environment) throws Exception { // Register the servlet that generates the UI Javascript config file final ServletHolder uiConfigServletHolder = new ServletHolder(new UIConfigServlet(configuration.getFrontend(), environment.getObjectMapper(), BASE_PATH)); environment.getApplicationContext().addServlet(uiConfigServletHolder, BASE_PATH + "/assets/config.js"); // Redirect to UI final ServletHolder redirectServletHolder = new ServletHolder(new RedirectServlet(BASE_PATH + "/")); environment.getApplicationContext().addServlet(redirectServletHolder, ""); environment.getApplicationContext().addServlet(redirectServletHolder, BASE_PATH); // Forward 404 pages to index (used for browser history) final FilterHolder forwardFilterHolder = new FilterHolder(new ForwardToIndexFilter(BASE_PATH)); environment.getApplicationContext().addFilter(forwardFilterHolder, BASE_PATH + "/*", EnumSet.allOf(DispatcherType.class)); // Default servlet final ServletHolder defaultServletHolder = new ServletHolder(new AssetServlet("/favicons/", "/", null, StandardCharsets.UTF_8)); environment.getApplicationContext().addServlet(defaultServletHolder, "/"); }
private static void stopJettySolrRunner(JettySolrRunner jetty) throws Exception { assert(jetty != null); monkeyLog("stop shard! " + jetty.getLocalPort()); // get a clean shutdown so that no dirs are left open... FilterHolder fh = jetty.getDispatchFilter(); if (fh != null) { SolrDispatchFilter sdf = (SolrDispatchFilter) fh.getFilter(); if (sdf != null) { sdf.destroy(); } } jetty.stop(); if (!jetty.isStopped()) { throw new RuntimeException("could not stop jetty"); } }
public static void kill(JettySolrRunner jetty) throws Exception { FilterHolder filterHolder = jetty.getDispatchFilter(); if (filterHolder != null) { Filter filter = filterHolder.getFilter(); if (filter != null) { CoreContainer cores = ((SolrDispatchFilter) filter).getCores(); if (cores != null) { int zklocalport = ((InetSocketAddress) cores.getZkController() .getZkClient().getSolrZooKeeper().getSocketAddress()).getPort(); IpTables.blockPort(zklocalport); } } } IpTables.blockPort(jetty.getLocalPort()); monkeyLog("kill shard! " + jetty.getLocalPort()); jetty.stop(); stop(jetty); if (!jetty.isStopped()) { throw new RuntimeException("could not kill jetty"); } }
public void stop() throws Exception { Filter filter = dispatchFilter.getFilter(); server.stop(); //server.destroy(); if (server.getState().equals(Server.FAILED)) { filter.destroy(); if (extraFilters != null) { for (FilterHolder f : extraFilters) { f.getFilter().destroy(); } } } server.join(); }
private void addFilters(ServletContextHandler servletContextHandler) { // RequestContext is required in other filters, hence set it up first servletContextHandler.addFilter(new FilterHolder(new HystrixContextFilter(configuration)), "/*", EnumSet.of(REQUEST)); // Set up distributed tracing filter ServletTraceFilter servletTraceFilter = ServletTraceFilterBuilder.build(configuration); if (servletTraceFilter != null) { servletContextHandler.addFilter(new FilterHolder(servletTraceFilter), "/*", EnumSet.of(REQUEST)); } servletContextHandler.addFilter(new FilterHolder(new RequestGzipFilter()), "/*", EnumSet.of(REQUEST)); List<JettyFilterConfiguration> jettyFilterConfigurations = Optional.ofNullable(configuration.getJettyConfiguration()).map(JettyConfiguration::getJettyFilterConfigurations).orElse(new ArrayList<>()); for (JettyFilterConfiguration filterConfig : jettyFilterConfigurations) { FilterHolder filterHolder = new FilterHolder(filterConfig.getFilter()); filterHolder.setInitParameters(filterConfig.getInitParameters()); for (String mapping : filterConfig.getMappings()) { servletContextHandler.addFilter(filterHolder, mapping, filterConfig.getDispatcherTypes()); } } }
private static Server startHttp1() throws Exception { Server server = new Server(0); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(newServletHolder(thriftServlet), TSERVLET_PATH); handler.addServletWithMapping(newServletHolder(rootServlet), "/"); handler.addFilterWithMapping(new FilterHolder(new ConnectionCloseFilter()), "/*", EnumSet.of(DispatcherType.REQUEST)); server.setHandler(handler); for (Connector c : server.getConnectors()) { for (ConnectionFactory f : c.getConnectionFactories()) { for (String p : f.getProtocols()) { if (p.startsWith("h2c")) { fail("Attempted to create a Jetty server without HTTP/2 support, but failed: " + f.getProtocols()); } } } } server.start(); return server; }
public EmbeddableJetty() { System.setProperty("wicket.configuration", "development"); ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration())); http.setPort(PORT); http.setIdleTimeout(1000 * 60 * 60); server.addConnector(http); ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SESSIONS); FilterHolder fh2 = new FilterHolder(WicketFilter.class); fh2.setInitParameter(ContextParamWebApplicationFactory.APP_CLASS_PARAM, WicketTestApplication.class.getName()); fh2.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, "/*"); sch.addFilter(fh2, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR)); server.setHandler(sch); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer); server.addEventListener(mBeanContainer); server.addBean(mBeanContainer); }
@Provides(type = Type.SET) ContextConfigurator provideCrossOriginFilter(final Configuration conf) { return new ContextConfigurator() { @Override public void init(ServletContextHandler context) { FilterHolder crossOriginFilter = new FilterHolder(CrossOriginFilter.class); Map<String, String> params = new HashMap<>(); params.put(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_ORIGIN, CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_ORIGIN_DEFAULT)); params.put(CrossOriginFilter.ALLOWED_METHODS_PARAM, conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_METHODS, CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_METHODS_DEFAULT)); params.put(CrossOriginFilter.ALLOWED_HEADERS_PARAM, conf.get(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_HEADERS, CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_HEADERS_DEFAULT)); crossOriginFilter.setInitParameters(params); context.addFilter(crossOriginFilter, "/*", EnumSet.of(DispatcherType.REQUEST)); } }; }
private static Server startSwaggerServer(CamelContext camelContext) throws Exception { Server server = new Server(9090); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.setAttribute("CamelContext", camelContext); server.setHandler(context); ServletHolder swaggerServlet = new ServletHolder(new ServletListenerRestSwaggerApiDeclarationServlet()); swaggerServlet.setInitParameter("base.path", "http://127.0.0.1:8080"); swaggerServlet.setInitParameter("api.path", "http://127.0.0.1:9090/api-docs"); swaggerServlet.setInitParameter("api.version", "0.0.1"); swaggerServlet.setInitParameter("api.title", "Example Services API"); context.addServlet(swaggerServlet, "/api-docs/*"); context.addFilter(new FilterHolder(new RestSwaggerCorsFilter ()), "/api-docs/*", EnumSet.of(DispatcherType.REQUEST)); server.start(); server.join(); return server; }
private static Pair<FilterHolder, Class<? extends ServletContainer>> loginServerPrincipal( UserProvider userProvider, Configuration conf) throws Exception { Class<? extends ServletContainer> containerClass = ServletContainer.class; if (userProvider.isHadoopSecurityEnabled() && userProvider.isHBaseSecurityEnabled()) { String machineName = Strings.domainNamePointerToHostName( DNS.getDefaultHost(conf.get(REST_DNS_INTERFACE, "default"), conf.get(REST_DNS_NAMESERVER, "default"))); String keytabFilename = conf.get(REST_KEYTAB_FILE); Preconditions.checkArgument(keytabFilename != null && !keytabFilename.isEmpty(), REST_KEYTAB_FILE + " should be set if security is enabled"); String principalConfig = conf.get(REST_KERBEROS_PRINCIPAL); Preconditions.checkArgument(principalConfig != null && !principalConfig.isEmpty(), REST_KERBEROS_PRINCIPAL + " should be set if security is enabled"); userProvider.login(REST_KEYTAB_FILE, REST_KERBEROS_PRINCIPAL, machineName); if (conf.get(REST_AUTHENTICATION_TYPE) != null) { containerClass = RESTServletContainer.class; FilterHolder authFilter = new FilterHolder(); authFilter.setClassName(AuthFilter.class.getName()); authFilter.setName("AuthenticationFilter"); return new Pair<>(authFilter,containerClass); } } return new Pair<>(null, containerClass); }
/** * Define a filter for a context and set up default url mappings. */ public static void defineFilter(ServletContextHandler handler, String name, String classname, Map<String,String> parameters, String[] urls) { FilterHolder holder = new FilterHolder(); holder.setName(name); holder.setClassName(classname); if (parameters != null) { holder.setInitParameters(parameters); } FilterMapping fmap = new FilterMapping(); fmap.setPathSpecs(urls); fmap.setDispatches(FilterMapping.ALL); fmap.setFilterName(name); handler.getServletHandler().addFilter(holder, fmap); }
@Test public void testConfiguredHttpProxy() throws Exception { File testRepo = createMyModuleRepository("testConfiguredHttpProxy"); File emptyRepo = Files.createTempDirectory("vertx").toFile(); emptyRepo.deleteOnExit(); startRemoteServer(createRemoteServer(testRepo)); System.setProperty(MavenVerticleFactory.HTTP_PROXY_SYS_PROP, "http://localhost:8081"); Server server = new Server(8081); ServletHandler handler = new ServletHandler(); server.setHandler(handler); handler.addServletWithMapping(ProxyServlet.class, "/*").setInitParameter("maxThreads", "10"); URL expectedHost = new URL("http://localhost:8080/"); UrlCollectorFilter urlCollector = new UrlCollectorFilter(); handler.addFilterWithMapping(new FilterHolder(urlCollector), "/*", 0); server.start(); servers.add(server); configureRepos(emptyRepo, "http://localhost:8080/"); vertx.deployVerticle("maven:my:module:1.0::my.serviceA", new DeploymentOptions(), onSuccess(id -> { assertTrue("Was expecting " + urlCollector.requestedHosts + " to contain " + expectedHost, urlCollector.requestedHosts.contains(expectedHost)); testComplete(); })); await(); }
private void initCasSecurity() { FilterHolder authFilter = webapp.addFilter( "org.jasig.cas.client.authentication.AuthenticationFilter", "/*", EnumSet.of(DispatcherType.REQUEST)); authFilter.setInitParameter("casServerLoginUrl", props.getProperty("auth.cas.url") + "/login"); authFilter.setInitParameter("service", props.getProperty("auth.zico.url")); FilterHolder validationFilter = webapp.addFilter( "org.jasig.cas.client.validation.Cas10TicketValidationFilter", "/*", EnumSet.of(DispatcherType.REQUEST) ); validationFilter.setInitParameter("casServerUrlPrefix", props.getProperty("auth.cas.url")); validationFilter.setInitParameter("service", props.getProperty("auth.zico.url")); webapp.addFilter( "org.jasig.cas.client.util.HttpServletRequestWrapperFilter", "/*", EnumSet.of(DispatcherType.REQUEST)); }
/** * Binds a filter into the interface along the specified path. * @param theFilter the filter being bound * @param theRoot the path the filter is being bound to */ public void bind( Filter theFilter, String theRoot ) { Preconditions.checkState( this.getState() == ExecutionLifecycleState.CREATED || this.getState() == ExecutionLifecycleState.STARTING, "Cannot bind a filter to interface '%s' while it is in the '%s' state.", this.getName(), this.getState( ) ); Preconditions.checkNotNull( theFilter, "must provide a filter" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( theRoot ), "need a path to bind to" ); Preconditions.checkArgument( theRoot.startsWith( "/" ), "the path '%s' must be a reference from the root (i.e. start with '/')", theRoot ); logger.info( "Binding filter '{}' on interface '{}' to http path '{}'.", theFilter.getClass().getSimpleName(), this.getName(), theRoot ); String path = theRoot; if( path.endsWith( "/") ) { path = path + "*"; } else if( !path.endsWith( "*" ) ) { path = path + "/*"; } // and properly bind the filter to the context servletContext.addFilter( new FilterHolder( theFilter ), path, EnumSet.allOf( DispatcherType.class ) ); }
protected void execute1(String component) throws Exception { System.out.println("Starting codeine "+component+" at version " + CodeineVersion.get()); injector = Guice.createInjector(getModules(component)); FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class)); ServletContextHandler handler = createServletContextHandler(); handler.setContextPath("/"); FilterHolder crossHolder = new FilterHolder(new CrossOriginFilter()); crossHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET, POST, PUT, DELETE"); crossHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Origin,Content-Type,Accept,api_token"); handler.addFilter(crossHolder, "/api/*", EnumSet.allOf(DispatcherType.class)); handler.addFilter(crossHolder, "/api-with-token/*", EnumSet.allOf(DispatcherType.class)); handler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class)); createAdditionalServlets(handler); ContextHandlerCollection contexts = createFileServerContexts(); contexts.addHandler(handler); int port = startServer(contexts); log.info("jetty started on port " + port); injector.getInstance(CodeineRuntimeInfo.class).setPort(port); execute(); }
public Server build() { ServiceLocator locator = BootstrapUtils.newServiceLocator(); Injector injector = BootstrapUtils.newInjector(locator, Arrays.asList(new ServletModule(), new MyModule())); BootstrapUtils.install(locator); Server server = new Server(port); ResourceConfig config = ResourceConfig.forApplication(new MyApplication()); ServletContainer servletContainer = new ServletContainer(config); ServletHolder sh = new ServletHolder(servletContainer); ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS); context.setContextPath("/"); FilterHolder filterHolder = new FilterHolder(GuiceFilter.class); context.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class)); context.addServlet(sh, "/*"); server.setHandler(context); return server; }
public JettyCrosServer() throws Exception { server = new Server(80); HandlerList handlers = new HandlerList(); ResourceHandler resource_handler = new ResourceHandler(); resource_handler.setDirectoriesListed(true); resource_handler.setWelcomeFiles(new String[] { "index.html" }); resource_handler.setBaseResource(Resource.newClassPathResource("web")); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.setInitParameter("maxInterval", "1000"); context.setInitParameter("logLevel", "2"); handlers.setHandlers(new Handler[] { resource_handler, context}); server.setHandler(handlers); FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter()); filterHolder.getInitParameters().put(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization"); context.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class)); context.addServlet(new ServletHolder(new JsonServlet()), "/t.json"); context.addServlet(new ServletHolder(new DefaultServlet()), "/*"); }
public JettyRamlProxyServer(ServerOptions options, ReportSaver saver, RamlDefinition definition) throws InterruptedException { super(options, saver); final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); final TesterFilter testerFilter = new TesterFilter(this, saver, definition); final ServletHolder servlet; if (options.isMockMode()) { servlet = new ServletHolder(new MockServlet(options.getMockDir())); context.addFilter(new FilterHolder(testerFilter), "/*", EnumSet.allOf(DispatcherType.class)); } else { servlet = new ServletHolder(new JettyProxyServlet(testerFilter)); servlet.setInitParameter("proxyTo", options.getTargetUrl()); servlet.setInitParameter("viaHost", "localhost"); //avoid calling InetAddress.getLocalHost() } servlet.setInitOrder(1); context.addServlet(servlet, "/*"); server = JettyServerProvider.getServer(options.getPort()); server.setHandler(context); server.setStopAtShutdown(true); doStart(); }
public FilterWrapper build() { if (built) { throw new IllegalStateException("This builder can be used to produce one filter wrapper instance. Please create a new builder."); } if (filterClass == null) { throw new IllegalStateException("Cannot build filter wrapper without a filter class"); } if (pathSpecs.isEmpty()) { logger.warn("Filter {} has no pathSpecs, therefore this filter will not handle any requests.", filterClass); } FilterHolder filterHolder = new FilterHolder(filterClass); for (String key : initParams.keySet()) { filterHolder.setInitParameter(key, initParams.get(key)); } built = true; logger.info("Built {}", this); return new FilterWrapper(filterHolder, pathSpecs, dispatcherTypeSet); }
private Server getServer(GuiceFilter filter) { Server server = new Server(PORT); ServletContextHandler servletHandler = new ServletContextHandler(); servletHandler.addServlet(new ServletHolder(new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.setContentType("text/plain"); resp.setContentType("UTF-8"); resp.getWriter().append("404"); } }), "/*"); // add guice servlet filter servletHandler.addFilter(new FilterHolder(filter), "/*", EnumSet.allOf(DispatcherType.class)); server.setHandler(servletHandler); return server; }