org.eclipse.jetty.servlets.CrossOriginFilter Java Examples

The following examples show how to use org.eclipse.jetty.servlets.CrossOriginFilter. 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: CrossOriginHandlerTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
private void testHandlesCrossOriginRequest(String domains, boolean wantHandled) throws Exception {
    final CrossOriginHandler victim = new CrossOriginHandler(domains, "GET,POST,HEAD", "X-Requested-With,Content-Type,Accept,Origin", "1800", "true", "");
    final MockJettyRequest req = mock(MockJettyRequest.class);
    final MockJettyResponse res = mock(MockJettyResponse.class);

    when(req.getMethod()).thenReturn("OPTIONS");
    when(req.getHeader("Origin")).thenReturn("betfair.com");
    when(req.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER)).thenReturn("PUT");
    when(req.getHeaders("Connection")).thenReturn(Collections.<String>emptyEnumeration());

    victim.handle("/", req, req, res);

    // this is always called
    verify(req, times(1)).setHandled(eq(true));
    if (wantHandled) {
        verify(req, never()).setHandled(eq(false));
    }
    else {
        verify(req, times(1)).setHandled(eq(false));
    }
}
 
Example #2
Source File: FoxtrotServer.java    From foxtrot with Apache License 2.0 6 votes vote down vote up
@Override
public void run(FoxtrotServerConfiguration configuration, Environment environment) throws Exception {
    // Enable CORS headers
    final FilterRegistration.Dynamic cors = environment.servlets()
            .addFilter("CORS", CrossOriginFilter.class);

    // Configure CORS parameters
    cors.setInitParameter("allowedOrigins", "*");
    cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
    cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    // Add URL mapping
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");

    ((AbstractServerFactory)configuration.getServerFactory()).setJerseyRootPath("/foxtrot");

    MetricUtil.setup(environment.metrics());
    ElasticsearchUtils.setTableNamePrefix(configuration.getElasticsearch());

}
 
Example #3
Source File: TestHttpAccessControl.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void testCORSGetRequest(String userInfoURI) throws Exception {
  HttpAuthenticationFeature authenticationFeature = HttpAuthenticationFeature.basic("admin", "admin");
  Response response = ClientBuilder.newClient()
      .target(userInfoURI)
      .register(authenticationFeature)
      .request()
      .header("Origin", "http://example.com")
      .header("Access-Control-Request-Method", "GET")
      .get();

  Assert.assertEquals(200, response.getStatus());

  MultivaluedMap<String, Object> responseHeader = response.getHeaders();

  List<Object> allowOriginHeader = responseHeader.get(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER);
  Assert.assertNotNull(allowOriginHeader);
  Assert.assertEquals(1, allowOriginHeader.size());
  Assert.assertEquals("http://example.com", allowOriginHeader.get(0));
}
 
Example #4
Source File: WebServerModule.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@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));
    }
  };
}
 
Example #5
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 #6
Source File: SoaBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
private void checkCorsFilter(SoaConfiguration configuration, ServletEnvironment servlets)
{
    if ( configuration.isAddCorsFilter() )
    {
        // from http://jitterted.com/tidbits/2014/09/12/cors-for-dropwizard-0-7-x/

        FilterRegistration.Dynamic filter = servlets.addFilter("CORS", CrossOriginFilter.class);
        filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
        filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
        filter.setInitParameter("allowCredentials", "true");
    }
}
 
Example #7
Source File: CrossOriginHandler.java    From cougar with Apache License 2.0 5 votes vote down vote up
/**
    * See {@link org.eclipse.jetty.servlets.CrossOriginFilter} for more information on these arguments.
    */
public CrossOriginHandler(final String allowedOrigins, final String allowedMethods, final String allowedHeaders,
                             final String preflightMaxAge, final String allowCredentials, final String exposedHeaders)
           throws ServletException {

	this.crossOriginFilter = new CrossOriginFilter();
	this.crossOriginFilter.init(new FilterConfig() {

           @Override
           public String getFilterName() {
               return "crossOriginFilter";
           }

           @Override
           public String getInitParameter(String name) {
               if (CrossOriginFilter.ALLOWED_ORIGINS_PARAM.equals(name)) return allowedOrigins;
               if (CrossOriginFilter.ALLOWED_METHODS_PARAM.equals(name)) return allowedMethods;
               if (CrossOriginFilter.ALLOWED_HEADERS_PARAM.equals(name)) return allowedHeaders;
               if (CrossOriginFilter.PREFLIGHT_MAX_AGE_PARAM.equals(name)) return preflightMaxAge;
               if (CrossOriginFilter.ALLOW_CREDENTIALS_PARAM.equals(name)) return allowCredentials;
               if (CrossOriginFilter.EXPOSED_HEADERS_PARAM.equals(name)) return exposedHeaders;
               if (CrossOriginFilter.CHAIN_PREFLIGHT_PARAM.equals(name)) return "false";
               return null;
           }

           @Override
           public Enumeration getInitParameterNames() {
               return null;
           }

           @Override
           public ServletContext getServletContext() {
               return null;
           }
       });
}
 
Example #8
Source File: OrderApplication.java    From bookstore-cqrs-example with Apache License 2.0 5 votes vote down vote up
private void configureCors(Environment environment) {
  FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
  filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
  filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
  filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
  filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
  filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
  filter.setInitParameter("allowCredentials", "true");
}
 
Example #9
Source File: ProductCatalogApplication.java    From bookstore-cqrs-example with Apache License 2.0 5 votes vote down vote up
private void configureCors(Environment environment) {
  FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
  filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
  filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
  filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
  filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
  filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
  filter.setInitParameter("allowCredentials", "true");
}
 
Example #10
Source File: MainApplication.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
void configureCors(Environment environment) {
  final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class);

  // Configure CORS parameters
  cors.setInitParameter("allowedOrigins", "*");
  cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
  cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

  // Add URL mapping
  cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
 
Example #11
Source File: NewtsService.java    From newts with Apache License 2.0 5 votes vote down vote up
private void configureCors(Environment environment) {
    Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
    filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
    filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
    filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
    filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
    filter.setInitParameter("allowCredentials", "true");
}
 
Example #12
Source File: TestHttpAccessControl.java    From datacollector with Apache License 2.0 5 votes vote down vote up
/**
 * Browser "pre flighted" requests first send an HTTP request by the 'OPTIONS' method to the resource on the other
 * domain, in order to determine whether the actual request is safe to send.
 *
 * No authentication required for OPTIONS method
 *
 * @param userInfoURI URI
 */
private void testPreFlightRequest(String userInfoURI) {
  Response response = ClientBuilder
      .newClient()
      .target(userInfoURI)
      .request()
      .options();

  Assert.assertEquals(200, response.getStatus());

  MultivaluedMap<String, Object> responseHeader = response.getHeaders();

  List<Object> allowOriginHeader = responseHeader.get(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER);
  Assert.assertNotNull(allowOriginHeader);
  Assert.assertEquals(1, allowOriginHeader.size());
  Assert.assertEquals(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_ORIGIN_DEFAULT, allowOriginHeader.get(0));


  List<Object> allowHeadersHeader = responseHeader.get(CrossOriginFilter.ACCESS_CONTROL_ALLOW_HEADERS_HEADER);
  Assert.assertNotNull(allowHeadersHeader);
  Assert.assertEquals(1, allowHeadersHeader.size());
  Assert.assertEquals(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_HEADERS_DEFAULT, allowHeadersHeader.get(0));

  List<Object> allowMethodsHeader = responseHeader.get(CrossOriginFilter.ACCESS_CONTROL_ALLOW_METHODS_HEADER);
  Assert.assertNotNull(allowMethodsHeader);
  Assert.assertEquals(1, allowMethodsHeader.size());
  Assert.assertEquals(CORSConstants.HTTP_ACCESS_CONTROL_ALLOW_METHODS_DEFAULT, allowMethodsHeader.get(0));
}
 
Example #13
Source File: StreamlineApplication.java    From streamline with Apache License 2.0 5 votes vote down vote up
private void enableCORS(Environment environment, List<String> urlPatterns) {
    // Enable CORS headers
    final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class);

    // Configure CORS parameters
    cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Authorization,Content-Type,Accept,Origin");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    // Add URL mapping
    String[] urls = urlPatterns.toArray(new String[urlPatterns.size()]);
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, urls);
}
 
Example #14
Source File: CrossOriginConstraintSecurityHandler.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
private static boolean isPreFlightRequest(Request request) {
    if(HttpMethods.OPTIONS.equalsIgnoreCase(request.getMethod())) {
        // If the origin does not match allowed the filter will skip anyway so don't bother checking it.
        if(request.getHeader(ORIGIN_HEADER) != null &&
           request.getHeader(CrossOriginFilter.ACCESS_CONTROL_REQUEST_METHOD_HEADER) != null) {
            return true;
        }
    }
    return false;
}
 
Example #15
Source File: HttpConductorImpl.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addCrossOriginFilter(ContextHandler handler) throws ServletException {
    FilterRegistration reg = handler.getServletContext().addFilter("CrossOriginFilter", CrossOriginFilter.class);
    reg.addMappingForServletNames(null, false, "*");
    reg.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM,
                         configurationService.getProperty(CONFIG_XORIGIN_ORIGINS));
    reg.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM,
                         configurationService.getProperty(CONFIG_XORIGIN_METHODS));
    reg.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM,
                         configurationService.getProperty(CONFIG_XORIGIN_HEADERS));
    reg.setInitParameter(CrossOriginFilter.PREFLIGHT_MAX_AGE_PARAM,
                         configurationService.getProperty(CONFIG_XORIGIN_MAX_AGE));
    reg.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM,
                         configurationService.getProperty(CONFIG_XORIGIN_CREDENTIALS));
}
 
Example #16
Source File: BlockExplorerApp.java    From fabric-api with Apache License 2.0 5 votes vote down vote up
@Override
public void run(BlockExplorerConfiguration configuration, Environment environment) throws Exception {
    BCSAPI api = hyperLedgerBundle.getBCSAPI();
    final FilterRegistration.Dynamic cors =
            environment.servlets().addFilter("CORS", CrossOriginFilter.class);

    // Configure CORS parameters
    cors.setInitParameter("allowedOrigins", "*");
    cors.setInitParameter("allowedHeaders", "*");
    cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    // Add URL mapping
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    environment.jersey().register(new ExplorerResource(api));
}
 
Example #17
Source File: HelloWorldApplication.java    From dropwizard-graphql with Apache License 2.0 5 votes vote down vote up
@Override
public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {

  // Enable CORS to allow GraphiQL on a separate port to reach the API
  final FilterRegistration.Dynamic cors =
      environment.servlets().addFilter("cors", CrossOriginFilter.class);
  cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");

  final HelloWorldResource resource =
      new HelloWorldResource(configuration.getTemplate(), configuration.getDefaultName());
  environment.jersey().register(resource);
}
 
Example #18
Source File: RegistryApplication.java    From registry with Apache License 2.0 5 votes vote down vote up
private void enableCORS(Environment environment) {
    // Enable CORS headers
    final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class);

    // Configure CORS parameters
    cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Authorization,Content-Type,Accept,Origin");
    cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    // Add URL mapping
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
 
Example #19
Source File: BlockExplorerApp.java    From fabric-api-archive with Apache License 2.0 5 votes vote down vote up
@Override
public void run(BlockExplorerConfiguration configuration, Environment environment) throws Exception {
    BCSAPI api = hyperLedgerBundle.getBCSAPI();
    final FilterRegistration.Dynamic cors =
            environment.servlets().addFilter("CORS", CrossOriginFilter.class);

    // Configure CORS parameters
    cors.setInitParameter("allowedOrigins", "*");
    cors.setInitParameter("allowedHeaders", "*");
    cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    // Add URL mapping
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    environment.jersey().register(new ExplorerResource(api));
}
 
Example #20
Source File: InventoryItemApi.java    From cqrs-eventsourcing-kafka with Apache License 2.0 5 votes vote down vote up
private void configureSwagger(Environment environment) {
    BeanConfig config = new BeanConfig();
    config.setTitle("Inventory Item API");
    config.setVersion("1.0.0");
    config.setResourcePackage(InventoryItemResource.class.getPackage().getName());
    config.setScan(true);

    FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORSFilter", CrossOriginFilter.class);
    filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() + "swagger.json");
    filter.setInitParameter(ALLOWED_METHODS_PARAM, "GET,OPTIONS");
    filter.setInitParameter(ALLOWED_HEADERS_PARAM, "Origin, Content-Type, Accept");
    filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*");
    filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, "true");
}
 
Example #21
Source File: CorsBundle.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final BaragonAgentConfiguration config, final Environment environment) {
  if (!config.isEnableCorsFilter()) {
    return;
  }

  final Filter corsFilter = new CrossOriginFilter();
  final FilterConfig corsFilterConfig = new FilterConfig() {

    @Override
    public String getFilterName() {
      return FILTER_NAME;
    }

    @Override
    public ServletContext getServletContext() {
      return null;
    }

    @Override
    public String getInitParameter(final String name) {
      return null;
    }

    @Override
    public Enumeration<String> getInitParameterNames() {
      return Iterators.asEnumeration(Collections.<String>emptyIterator());
    }
  };

  try {
    corsFilter.init(corsFilterConfig);
  } catch (final Exception e) {
    throw Throwables.propagate(e);
  }

  environment.servlets().addFilter(FILTER_NAME, corsFilter).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
 
Example #22
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 #23
Source File: CorsBundle.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final BaragonConfiguration config, final Environment environment) {
  if (!config.isEnableCorsFilter()) {
    return;
  }

  final Filter corsFilter = new CrossOriginFilter();
  final FilterConfig corsFilterConfig = new FilterConfig() {

    @Override
    public String getFilterName() {
      return FILTER_NAME;
    }

    @Override
    public ServletContext getServletContext() {
      return null;
    }

    @Override
    public String getInitParameter(final String name) {
      return null;
    }

    @Override
    public Enumeration<String> getInitParameterNames() {
      return Iterators.asEnumeration(Collections.<String>emptyIterator());
    }
  };

  try {
    corsFilter.init(corsFilterConfig);
  } catch (final Exception e) {
    throw Throwables.propagate(e);
  }

  environment.servlets().addFilter(FILTER_NAME, corsFilter).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
 
Example #24
Source File: SnowizardApplication.java    From snowizard with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void run(final SnowizardConfiguration config,
        final Environment environment) throws Exception {

    environment.jersey().register(new SnowizardExceptionMapper());
    environment.jersey().register(new ProtocolBufferMessageBodyProvider());

    if (config.isCORSEnabled()) {
        final FilterRegistration.Dynamic filter = environment.servlets()
                .addFilter("CrossOriginFilter", CrossOriginFilter.class);
        filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),
                true, "/*");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM,
                "GET");
    }

    final IdWorker worker = new IdWorker(config.getWorkerId(),
            config.getDatacenterId(), 0L, config.validateUserAgent(),
            environment.metrics());

    environment.metrics().register(
            MetricRegistry.name(SnowizardApplication.class, "worker_id"),
            new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return config.getWorkerId();
                }
            });

    environment.metrics()
    .register(
            MetricRegistry.name(SnowizardApplication.class,
                    "datacenter_id"), new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return config.getDatacenterId();
                }
            });

    // health check
    environment.healthChecks().register("empty", new EmptyHealthCheck());

    // resources
    environment.jersey().register(new IdResource(worker));
    environment.jersey().register(new PingResource());
    environment.jersey().register(new VersionResource());
}
 
Example #25
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 #26
Source File: ImageJServer.java    From imagej-server with Apache License 2.0 4 votes vote down vote up
@Override
public void run(final ImageJServerConfiguration configuration,
	final Environment environment)
{
	// Enable CORS headers
	final FilterRegistration.Dynamic cors = environment.servlets().addFilter(
		"CORS", CrossOriginFilter.class);

	// Configure CORS parameters
	cors.setInitParameter("allowedOrigins", "*");
	cors.setInitParameter("allowedHeaders",
		"X-Requested-With,Content-Type,Accept,Origin");
	cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

	// Add URL mapping
	cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true,
		"/*");

	env = environment;

	// NB: not implemented yet
	final ImageJServerHealthCheck healthCheck = new ImageJServerHealthCheck();
	environment.healthChecks().register("imagej-server", healthCheck);

	environment.jersey().register(MultiPartFeature.class);

	// -- resources --

	environment.jersey().register(AdminResource.class);

	environment.jersey().register(ModulesResource.class);

	environment.jersey().register(ObjectsResource.class);

	// -- context dependencies injection --

	environment.jersey().register(new AbstractBinder() {

		@Override
		protected void configure() {
			bind(ctx).to(Context.class);
			bind(env).to(Environment.class);
			bind(objectService).to(ObjectService.class);
			bind(jsonService).to(JsonService.class);
		}

	});
}
 
Example #27
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 #28
Source File: CorsBundle.java    From Singularity with Apache License 2.0 4 votes vote down vote up
@Override
public void run(final SingularityConfiguration config, final Environment environment) {
  CorsConfiguration corsConfiguration = config.getCors();
  if (!config.isEnableCorsFilter() && !corsConfiguration.isEnabled()) {
    return;
  }

  final Filter corsFilter = new CrossOriginFilter();
  final FilterConfig corsFilterConfig = new FilterConfig() {

    @Override
    public String getFilterName() {
      return FILTER_NAME;
    }

    @Override
    public ServletContext getServletContext() {
      return null;
    }

    @Override
    public String getInitParameter(final String name) {
      return null;
    }

    @Override
    public Enumeration<String> getInitParameterNames() {
      return Iterators.asEnumeration(Collections.<String>emptyIterator());
    }
  };

  try {
    corsFilter.init(corsFilterConfig);
  } catch (final Exception e) {
    throw new RuntimeException(e);
  }

  FilterRegistration.Dynamic filter = environment
    .servlets()
    .addFilter(FILTER_NAME, corsFilter);

  filter.setInitParameter(
    CrossOriginFilter.ALLOWED_ORIGINS_PARAM,
    corsConfiguration.getAllowedOrigins()
  );
  filter.setInitParameter(
    CrossOriginFilter.ALLOWED_HEADERS_PARAM,
    corsConfiguration.getAllowedHeaders()
  );
  filter.setInitParameter(
    CrossOriginFilter.ALLOWED_METHODS_PARAM,
    corsConfiguration.getAllowedMethods()
  );
  filter.setInitParameter(
    CrossOriginFilter.ALLOW_CREDENTIALS_PARAM,
    corsConfiguration.isAllowCredentials() ? "true" : "false"
  );

  filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
}
 
Example #29
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 #30
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;
}