Java Code Examples for org.eclipse.jetty.servlet.FilterHolder#setInitParameter()

The following examples show how to use org.eclipse.jetty.servlet.FilterHolder#setInitParameter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebServerModule.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideHeaderFilter() {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      FilterHolder filter = new FilterHolder(new HeaderFilter());
      filter.setInitParameter("headerConfig", "set X-Frame-Options: DENY");
      context.addFilter(filter, "/*", EnumSet.of(
          DispatcherType.FORWARD,
          DispatcherType.REQUEST,
          DispatcherType.INCLUDE,
          DispatcherType.ASYNC,
          DispatcherType.ERROR
      ));
    }
  };
}
 
Example 2
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private void addFiltersAndServletsForRest(final ServletContextHandler root)
{
    FilterHolder loggingFilter = new FilterHolder(new LoggingFilter());
    root.addFilter(loggingFilter, "/api/*", EnumSet.of(DispatcherType.REQUEST));
    root.addFilter(loggingFilter, "/service/*", EnumSet.of(DispatcherType.REQUEST));

    FilterHolder restAuthorizationFilter = new FilterHolder(new AuthenticationCheckFilter());
    restAuthorizationFilter.setInitParameter(AuthenticationCheckFilter.INIT_PARAM_ALLOWED, "/service/sasl");
    root.addFilter(restAuthorizationFilter, "/api/*", EnumSet.of(DispatcherType.REQUEST));
    root.addFilter(restAuthorizationFilter, "/service/*", EnumSet.of(DispatcherType.REQUEST));

    addRestServlet(root);

    ServletHolder queryServlet = new ServletHolder(new BrokerQueryServlet());
    root.addServlet(queryServlet, "/api/latest/querybroker/*");
    root.addServlet(queryServlet, "/api/v" + BrokerModel.MODEL_VERSION + "/querybroker/*");

    ServletHolder vhQueryServlet = new ServletHolder(new VirtualHostQueryServlet());
    root.addServlet(vhQueryServlet, "/api/latest/queryvhost/*");
    root.addServlet(vhQueryServlet, "/api/v" + BrokerModel.MODEL_VERSION + "/queryvhost/*");

    root.addServlet(new ServletHolder(new StructureServlet()), "/service/structure");
    root.addServlet(new ServletHolder(new QueueReportServlet()), "/service/queuereport/*");
    root.addServlet(new ServletHolder(new MetaDataServlet()), "/service/metadata");
    root.addServlet(new ServletHolder(new TimeZoneServlet()), "/service/timezones");
}
 
Example 3
Source File: RESTApp.java    From account-provisioning-for-google-apps with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example 4
Source File: Application.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Register header filter to ServletContextHandler.
 * @param context The serverlet context handler
 */
protected void configureHttpResponsHeaderFilter(ServletContextHandler context) {
  String headerConfig = config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG);
  log.debug("headerConfig : " + headerConfig);
  String[] configs = StringUtil.csvSplit(headerConfig);
  Arrays.stream(configs)
          .forEach(RestConfig::validateHttpResponseHeaderConfig);
  FilterHolder headerFilterHolder = new FilterHolder(HeaderFilter.class);
  headerFilterHolder.setInitParameter("headerConfig", headerConfig);
  context.addFilter(headerFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
}
 
Example 5
Source File: UrlRewriteServletFilterTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private void testSetUp(Map<String,String> initParams ) throws Exception {
  String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();

  server = new ServletTester();
  server.setContextPath( "/" );
  server.getContext().addEventListener( new UrlRewriteServletContextListener() );
  server.getContext().setInitParameter(
      UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );

  FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  setupFilter.setFilter( new SetupFilter() );
  FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  if( initParams != null ) {
    for( Map.Entry<String,String> entry : initParams.entrySet() ) {
      rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
    }
  }
  rewriteFilter.setFilter( new UrlRewriteServletFilter() );

  interactions = new ArrayDeque<>();

  ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
  servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );

  server.start();

  interaction = new MockInteraction();
  request = HttpTester.newRequest();
  response = null;
}
 
Example 6
Source File: UsernameFunctionProcessorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private void testSetup(String username, Map<String,String> initParams ) throws Exception {
  String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();

  Log.setLog( new NoOpLogger() );

  server = new ServletTester();
  server.setContextPath( "/" );
  server.getContext().addEventListener( new UrlRewriteServletContextListener() );
  server.getContext().setInitParameter(
      UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );

  FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  setupFilter.setFilter( new SetupFilter( username ) );
  FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  if( initParams != null ) {
    for( Map.Entry<String,String> entry : initParams.entrySet() ) {
      rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
    }
  }
  rewriteFilter.setFilter( new UrlRewriteServletFilter() );

  interactions = new ArrayDeque<>();

  ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
  servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );

  server.start();

  interaction = new MockInteraction();
  request = HttpTester.newRequest();
  response = null;
}
 
Example 7
Source File: HelloBrotliApplication.java    From jbrotli with Apache License 2.0 5 votes vote down vote up
@Override
  public void run(HelloBrotliConfiguration configuration, Environment environment) {
    final FilterHolder brotliFilterHolder = new FilterHolder(checkNotNull(new BrotliServletFilter()));
    brotliFilterHolder.setName("BrotliCompressionFilter");
    brotliFilterHolder.setInitParameter(BrotliServletFilter.BROTLI_COMPRESSION_PARAMETER_QUALITY, "5");
//    brotliFilterHolder.setInitParameter(BrotliServletFilter.BROTLI_COMPRESSION_PARAMETER_MODE, "GENERIC");
//    brotliFilterHolder.setInitParameter(BrotliServletFilter.BROTLI_COMPRESSION_PARAMETER_LGBLOCK, "0");
//    brotliFilterHolder.setInitParameter(BrotliServletFilter.BROTLI_COMPRESSION_PARAMETER_LGWIN, "22");
    environment.getApplicationContext().getServletHandler().addFilter(brotliFilterHolder);
    brotliFilterHolder.getRegistration().addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

    environment.jersey().register(new HelloBrotliResource());
  }
 
Example 8
Source File: EmbeddedServer.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server with a http port and optional javamelody parameters.
 * @param port Http port
 * @param parameters Optional javamelody parameters
 * @throws Exception e
 */
public static void start(int port, Map<Parameter, String> parameters) throws Exception {
	// Init jetty
	final Server server = new Server(port);
	final ContextHandlerCollection contexts = new ContextHandlerCollection();
	final ServletContextHandler context = new ServletContextHandler(contexts, "/",
			ServletContextHandler.SESSIONS);

	final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter();
	monitoringFilter.setApplicationType("Standalone");
	final FilterHolder filterHolder = new FilterHolder(monitoringFilter);
	if (parameters != null) {
		for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) {
			final net.bull.javamelody.Parameter parameter = entry.getKey();
			final String value = entry.getValue();
			filterHolder.setInitParameter(parameter.getCode(), value);
		}
	}
	context.addFilter(filterHolder, "/*",
			EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));

	final RequestLogHandler requestLogHandler = new RequestLogHandler();
	contexts.addHandler(requestLogHandler);

	final HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] { contexts });
	server.setHandler(handlers);

	server.start();
}
 
Example 9
Source File: EmbeddedServer.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server with a http port and optional javamelody parameters.
 * @param port Http port
 * @param parameters Optional javamelody parameters
 * @throws Exception e
 */
public static void start(int port, Map<Parameter, String> parameters) throws Exception {
	// Init jetty
	server = new Server(port);
	final ContextHandlerCollection contexts = new ContextHandlerCollection();
	final ServletContextHandler context = new ServletContextHandler(contexts, "/",
			ServletContextHandler.SESSIONS);

	final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter();
	monitoringFilter.setApplicationType("Standalone");
	final FilterHolder filterHolder = new FilterHolder(monitoringFilter);
	if (parameters != null) {
		for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) {
			final net.bull.javamelody.Parameter parameter = entry.getKey();
			final String value = entry.getValue();
			filterHolder.setInitParameter(parameter.getCode(), value);
		}
	}
	context.addFilter(filterHolder, "/*",
			EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));

	context.addEventListener(new SessionListener());

	final RequestLogHandler requestLogHandler = new RequestLogHandler();
	contexts.addHandler(requestLogHandler);

	final HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] { contexts });
	server.setHandler(handlers);

	server.start();
}
 
Example 10
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void addFiltersAndServletsForUserInterfaces(final ServletContextHandler root)
{
    root.addFilter(new FilterHolder(new AuthenticationCheckFilter()), "/apidocs/*", EnumSet.of(DispatcherType.REQUEST));
    root.addFilter(new FilterHolder(new InteractiveAuthenticationFilter()), "/index.html", EnumSet.of(DispatcherType.REQUEST));
    root.addFilter(new FilterHolder(new InteractiveAuthenticationFilter()), "/", EnumSet.of(DispatcherType.REQUEST));

    FilterHolder redirectFilter = new FilterHolder(new RedirectFilter());
    redirectFilter.setInitParameter(RedirectFilter.INIT_PARAM_REDIRECT_URI, "/index.html");
    root.addFilter(redirectFilter, "/login.html", EnumSet.of(DispatcherType.REQUEST));

    if (_serveUncompressedDojo)
    {
        root.addFilter(RewriteRequestForUncompressedJavascript.class, "/dojo/dojo/*", EnumSet.of(DispatcherType.REQUEST));
        root.addFilter(RewriteRequestForUncompressedJavascript.class, "/dojo/dojox/*", EnumSet.of(DispatcherType.REQUEST));
    }

    addApiDocsServlets(root);

    root.addServlet(new ServletHolder(new SaslServlet()), "/service/sasl");
    root.addServlet(new ServletHolder(new RootServlet("/", "/apidocs/", "index.html")), "/");
    root.addServlet(new ServletHolder(new LogoutServlet()), "/logout");
    root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDojoPath(), true)), "/dojo/dojo/*");
    root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDijitPath(), true)), "/dojo/dijit/*");
    root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDojoxPath(), true)), "/dojo/dojox/*");
    root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDgridPath(), true)), "/dojo/dgrid/*");
    root.addServlet(new ServletHolder(new FileServlet(DojoHelper.getDstorePath(), true)), "/dojo/dstore/*");

    for (String pattern : STATIC_FILE_TYPES)
    {
        root.addServlet(new ServletHolder(new FileServlet()), pattern);
    }
}
 
Example 11
Source File: JettyManager.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private FilterHolder configureCors() {
	final FilterHolder filter = new FilterHolder(new CrossOriginFilter());
	filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*");
	filter.setInitParameter(ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, valueOf(TRUE));
	filter.setInitParameter(ALLOWED_METHODS_PARAM, on(",").join(HttpMethod.values()));
	filter.setInitParameter(ALLOWED_HEADERS_PARAM,
			on(",").join(X_PING_OTHER, ORIGIN, X_REQUESTED_WITH, CONTENT_TYPE, ACCEPT));
	filter.setInitParameter(PREFLIGHT_MAX_AGE_PARAM, PREFLIGHT_MAX_AGE_VALUE);
	filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, valueOf(TRUE));
	return filter;
}
 
Example 12
Source File: JettyServer.java    From selenium with Apache License 2.0 4 votes vote down vote up
public JettyServer(BaseServerOptions options, HttpHandler handler) {
  this.handler = Require.nonNull("Handler", handler);
  int port = options.getPort() == 0 ? PortProber.findFreePort() : options.getPort();

  String host = options.getHostname().orElseGet(() -> {
    try {
      return new NetworkUtils().getNonLoopbackAddressOfThisMachine();
    } catch (WebDriverException ignored) {
      return "localhost";
    }
  });

  try {
    this.url = new URL("http", host, port, "");
  } catch (MalformedURLException e) {
    throw new UncheckedIOException(e);
  }

  Log.setLog(new JavaUtilLog());
  this.server = new org.eclipse.jetty.server.Server(
      new QueuedThreadPool(options.getMaxServerThreads()));

  this.servletContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
  ConstraintSecurityHandler
      securityHandler =
      (ConstraintSecurityHandler) servletContextHandler.getSecurityHandler();

  Constraint disableTrace = new Constraint();
  disableTrace.setName("Disable TRACE");
  disableTrace.setAuthenticate(true);
  ConstraintMapping disableTraceMapping = new ConstraintMapping();
  disableTraceMapping.setConstraint(disableTrace);
  disableTraceMapping.setMethod("TRACE");
  disableTraceMapping.setPathSpec("/");
  securityHandler.addConstraintMapping(disableTraceMapping);

  Constraint enableOther = new Constraint();
  enableOther.setName("Enable everything but TRACE");
  ConstraintMapping enableOtherMapping = new ConstraintMapping();
  enableOtherMapping.setConstraint(enableOther);
  enableOtherMapping.setMethodOmissions(new String[]{"TRACE"});
  enableOtherMapping.setPathSpec("/");
  securityHandler.addConstraintMapping(enableOtherMapping);

  // Allow CORS: Whether the Selenium server should allow web browser connections from any host
  if (options.getAllowCORS()) {
    FilterHolder
        filterHolder = servletContextHandler.addFilter(CrossOriginFilter.class, "/*", EnumSet
        .of(DispatcherType.REQUEST));
    filterHolder.setInitParameter("allowedMethods", "GET,POST,PUT,DELETE,HEAD");

    // Warning user
    LOG.warning("You have enabled CORS requests from any host. "
                + "Be careful not to visit sites which could maliciously "
                + "try to start Selenium sessions on your machine");
  }

  server.setHandler(servletContextHandler);

  HttpConfiguration httpConfig = new HttpConfiguration();
  httpConfig.setSecureScheme("https");

  ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
  options.getHostname().ifPresent(http::setHost);
  http.setPort(getUrl().getPort());

  http.setIdleTimeout(500000);

  server.setConnectors(new Connector[]{http});
}
 
Example 13
Source File: WebServer.java    From AisAbnormal with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void start() throws Exception {
    ((ServerConnector) server.getConnectors()[0]).setReuseAddress(true);

    // Root context
    context.setContextPath("/abnormal");

    // Setup static content
    context.setResourceBase("src/main/webapp/");
    context.addServlet(DefaultServlet.class, "/");

    // Enable Jersey debug output
    context.setInitParameter("com.sun.jersey.config.statistic.Trace", "true");

    // Enable CORS - cross origin resource sharing
    FilterHolder cors = new FilterHolder();
    cors.setInitParameter("allowedOrigins", "https?://localhost:*, https?://*.e-navigation.net:*");
    cors.setInitParameter("allowedHeaders", "*");
    cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
    cors.setFilter(new CrossOriginFilter());
    context.addFilter(cors, "*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.INCLUDE));

    // Little hack to satisfy OpenLayers URLs in DMA context
    RewritePatternRule openlayersRewriteRule = new RewritePatternRule();
    openlayersRewriteRule.setPattern("/abnormal/theme/*");
    openlayersRewriteRule.setReplacement("/abnormal/js/theme/");

    RewriteHandler rewrite = new RewriteHandler();
    rewrite.setRewriteRequestURI(true);
    rewrite.setRewritePathInfo(false);
    rewrite.setOriginalPathAttribute("requestedPath");
    rewrite.addRule(openlayersRewriteRule);
    rewrite.setHandler(context);
    server.setHandler(rewrite);

    // Setup Guice-Jersey integration
    context.addEventListener(new GuiceServletContextListener() {
        @Override
        protected Injector getInjector() {
            return Guice.createInjector(new RestModule(
                    repositoryName,
                    pathToEventDatabase,
                    eventRepositoryType,
                    eventDataDbHost,
                    eventDataDbPort,
                    eventDataDbName,
                    eventDataDbUsername,
                    eventDataDbPassword
            ));
        }
    });
    context.addFilter(com.google.inject.servlet.GuiceFilter.class, "/rest/*", EnumSet.allOf(DispatcherType.class));

    // Start the server
    server.start();
}
 
Example 14
Source File: HttpManagement.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private Server createServer(Collection<HttpPort<?>> ports)
{
    LOGGER.debug("Starting up web server on {}", ports);

    _jettyServerExecutor = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory("Jetty-Server-Thread"));
    Server server = new Server(new ExecutorThreadPool(_jettyServerExecutor));
    int lastPort = -1;
    for (HttpPort<?> port : ports)
    {
        ServerConnector connector = createConnector(port, server);
        connector.addBean(new ConnectionTrackingListener());
        server.addConnector(connector);
        _portConnectorMap.put(port, connector);
        lastPort = port.getPort();
    }

    ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);
    root.setContextPath("/");
    root.setCompactPath(true);
    server.setHandler(root);

    final ErrorHandler errorHandler = new ErrorHandler()
    {
        @Override
        protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
                throws IOException
        {
            String uri= request.getRequestURI();

            writeErrorPageMessage(request,writer,code,message,uri);

            for (int i= 0; i < 20; i++)
                writer.write("<br/>                                                \n");
        }
    };
    root.setErrorHandler(errorHandler);

    // set servlet context attributes for broker and configuration
    root.getServletContext().setAttribute(HttpManagementUtil.ATTR_BROKER, getBroker());
    root.getServletContext().setAttribute(HttpManagementUtil.ATTR_MANAGEMENT_CONFIGURATION, this);

    root.addFilter(new FilterHolder(new ExceptionHandlingFilter()), "/*", EnumSet.allOf(DispatcherType.class));

    FilterHolder corsFilter = new FilterHolder(new CrossOriginFilter());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, getCorsAllowOrigins());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, Joiner.on(",").join(getCorsAllowMethods()));
    corsFilter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, getCorsAllowHeaders());
    corsFilter.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, String.valueOf(getCorsAllowCredentials()));
    root.addFilter(corsFilter, "/*", EnumSet.of(DispatcherType.REQUEST));

    root.addFilter(new FilterHolder(new ForbiddingTraceFilter()), "/*", EnumSet.of(DispatcherType.REQUEST));

    addFiltersAndServletsForRest(root);
    if (!Boolean.TRUE.equals(getContextValue(Boolean.class, DISABLE_UI_CONTEXT_NAME)))
    {
        addFiltersAndServletsForUserInterfaces(root);
    }

    root.getSessionHandler().getSessionCookieConfig().setName(JSESSIONID_COOKIE_PREFIX + lastPort);
    root.getSessionHandler().getSessionCookieConfig().setHttpOnly(true);
    root.getSessionHandler().setMaxInactiveInterval(getSessionTimeout());

    return server;
}
 
Example 15
Source File: FrontendFunctionProcessorTest.java    From knox with Apache License 2.0 4 votes vote down vote up
private void testSetup(String username, Map<String, String> initParams, Attributes attributes) throws Exception {
  ServiceRegistry mockServiceRegistry = EasyMock.createNiceMock( ServiceRegistry.class );
  EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "NAMENODE" ) ).andReturn( "test-nn-scheme://test-nn-host:411" ).anyTimes();
  EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "JOBTRACKER" ) ).andReturn( "test-jt-scheme://test-jt-host:511" ).anyTimes();

  GatewayServices mockGatewayServices = EasyMock.createNiceMock( GatewayServices.class );
  EasyMock.expect( mockGatewayServices.getService(ServiceType.SERVICE_REGISTRY_SERVICE) ).andReturn( mockServiceRegistry ).anyTimes();

  EasyMock.replay( mockServiceRegistry, mockGatewayServices );

  String descriptorUrl = TestUtils.getResourceUrl( FrontendFunctionProcessorTest.class, "rewrite.xml" ).toExternalForm();

  Log.setLog( new NoOpLogger() );

  server = new ServletTester();
  server.setContextPath( "/" );
  server.getContext().addEventListener( new UrlRewriteServletContextListener() );
  server.getContext().setInitParameter(
      UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );

  if( attributes != null ) {
    server.getContext().setAttributes( attributes );
  }
  server.getContext().setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, "test-cluster" );
  server.getContext().setAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, mockGatewayServices );

  FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  setupFilter.setFilter( new SetupFilter( username ) );
  FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  if( initParams != null ) {
    for( Map.Entry<String,String> entry : initParams.entrySet() ) {
      rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
    }
  }
  rewriteFilter.setFilter( new UrlRewriteServletFilter() );

  interactions = new ArrayDeque<>();

  ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
  servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );

  server.start();

  interaction = new MockInteraction();
  request = HttpTester.newRequest();
  response = null;
}
 
Example 16
Source File: WebServerTools.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Server start(WebServer webServer) throws Exception {

		/**
		 * 更新x_desktop的center指向
		 */
		updateCenterConfigJson();
		/**
		 * 更新 favicon.ico
		 */
		updateFavicon();
		/**
		 * 创建index.html
		 */
		createIndexPage();

		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setMinThreads(WEBSERVER_THREAD_POOL_SIZE_MIN);
		threadPool.setMaxThreads(WEBSERVER_THREAD_POOL_SIZE_MAX);
		Server server = new Server(threadPool);
		if (webServer.getSslEnable()) {
			addHttpsConnector(server, webServer.getPort());
		} else {
			addHttpConnector(server, webServer.getPort());
		}
		WebAppContext context = new WebAppContext();
		context.setContextPath("/");
		context.setBaseResource(Resource.newResource(new File(Config.base(), "servers/webServer")));
		// context.setResourceBase(".");
		context.setParentLoaderPriority(true);
		context.setExtractWAR(false);
		// context.setDefaultsDescriptor(new File(Config.base(),
		// "commons/webdefault_w.xml").getAbsolutePath());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "" + webServer.getDirAllowed());
		context.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
		if (webServer.getCacheControlMaxAge() > 0) {
			context.setInitParameter("org.eclipse.jetty.servlet.Default.cacheControl",
					"max-age=" + webServer.getCacheControlMaxAge());
		}
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCacheSize", "256000000");
		context.setInitParameter("org.eclipse.jetty.servlet.Default.maxCachedFileSize", "200000000");
		context.setWelcomeFiles(new String[] { "default.html", "index.html" });
		context.setGzipHandler(new GzipHandler());
		context.setParentLoaderPriority(true);
		context.getMimeTypes().addMimeMapping("wcss", "application/json");
		/* stat */
		if (webServer.getStatEnable()) {
			FilterHolder statFilterHolder = new FilterHolder(new WebStatFilter());
			statFilterHolder.setInitParameter("exclusions", webServer.getStatExclusions());
			context.addFilter(statFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
			ServletHolder statServletHolder = new ServletHolder(StatViewServlet.class);
			statServletHolder.setInitParameter("sessionStatEnable", "false");
			context.addServlet(statServletHolder, "/druid/*");
		}
		/* stat end */
		server.setHandler(context);
		server.setDumpAfterStart(false);
		server.setDumpBeforeStop(false);
		server.setStopAtShutdown(true);
		server.start();

		context.setMimeTypes(Config.mimeTypes());
		System.out.println("****************************************");
		System.out.println("* web server start completed.");
		System.out.println("* port: " + webServer.getPort() + ".");
		System.out.println("****************************************");
		return server;
	}
 
Example 17
Source File: Application.java    From rest-utils with Apache License 2.0 4 votes vote down vote up
final Handler configureHandler() {
  ResourceConfig resourceConfig = new ResourceConfig();
  configureBaseApplication(resourceConfig, getMetricsTags());
  configureResourceExtensions(resourceConfig);
  setupResources(resourceConfig, getConfiguration());

  // Configure the servlet container
  ServletContainer servletContainer = new ServletContainer(resourceConfig);
  final FilterHolder servletHolder = new FilterHolder(servletContainer);

  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath(path);

  ServletHolder defaultHolder = new ServletHolder("default", DefaultServlet.class);
  defaultHolder.setInitParameter("dirAllowed", "false");

  ResourceCollection staticResources = getStaticResources();
  if (staticResources != null) {
    context.setBaseResource(staticResources);
  }

  configureSecurityHandler(context);

  if (isCorsEnabled()) {
    String allowedOrigins = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);
    filterHolder.setName("cross-origin");
    filterHolder.setInitParameter(
            CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins

    );
    String allowedMethods = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_METHODS);
    String allowedHeaders = config.getString(RestConfig.ACCESS_CONTROL_ALLOW_HEADERS);
    if (allowedMethods != null && !allowedMethods.trim().isEmpty()) {
      filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
    }
    if (allowedHeaders != null && !allowedHeaders.trim().isEmpty()) {
      filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, allowedHeaders);
    }
    // handle preflight cors requests at the filter level, do not forward down the filter chain
    filterHolder.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, "false");
    context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
  }

  if (config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG) != null
          && !config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG).isEmpty()) {
    configureHttpResponsHeaderFilter(context);
  }

  configurePreResourceHandling(context);
  context.addFilter(servletHolder, "/*", null);
  configurePostResourceHandling(context);
  context.addServlet(defaultHolder, "/*");

  applyCustomConfiguration(context, REST_SERVLET_INITIALIZERS_CLASSES_CONFIG);

  RequestLogHandler requestLogHandler = new RequestLogHandler();
  requestLogHandler.setRequestLog(requestLog);

  HandlerCollection handlers = new HandlerCollection();
  handlers.setHandlers(new Handler[]{context, requestLogHandler});

  return handlers;
}
 
Example 18
Source File: RestServer.java    From DataLink with Apache License 2.0 4 votes vote down vote up
public void start() {
        log.info("Starting REST server");
        ResourceConfig resourceConfig = new ResourceConfig();
        resourceConfig.register(DataxResource.class);

        ServletContainer servletContainer = new ServletContainer(resourceConfig);
        ServletHolder servletHolder = new ServletHolder(servletContainer);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.addServlet(servletHolder, "/*");

        String allowedOrigins = System.getProperty(ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
        if (allowedOrigins != null && !allowedOrigins.trim().isEmpty()) {
            FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
            filterHolder.setName("cross-origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins);
        String allowedMethods = System.getProperty(ACCESS_CONTROL_ALLOW_METHODS_CONFIG);
        if (allowedMethods != null && !allowedOrigins.trim().isEmpty()) {
            filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
        }
            context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setLoggerName(RestServer.class.getCanonicalName());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);


    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{context, new DefaultHandler(), requestLogHandler});

    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);

    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new RuntimeException("Unable to start REST server", e);
    }

    log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl());
}
 
Example 19
Source File: WebServer.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * Start the web server including setup.
 */
public void start() throws Exception {
  if (!config.getBoolean(ExecConstants.HTTP_ENABLE)) {
    return;
  }

  final boolean authEnabled = config.getBoolean(ExecConstants.USER_AUTHENTICATION_ENABLED);

  int port = config.getInt(ExecConstants.HTTP_PORT);
  final boolean portHunt = config.getBoolean(ExecConstants.HTTP_PORT_HUNT);
  final int acceptors = config.getInt(ExecConstants.HTTP_JETTY_SERVER_ACCEPTORS);
  final int selectors = config.getInt(ExecConstants.HTTP_JETTY_SERVER_SELECTORS);
  final int handlers = config.getInt(ExecConstants.HTTP_JETTY_SERVER_HANDLERS);
  final QueuedThreadPool threadPool = new QueuedThreadPool(2, 2);
  embeddedJetty = new Server(threadPool);
  ServletContextHandler webServerContext = createServletContextHandler(authEnabled);
  //Allow for Other Drillbits to make REST calls
  FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);
  filterHolder.setInitParameter("allowedOrigins", "*");
  //Allowing CORS for metrics only
  webServerContext.addFilter(filterHolder, STATUS_METRICS_PATH, null);
  embeddedJetty.setHandler(webServerContext);

  ServerConnector connector = createConnector(port, acceptors, selectors);
  threadPool.setMaxThreads(handlers + connector.getAcceptors() + connector.getSelectorManager().getSelectorCount());
  embeddedJetty.addConnector(connector);
  for (int retry = 0; retry < PORT_HUNT_TRIES; retry++) {
    connector.setPort(port);
    try {
      embeddedJetty.start();
      return;
    } catch (IOException e) {
      if (portHunt) {
        logger.info("Failed to start on port {}, trying port {}", port, ++port, e);
      } else {
        throw e;
      }
    }
  }
  throw new IOException("Failed to find a port");
}
 
Example 20
Source File: WebDAVServer.java    From MtgDesktopCompanion with GNU General Public License v3.0 3 votes vote down vote up
@Override
public void start() throws IOException {
	server = new Server(getInt(SERVER_PORT));
	
	
	log = getString(LOGIN);
	pas = getString(PASS);
	
	
	ServletContextHandler ctx = new ServletContextHandler(ServletContextHandler.SESSIONS);
	ctx.setContextPath("/");
	
	ServletHandler handler = new ServletHandler();
	
	ctx.addServlet(new ServletHolder("default", new MiltonServlet()),"/");
	
	
	FilterHolder fh = handler.addFilterWithMapping(MiltonFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
				 fh.setInitParameter("resource.factory.class", WebDavMTGResourceFactory.class.getCanonicalName());
				 

	ctx.addFilter(fh, "/*", EnumSet.of(DispatcherType.REQUEST));
				 
	logger.trace(ctx.dump());

	ctx.setHandler(handler);
	server.setHandler(ctx);
	
	try {
		server.start();
		logger.info("Webdav start on port http://"+InetAddress.getLocalHost().getHostName() + ":"+getInt(SERVER_PORT));

	} catch (Exception e) {
		throw new IOException(e);
	}
}