List of usage examples for javax.servlet FilterRegistration.Dynamic setInitParameter
public boolean setInitParameter(String name, String value);
From source file:com.hortonworks.streamline.webservice.StreamlineApplication.java
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); }
From source file:com.devnexus.ting.web.WebAppInitializer.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.setInitParameter("javax.servlet.jsp.jstl.fmt.localizationContext", "messages"); //UrlRewriteFilter final FilterRegistration.Dynamic urlRewriteFilterRegistration = servletContext.addFilter("UrlRewriteFilter", new UrlRewriteFilter()); urlRewriteFilterRegistration.setAsyncSupported(true); urlRewriteFilterRegistration.addMappingForUrlPatterns(null, true, "/proxy/*"); // UTF-8 Encoding FilterRegistration.Dynamic encodingFilterRegistration = servletContext.addFilter("encodingFilter", new CharacterEncodingFilter()); encodingFilterRegistration.setInitParameter("encoding", "UTF-8"); encodingFilterRegistration.setInitParameter("forceEncoding", "true"); encodingFilterRegistration.addMappingForUrlPatterns(null, true, "/s/*"); FilterRegistration.Dynamic gzipFilterRegistration = servletContext.addFilter("gzipFilter", CompressingFilter.class); gzipFilterRegistration.addMappingForUrlPatterns(null, true, "/s/*", "*.html", "/api/*"); // jsonPRequestFilter FilterRegistration.Dynamic jsonPRequestFilterRegistration = servletContext.addFilter("JSONPRequestFilter", JSONPRequestFilter.class); jsonPRequestFilterRegistration.addMappingForUrlPatterns(null, true, "*.json"); // lazyLoadingFilter FilterRegistration.Dynamic lazyLoadingFilterRegistration = servletContext.addFilter("lazyLoadingFilter", OpenEntityManagerInViewFilter.class); lazyLoadingFilterRegistration.addMappingForUrlPatterns(null, true, "*.html", "/s/*"); // springSecurityFilterChain FilterRegistration.Dynamic springSecurityFilterChainRegistration = servletContext .addFilter("springSecurityFilterChain", DelegatingFilterProxy.class); springSecurityFilterChainRegistration.addMappingForUrlPatterns(null, true, "/*"); // loggingFilter4Logback FilterRegistration.Dynamic loggingFilter4LogbackRegistration = servletContext .addFilter("loggingFilter4Logback", LoggingFilter4Logback.class); loggingFilter4LogbackRegistration.addMappingForUrlPatterns(null, true, "/s/*", "/api/*"); // etagFilter FilterRegistration.Dynamic etagFilterRegistration = servletContext.addFilter("etagFilter", ShallowEtagHeaderFilter.class); etagFilterRegistration.addMappingForUrlPatterns(null, true, "/s/*"); // sitemeshFilter FilterRegistration.Dynamic sitemeshRegistration = servletContext.addFilter("sitemesh", ConfigurableSiteMeshFilter.class); sitemeshRegistration.addMappingForUrlPatterns(null, true, "/s/*", "/index.jsp"); // responseAddHttpHeadersFilter FilterRegistration.Dynamic responseAddHttpHeadersFilterRegistration = servletContext .addFilter("responseAddHttpHeadersFilter", ResponseAddHttpHeadersFilter.class); responseAddHttpHeadersFilterRegistration.setInitParameter("secondsToCache", "2592000"); responseAddHttpHeadersFilterRegistration.addMappingForUrlPatterns(null, true, "*.css", "*.gif", "*.ico", "*.jpg", "*.png", "*.js"); setupContext(servletContext);// w w w.j a va2 s . c o m super.onStartup(servletContext); }
From source file:com.spotify.reaper.ReaperApplication.java
@Override public void run(ReaperApplicationConfiguration config, Environment environment) throws Exception { // Using UTC times everywhere as default. Affects only Yoda time. DateTimeZone.setDefault(DateTimeZone.UTC); checkConfiguration(config);/*from w w w. ja va2 s . co m*/ context.config = config; addSignalHandlers(); // SIGHUP, etc. LOG.info("initializing runner thread pool with {} threads", config.getRepairRunThreadCount()); context.repairManager = new RepairManager(); context.repairManager.initializeThreadPool(config.getRepairRunThreadCount(), config.getHangingRepairTimeoutMins(), TimeUnit.MINUTES, 30, TimeUnit.SECONDS); if (context.storage == null) { LOG.info("initializing storage of type: {}", config.getStorageType()); context.storage = initializeStorage(config, environment); } else { LOG.info("storage already given in context, not initializing a new one"); } if (context.jmxConnectionFactory == null) { LOG.info("no JMX connection factory given in context, creating default"); context.jmxConnectionFactory = new JmxConnectionFactory(); } // read jmx host/port mapping from config and provide to jmx con.factory Map<String, Integer> jmxPorts = config.getJmxPorts(); if (jmxPorts != null) { LOG.debug("using JMX ports mapping: {}", jmxPorts); context.jmxConnectionFactory.setJmxPorts(jmxPorts); } // Enable cross-origin requests for using external GUI applications. if (config.isEnableCrossOrigin() || System.getProperty("enableCrossOrigin") != null) { final FilterRegistration.Dynamic cors = environment.servlets().addFilter("crossOriginRequests", CrossOriginFilter.class); cors.setInitParameter("allowedOrigins", "*"); cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin"); cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD"); cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); } JmxCredentials jmxAuth = config.getJmxAuth(); if (jmxAuth != null) { LOG.debug("using specified JMX credentials for authentication"); context.jmxConnectionFactory.setJmxAuth(jmxAuth); } LOG.info("creating and registering health checks"); // Notice that health checks are registered under the admin application on /healthcheck final ReaperHealthCheck healthCheck = new ReaperHealthCheck(context); environment.healthChecks().register("reaper", healthCheck); LOG.info("creating resources and registering endpoints"); final PingResource pingResource = new PingResource(); environment.jersey().register(pingResource); final ClusterResource addClusterResource = new ClusterResource(context); environment.jersey().register(addClusterResource); final RepairRunResource addRepairRunResource = new RepairRunResource(context); environment.jersey().register(addRepairRunResource); final RepairScheduleResource addRepairScheduleResource = new RepairScheduleResource(context); environment.jersey().register(addRepairScheduleResource); Thread.sleep(1000); SchedulingManager.start(context); if (config.hasAutoSchedulingEnabled()) { LOG.debug("using specified configuration for auto scheduling: {}", config.getAutoScheduling()); AutoSchedulingManager.start(context); } LOG.info("resuming pending repair runs"); context.repairManager.resumeRunningRepairRuns(context); }
From source file:be.wolkmaan.klimtoren.web.config.WebAppInitializer.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { // Create the root appcontext AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(RootConfig.class); rootContext.register(PersistenceConfig.class); // Manage the lifecycle of the root appcontext servletContext.addListener(new ContextLoaderListener(rootContext)); servletContext.setInitParameter("defaultHtmlEscape", "true"); this.zkLoaderServlet(servletContext); // now the config for the Dispatcher servlet AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext(); mvcContext.register(WebMvcConfig.class); // Filters//from ww w.j a v a2 s . c o m // http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/filter/package-summary.html // Enables support for DELETE and PUT request methods with web browser // clients // http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/filter/HiddenHttpMethodFilter.html FilterRegistration.Dynamic fr = servletContext.addFilter("hiddenHttpMethodFilter", new HiddenHttpMethodFilter()); fr.addMappingForUrlPatterns(null, true, "/*"); fr = servletContext.addFilter("encodingFilter", new CharacterEncodingFilter()); fr.setInitParameter("encoding", "UTF-8"); fr.setInitParameter("forceEncoding", "true"); fr.addMappingForUrlPatterns(null, true, "/*"); // The main Spring MVC servlet. ServletRegistration.Dynamic appServlet = servletContext.addServlet("appServlet", new DispatcherServlet(mvcContext)); appServlet.setLoadOnStartup(2); Set<String> mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { for (String s : mappingConflicts) { logger.error("Mapping conflict: " + s); } throw new IllegalStateException("'appServlet' cannot be mapped to '/' under Tomcat versions <= 7.0.14"); } HttpSessionListener zkCleanUp = new HttpSessionListener(); servletContext.addListener(zkCleanUp); this.logbackServlet(servletContext); this.zkUpdateServlet(servletContext); }
From source file:io.paradoxical.cassieq.ServiceConfigurator.java
private void enableCors(ServiceConfiguration config, Environment environment) { FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() + "*"); filter.setInitParameter("allowedOrigins", String.join(",", config.getWeb().getAllowedOrigins())); // allowed origins comma separated filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin"); filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS"); }
From source file:com.srotya.tau.api.ApplicationManager.java
@Override public void run(AppConfig configuration, Environment environment) throws Exception { this.configuration = configuration; init(configuration);// w w w. j a va 2 s. c om environment.jersey().property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, false); environment.jersey().register(ValidationFeature.class); if (configuration.isEnableAuthorization()) { environment.jersey().register(new BapiAuthorizationFilter()); environment.jersey().register(RolesAllowedDynamicFeature.class); } configureIgnite(configuration, environment); perfMonitor = new PerformanceMonitor(this); environment.lifecycle().manage(perfMonitor); alertReceiver = new EventViewer(this); environment.lifecycle().manage(alertReceiver); environment.jersey().register(new RulesEndpoint(this)); environment.jersey().register(new RuleGroupEndpoint(this)); environment.jersey().register(new TemplateEndpoint(this)); environment.jersey().register(new RestReceiver(this)); environment.jersey().register(new PerfMonEndpoint(this)); environment.healthChecks().register("dbHC", new DBHealthCheck(this)); 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, "/*"); }
From source file:com.techtrip.dynbl.context.config.WebAppinitializer.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { // Setup Context to Accept Annotated Classes on Input (including plain Spring {@code @Component} // Stereotypes in addition to JSR-330 Compliant Classes using {@code javax.inject} AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); //context.setConfigLocation(APP_CONFIG_LOCATION); context.setConfigLocation(APP_CONFIG_LOCATION); /* /*w w w . j a v a 2 s . c o m*/ * Add a Spring Security Filter using the JEE6 Filter Registration Filter Method from {@code FilterRegistration) that allows filters to be registered * and configured with the specified context */ /* FilterRegistration.Dynamic securityFilter = servletContext.addFilter(ProjectKeyValConsts.SECURITY_FILTER.getKey(), new DelegatingFilterProxy(ProjectKeyValConsts.SECURITY_FILTER.getValue())); securityFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, ProjectConsts.BASE_URL_MAPPING_PATTERN.getValue()); // where the filter will be applied */ // Add a Character Encoding Filter that specifies an encoding for mapped requests FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter()); characterEncodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, ROOT_CONTEXT); // where the filter will be applied characterEncodingFilter.setInitParameter("encoding", "UTF-8"); characterEncodingFilter.setInitParameter("forceEncoding", Boolean.TRUE.toString()); characterEncodingFilter.setAsyncSupported(true); servletContext.addListener(new ContextLoaderListener(context)); servletContext.setInitParameter("defaultHtmlEscape", Boolean.TRUE.toString()); DispatcherServlet servlet = new DispatcherServlet(); // no explicit configuration reference here: everything is configured in the root container for simplicity servlet.setContextConfigLocation(""); /* TMT From JEE 6 API Docs: * Registers the given servlet instance with this ServletContext under the given servletName. * The registered servlet may be further configured via the returned ServletRegistration object. */ ServletRegistration.Dynamic appServlet = servletContext.addServlet(APP_SERVLET, servlet); appServlet.setLoadOnStartup(1); appServlet.setAsyncSupported(true); Set<String> mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { throw new IllegalStateException(String.format( "The servlet named '%s' cannot be mapped to '/' under Tomcat versions <= 7.0.14", APP_SERVLET)); } // TMT servletContext.addListener(new Log4jConfigListener()); System.out.println("Application inplemented on Spring Version: " + SpringVersion.getVersion()); }
From source file:com.iflytek.edu.cloud.frame.web.RestServiceWebApplicationInitializer.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.setInitParameter("contextConfigLocation", "classpath*:META-INF/spring/*-context.xml"); servletContext.setInitParameter("contextInitializerClasses", ProfileApplicationContextInitializer.class.getName()); servletContext.addListener(new LogBackLoadConfigureListener()); servletContext.addListener(new ContextLoaderListener()); FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter()); EnumSet<DispatcherType> characterEncodingFilterDispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);//ww w . j av a2 s. com characterEncodingFilter.setInitParameter("encoding", "UTF-8"); characterEncodingFilter.setInitParameter("forceEncoding", "true"); characterEncodingFilter.addMappingForUrlPatterns(characterEncodingFilterDispatcherTypes, true, "/*"); FilterRegistration.Dynamic openServiceFilter = servletContext.addFilter("openServiceFilter", new DelegatingFilterProxy()); EnumSet<DispatcherType> openServiceFilterDispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD); openServiceFilter.addMappingForUrlPatterns(openServiceFilterDispatcherTypes, true, "/api"); if (EnvUtil.jdbcEnabled()) { FilterRegistration.Dynamic serviceMetricsFilter = servletContext.addFilter("serviceMetricsFilter", new DelegatingFilterProxy()); EnumSet<DispatcherType> serviceMetricsFilterDispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD); serviceMetricsFilter.addMappingForUrlPatterns(serviceMetricsFilterDispatcherTypes, true, "/api"); } FilterRegistration.Dynamic CORSFilter = servletContext.addFilter("CORSFilter", new DelegatingFilterProxy()); EnumSet<DispatcherType> CORSFilterDispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD); CORSFilter.addMappingForUrlPatterns(CORSFilterDispatcherTypes, true, "/api"); if (EnvUtil.oauthEnabled()) { FilterRegistration.Dynamic springSecurityFilterChain = servletContext .addFilter("springSecurityFilterChain", new DelegatingFilterProxyExt()); EnumSet<DispatcherType> springSecurityFilterChainDispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD); springSecurityFilterChain.addMappingForUrlPatterns(springSecurityFilterChainDispatcherTypes, true, "/api"); } else { logger.info( "?oauth2???META-INF/res/profile.propertiesoauth2 profile"); } ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("rest", new DispatcherServlet()); dispatcherServlet.setLoadOnStartup(1); dispatcherServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); dispatcherServlet.setInitParameter("contextConfigLocation", "org.spring.rest"); dispatcherServlet.setMultipartConfig(getMultiPartConfig()); dispatcherServlet.addMapping("/api"); ServletRegistration.Dynamic printProjectVersionServlet = servletContext .addServlet("printProjectVersionServlet", new PrintProjectVersionServlet()); printProjectVersionServlet.setLoadOnStartup(Integer.MAX_VALUE); }
From source file:io.soabase.core.SoaBundle.java
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"); }/*from w ww . j a v a 2s. c o m*/ }
From source file:org.whispersystems.textsecuregcm.WhisperServerService.java
@Override public void run(WhisperServerConfiguration config, Environment environment) throws Exception { SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics()); environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); environment.getObjectMapper().setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); environment.getObjectMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); DBIFactory dbiFactory = new DBIFactory(); DBI database = dbiFactory.build(environment, config.getDataSourceFactory(), "accountdb"); DBI messagedb = dbiFactory.build(environment, config.getMessageStoreConfiguration(), "messagedb"); Accounts accounts = database.onDemand(Accounts.class); PendingAccounts pendingAccounts = database.onDemand(PendingAccounts.class); PendingDevices pendingDevices = database.onDemand(PendingDevices.class); Keys keys = database.onDemand(Keys.class); Messages messages = messagedb.onDemand(Messages.class); RedisClientFactory cacheClientFactory = new RedisClientFactory(config.getCacheConfiguration().getUrl()); JedisPool cacheClient = cacheClientFactory.getRedisClientPool(); JedisPool directoryClient = new RedisClientFactory(config.getDirectoryConfiguration().getUrl()) .getRedisClientPool();// w w w. ja va 2 s . c om Client httpClient = initializeHttpClient(environment, config); DirectoryManager directory = new DirectoryManager(directoryClient); PendingAccountsManager pendingAccountsManager = new PendingAccountsManager(pendingAccounts, cacheClient); PendingDevicesManager pendingDevicesManager = new PendingDevicesManager(pendingDevices, cacheClient); AccountsManager accountsManager = new AccountsManager(accounts, directory, cacheClient); FederatedClientManager federatedClientManager = new FederatedClientManager(environment, config.getJerseyClientConfiguration(), config.getFederationConfiguration()); MessagesManager messagesManager = new MessagesManager(messages); DeadLetterHandler deadLetterHandler = new DeadLetterHandler(messagesManager); DispatchManager dispatchManager = new DispatchManager(cacheClientFactory, Optional.<DispatchChannel>of(deadLetterHandler)); PubSubManager pubSubManager = new PubSubManager(cacheClient, dispatchManager); PushServiceClient pushServiceClient = new PushServiceClient(httpClient, config.getPushConfiguration()); WebsocketSender websocketSender = new WebsocketSender(messagesManager, pubSubManager); AccountAuthenticator deviceAuthenticator = new AccountAuthenticator(accountsManager); FederatedPeerAuthenticator federatedPeerAuthenticator = new FederatedPeerAuthenticator( config.getFederationConfiguration()); RateLimiters rateLimiters = new RateLimiters(config.getLimitsConfiguration(), cacheClient); ApnFallbackManager apnFallbackManager = new ApnFallbackManager(pushServiceClient, pubSubManager); TwilioSmsSender twilioSmsSender = new TwilioSmsSender(config.getTwilioConfiguration()); SmsSender smsSender = new SmsSender(twilioSmsSender); UrlSigner urlSigner = new UrlSigner(config.getS3Configuration()); PushSender pushSender = new PushSender(apnFallbackManager, pushServiceClient, websocketSender, config.getPushConfiguration().getQueueSize()); ReceiptSender receiptSender = new ReceiptSender(accountsManager, pushSender, federatedClientManager); FeedbackHandler feedbackHandler = new FeedbackHandler(pushServiceClient, accountsManager); TurnTokenGenerator turnTokenGenerator = new TurnTokenGenerator(config.getTurnConfiguration()); Optional<byte[]> authorizationKey = config.getRedphoneConfiguration().getAuthorizationKey(); environment.lifecycle().manage(apnFallbackManager); environment.lifecycle().manage(pubSubManager); environment.lifecycle().manage(feedbackHandler); environment.lifecycle().manage(pushSender); AttachmentController attachmentController = new AttachmentController(rateLimiters, federatedClientManager, urlSigner); KeysControllerV1 keysControllerV1 = new KeysControllerV1(rateLimiters, keys, accountsManager, federatedClientManager); KeysControllerV2 keysControllerV2 = new KeysControllerV2(rateLimiters, keys, accountsManager, federatedClientManager); MessageController messageController = new MessageController(rateLimiters, pushSender, receiptSender, accountsManager, messagesManager, federatedClientManager); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<Account>().setAuthenticator(deviceAuthenticator) .setPrincipal(Account.class).buildAuthFilter(), new BasicCredentialAuthFilter.Builder<FederatedPeer>().setAuthenticator(federatedPeerAuthenticator) .setPrincipal(FederatedPeer.class).buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder()); environment.jersey() .register(new AccountController(pendingAccountsManager, accountsManager, rateLimiters, smsSender, messagesManager, new TimeProvider(), authorizationKey, turnTokenGenerator, config.getTestDevices())); environment.jersey().register( new DeviceController(pendingDevicesManager, accountsManager, messagesManager, rateLimiters)); environment.jersey().register(new DirectoryController(rateLimiters, directory)); environment.jersey().register(new FederationControllerV1(accountsManager, attachmentController, messageController, keysControllerV1)); environment.jersey().register(new FederationControllerV2(accountsManager, attachmentController, messageController, keysControllerV2)); environment.jersey().register(new ReceiptController(receiptSender)); environment.jersey().register(new ProvisioningController(rateLimiters, pushSender)); environment.jersey().register(attachmentController); environment.jersey().register(keysControllerV1); environment.jersey().register(keysControllerV2); environment.jersey().register(messageController); if (config.getWebsocketConfiguration().isEnabled()) { WebSocketEnvironment webSocketEnvironment = new WebSocketEnvironment(environment, config, 90000); webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(deviceAuthenticator)); webSocketEnvironment.setConnectListener(new AuthenticatedConnectListener(accountsManager, pushSender, receiptSender, messagesManager, pubSubManager)); webSocketEnvironment.jersey().register(new KeepAliveController(pubSubManager)); webSocketEnvironment.jersey().register(messageController); WebSocketEnvironment provisioningEnvironment = new WebSocketEnvironment(environment, config); provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(pubSubManager)); provisioningEnvironment.jersey().register(new KeepAliveController(pubSubManager)); WebSocketResourceProviderFactory webSocketServlet = new WebSocketResourceProviderFactory( webSocketEnvironment); WebSocketResourceProviderFactory provisioningServlet = new WebSocketResourceProviderFactory( provisioningEnvironment); ServletRegistration.Dynamic websocket = environment.servlets().addServlet("WebSocket", webSocketServlet); ServletRegistration.Dynamic provisioning = environment.servlets().addServlet("Provisioning", provisioningServlet); websocket.addMapping("/v1/websocket/"); websocket.setAsyncSupported(true); provisioning.addMapping("/v1/websocket/provisioning/"); provisioning.setAsyncSupported(true); webSocketServlet.start(); provisioningServlet.start(); FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class); filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); filter.setInitParameter("allowedOrigins", "*"); filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,X-Signal-Agent"); filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS"); filter.setInitParameter("preflightMaxAge", "5184000"); filter.setInitParameter("allowCredentials", "true"); } environment.healthChecks().register("directory", new RedisHealthCheck(directoryClient)); environment.healthChecks().register("cache", new RedisHealthCheck(cacheClient)); environment.jersey().register(new IOExceptionMapper()); environment.jersey().register(new RateLimitExceededExceptionMapper()); environment.jersey().register(new InvalidWebsocketAddressExceptionMapper()); environment.jersey().register(new DeviceLimitExceededExceptionMapper()); environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge()); environment.metrics().register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge()); environment.metrics().register(name(NetworkSentGauge.class, "bytes_sent"), new NetworkSentGauge()); environment.metrics().register(name(NetworkReceivedGauge.class, "bytes_received"), new NetworkReceivedGauge()); environment.metrics().register(name(FileDescriptorGauge.class, "fd_count"), new FileDescriptorGauge()); }