Example usage for javax.servlet FilterRegistration.Dynamic addMappingForUrlPatterns

List of usage examples for javax.servlet FilterRegistration.Dynamic addMappingForUrlPatterns

Introduction

In this page you can find the example usage for javax.servlet FilterRegistration.Dynamic addMappingForUrlPatterns.

Prototype

public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter,
        String... urlPatterns);

Source Link

Document

Adds a filter mapping with the given url patterns and dispatcher types for the Filter represented by this FilterRegistration.

Usage

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebContextLoader.java

protected void registerClassLoaderFilter(ServletContext servletContext) {
    FilterRegistration.Dynamic filterReg = servletContext.addFilter("WebSingleWarHttpFilter",
            new SetClassLoaderFilter());
    filterReg.setAsyncSupported(true);/*w  ww . j a v  a2  s.c  o  m*/
    filterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
    filterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/dispatch/*");
    filterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/rest/*");
}

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);//from   w w w  . j  a v  a2  s .c  om
    super.onStartup(servletContext);
}

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebContextLoader.java

protected void registerRestApiServlet(ServletContext servletContext) {
    CubaRestApiServlet cubaRestApiServlet = new SingleAppRestApiServlet(dependencyJars);
    try {//from  www .ja  va  2s .c  om
        cubaRestApiServlet.init(new CubaServletConfig("rest_api", servletContext));
    } catch (ServletException e) {
        throw new RuntimeException("An error occurred while initializing dispatcher servlet", e);
    }
    ServletRegistration.Dynamic cubaRestApiServletReg = servletContext.addServlet("rest_api",
            cubaRestApiServlet);
    cubaRestApiServletReg.setLoadOnStartup(2);
    cubaRestApiServletReg.addMapping("/rest/*");

    DelegatingFilterProxy restSpringSecurityFilterChain = new DelegatingFilterProxy();
    restSpringSecurityFilterChain
            .setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.rest_api");
    restSpringSecurityFilterChain.setTargetBeanName("springSecurityFilterChain");

    FilterRegistration.Dynamic restSpringSecurityFilterChainReg = servletContext
            .addFilter("restSpringSecurityFilterChain", restSpringSecurityFilterChain);
    restSpringSecurityFilterChainReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true,
            "/rest/*");
}

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebContextLoader.java

protected void registerIdpServlet(ServletContext servletContext) {
    String serviceProvidersUrls = AppContext.getProperty(IDP_SERVICE_PROVIDERS_URLS);
    if (StringUtils.isEmpty(serviceProvidersUrls)) {
        log.debug("No service providers were found. IDP Servlet will not be started");
        return;/*from   w  w w. j av  a2s .  c om*/
    }

    CubaIdpServlet idpServlet = new SingleAppIdpServlet(dependencyJars);
    try {
        idpServlet.init(new CubaServletConfig("idp", servletContext));
    } catch (ServletException e) {
        throw new RuntimeException("An error occurred while initializing idp servlet", e);
    }

    ServletRegistration.Dynamic idpServletRegistration = servletContext.addServlet("idp", idpServlet);
    idpServletRegistration.setLoadOnStartup(4);
    idpServletRegistration.addMapping("/idp/*");

    DelegatingFilterProxy idpSpringSecurityFilterChain = new DelegatingFilterProxy();
    idpSpringSecurityFilterChain
            .setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.idp");
    idpSpringSecurityFilterChain.setTargetBeanName("springSecurityFilterChain");

    FilterRegistration.Dynamic idpSpringSecurityFilterChainReg = servletContext
            .addFilter("idpSpringSecurityFilterChain", idpSpringSecurityFilterChain);

    idpSpringSecurityFilterChainReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true,
            "/idp/*");
}

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();//  ww  w.ja v a  2s  .  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());
}

From source file:org.obiba.mica.config.WebConfiguration.java

/**
 * Initializes the GZip filter.//  w  ww  .j  a v  a  2 s.c om
 */
private void initGzipFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
    log.debug("Registering GZip Filter");

    FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("gzipFilter", new GzipFilter());

    if (filterRegistration == null) {
        filterRegistration = (FilterRegistration.Dynamic) servletContext.getFilterRegistration("gzipFilter");
    }

    filterRegistration.addMappingForUrlPatterns(disps, true, "*.css");
    filterRegistration.addMappingForUrlPatterns(disps, true, "*.json");
    filterRegistration.addMappingForUrlPatterns(disps, true, "*.html");
    filterRegistration.addMappingForUrlPatterns(disps, true, "*.js");
    filterRegistration.addMappingForUrlPatterns(disps, true, "/jvm/*");
    filterRegistration.addMappingForUrlPatterns(disps, true, WS_ROOT + "/*");
    filterRegistration.setAsyncSupported(true);
}

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);/*from www .  ja v a 2 s .c om*/
    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:com.hortonworks.streamline.webservice.StreamlineApplication.java

@SuppressWarnings("unchecked")
private void addServletFilters(StreamlineConfiguration configuration, Environment environment) {
    List<ServletFilterConfiguration> servletFilterConfigurations = configuration.getServletFilters();
    if (servletFilterConfigurations != null && !servletFilterConfigurations.isEmpty()) {
        for (ServletFilterConfiguration servletFilterConfiguration : servletFilterConfigurations) {
            try {
                FilterRegistration.Dynamic dynamic = environment.servlets().addFilter(
                        servletFilterConfiguration.getClassName(),
                        (Class<? extends Filter>) Class.forName(servletFilterConfiguration.getClassName()));
                dynamic.setInitParameters(servletFilterConfiguration.getParams());
                dynamic.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
                LOG.info("Added servlet filter with configuration {}", servletFilterConfiguration);
            } catch (Exception e) {
                LOG.error("Error occurred while adding servlet filter {}", servletFilterConfiguration);
                throw new RuntimeException(e);
            }//from   ww  w.j a v a  2 s.  c  o  m
        }
    } else {
        LOG.info("No servlet filters configured");
    }
}

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  ww  .java  2s .  c om*/
    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: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 av a  2 s. c o m
    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, "/*");
}