Example usage for javax.servlet ServletRegistration.Dynamic addMapping

List of usage examples for javax.servlet ServletRegistration.Dynamic addMapping

Introduction

In this page you can find the example usage for javax.servlet ServletRegistration.Dynamic addMapping.

Prototype

public Set<String> addMapping(String... urlPatterns);

Source Link

Document

Adds a servlet mapping with the given URL patterns for the Servlet represented by this ServletRegistration.

Usage

From source file:org.lightadmin.core.config.LightAdminWebApplicationInitializer.java

private void registerLogoResourceServlet(final ServletContext servletContext) {
    ServletRegistration.Dynamic customResourceServletRegistration = servletContext
            .addServlet(LIGHT_ADMIN_LOGO_RESOURCE_SERVLET_NAME, logoResourceServlet(servletContext));
    customResourceServletRegistration.setLoadOnStartup(3);
    customResourceServletRegistration/*from ww  w  . java2 s  .  c  o  m*/
            .addMapping(resourceServletMapping(servletContext, LIGHT_ADMIN_LOGO_SERVLET_URL));
}

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

protected void registerFrontAppServlet(ServletContext servletContext) {
    boolean hasFrontApp = false;
    try {//w w w  .  jav a 2s .  com
        hasFrontApp = servletContext.getResource("/" + FRONT_CONTEXT_NAME) != null;
    } catch (MalformedURLException e) {
        //Do nothing
    }
    if (hasFrontApp) {
        String contextPath = servletContext.getContextPath();
        String baseUrl = System.getProperty("cuba.front.baseUrl");
        if (baseUrl == null || baseUrl.length() == 0) {
            String path = "/" + FRONT_CONTEXT_NAME + "/";
            System.setProperty("cuba.front.baseUrl", "/".equals(contextPath) ? path : contextPath + path);
        }
        String apiUrl = System.getProperty("cuba.front.apiUrl");
        if (apiUrl == null || apiUrl.length() == 0) {
            String path = "/rest/";
            System.setProperty("cuba.front.apiUrl", "/".equals(contextPath) ? path : contextPath + path);
        }
        DispatcherServlet frontServlet;
        try {
            Class frontServletClass = ReflectionHelper.getClass("com.haulmont.cuba.web.sys.AppFrontServlet");
            frontServlet = (DispatcherServlet) ReflectionHelper.newInstance(frontServletClass,
                    FRONT_CONTEXT_NAME, (Supplier<ApplicationContext>) AppContext::getApplicationContext);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Unable to instantiate app front servlet", e);
        }
        ServletRegistration.Dynamic cubaServletReg = servletContext.addServlet("app_front_servlet",
                frontServlet);
        cubaServletReg.setLoadOnStartup(3);
        cubaServletReg.setAsyncSupported(true);
        cubaServletReg.addMapping(String.format("/%s/*", FRONT_CONTEXT_NAME));
    }
}

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  . j a v  a 2s  .  co  m
    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.kurento.kmf.content.internal.ContentApiWebApplicationInitializer.java

/**
 * Player initializator: this method search classes in the classpath using
 * the annotation {@link HttpPlayerService}, and it register a servlet for
 * each handler found.//from  w w w  . j a v  a  2s  .  co  m
 * 
 * @param sc
 *            Servlet Context in which register servlets for each handler
 * @throws ServletException
 *             Exception raised when a reflection problem occurs, typically
 *             when a class has not been found in the classpath
 */
private void initializePlayers(ServletContext sc) throws ServletException {
    for (String ph : findServices(HttpPlayerHandler.class, HttpPlayerService.class)) {
        try {
            HttpPlayerService playerService = Class.forName(ph).getAnnotation(HttpPlayerService.class);
            if (playerService != null) {
                String name = playerService.name().isEmpty() ? ph : playerService.name();
                String path = playerService.path();
                log.debug("Registering HttpPlayerHandler with name " + name + " at path " + path);
                ServletRegistration.Dynamic sr = sc.addServlet(name, PlayerHandlerServlet.class);
                if (sr == null) {
                    throw new ServletException("Duplicated handler named " + name
                            + " found. You must check your handlers' annotations to assert that no name duplications are declared.");
                }
                sr.addMapping(path);
                sr.setInitParameter(HANDLER_CLASS_PARAM_NAME, ph);
                sr.setAsyncSupported(true);
            }
        } catch (ClassNotFoundException e) {
            log.error("Error: could not find class " + ph + " in classpath", e);
            throw new ServletException(e);
        }
    }
}

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();//from   w  w  w. j a  v  a 2s  .  c o  m
    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:eionet.transfer.TransferWebAppInitializer.java

@Override
public void onStartup(ServletContext container) {
    XmlWebApplicationContext appContext = new XmlWebApplicationContext();
    appContext.setConfigLocation("/WEB-INF/classes/spring-db-config.xml "
            + "/WEB-INF/classes/spring-init-config.xml " + "/WEB-INF/classes/spring-mvc-config.xml");

    // Listeners//from  www  .  j  a  va2  s  . co m
    //SingleSignOutHttpSessionListener ssoListener = new SingleSignOutHttpSessionListener(appContext);
    //container.addListener(ssoListener);

    //ContextLoaderListener contextLoaderListener = new ContextLoaderListener(appContext);
    //container.addListener(contextLoaderListener);

    ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher",
            new DispatcherServlet(appContext));

    String location = null;
    try {
        location = System.getProperty("upload.dir", null);
    } catch (Exception e) {
        location = null;
    }

    logger.info("Upload directory configured to: " + (location == null ? "[default]" : location));

    //long maxFileSize = 5000000L;
    //long maxRequestSize = 5000000L;
    //int fileSizeThreshold = 0;
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement(location);
    //MultipartConfigElement multipartConfigElement = new MultipartConfigElement(location, maxFileSize, maxRequestSize, fileSizeThreshold);
    dispatcher.setMultipartConfig(multipartConfigElement);

    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

From source file:com.jsmartframework.web.manager.ContextControl.java

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {//from w  ww  . j a  v  a  2  s. c  o  m
        ServletContext servletContext = event.getServletContext();

        CONFIG.init(servletContext);
        if (CONFIG.getContent() == null) {
            throw new RuntimeException("Configuration file " + Constants.WEB_CONFIG_XML
                    + " was not found in WEB-INF resources folder!");
        }

        String contextConfigLocation = "com.jsmartframework.web.manager";
        if (CONFIG.getContent().getPackageScan() != null) {
            contextConfigLocation += "," + CONFIG.getContent().getPackageScan();
        }

        // Configure necessary parameters in the ServletContext to set Spring configuration without needing an XML file
        AnnotationConfigWebApplicationContext configWebAppContext = new AnnotationConfigWebApplicationContext();
        configWebAppContext.setConfigLocation(contextConfigLocation);

        CONTEXT_LOADER = new ContextLoader(configWebAppContext);
        CONTEXT_LOADER.initWebApplicationContext(servletContext);

        TagEncrypter.init();
        TEXTS.init();
        IMAGES.init(servletContext);
        HANDLER.init(servletContext);

        // ServletControl -> @MultipartConfig @WebServlet(name = "ServletControl", displayName = "ServletControl", loadOnStartup = 1)
        Servlet servletControl = servletContext.createServlet(
                (Class<? extends Servlet>) Class.forName("com.jsmartframework.web.manager.ServletControl"));
        ServletRegistration.Dynamic servletControlReg = (ServletRegistration.Dynamic) servletContext
                .addServlet("ServletControl", servletControl);
        servletControlReg.setAsyncSupported(true);
        servletControlReg.setLoadOnStartup(1);

        // ServletControl Initial Parameters
        InitParam[] initParams = CONFIG.getContent().getInitParams();
        if (initParams != null) {
            for (InitParam initParam : initParams) {
                servletControlReg.setInitParameter(initParam.getName(), initParam.getValue());
            }
        }

        // MultiPart to allow file upload on ServletControl
        MultipartConfigElement multipartElement = getServletMultipartElement();
        if (multipartElement != null) {
            servletControlReg.setMultipartConfig(multipartElement);
        }

        // Security constraint to ServletControl
        ServletSecurityElement servletSecurityElement = getServletSecurityElement(servletContext);
        if (servletSecurityElement != null) {
            servletControlReg.setServletSecurity(servletSecurityElement);
        }

        // TODO: Fix problem related to authentication by container to use SSL dynamically (Maybe create more than one servlet for secure and non-secure patterns)
        // Check also the use of request.login(user, pswd)
        // Check the HttpServletRequest.BASIC_AUTH, CLIENT_CERT_AUTH, FORM_AUTH, DIGEST_AUTH
        // servletReg.setRunAsRole("admin");
        // servletContext.declareRoles("admin");

        // ServletControl URL mapping
        String[] servletMapping = getServletMapping();
        servletControlReg.addMapping(servletMapping);

        // ErrorFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter errorFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.ErrorFilter"));
        FilterRegistration.Dynamic errorFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("ErrorFilter", errorFilter);

        errorFilterReg.setAsyncSupported(true);
        errorFilterReg.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR), true, "/*");

        // EncodeFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter encodeFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.EncodeFilter"));
        FilterRegistration.Dynamic encodeFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("EncodeFilter", encodeFilter);

        encodeFilterReg.setAsyncSupported(true);
        encodeFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // CacheFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter cacheFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.CacheFilter"));
        FilterRegistration.Dynamic cacheFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("CacheFilter", cacheFilter);

        cacheFilterReg.setAsyncSupported(true);
        cacheFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // Add custom filters defined by client
        for (String filterName : sortCustomFilters()) {
            Filter customFilter = servletContext
                    .createFilter((Class<? extends Filter>) HANDLER.webFilters.get(filterName));
            HANDLER.executeInjection(customFilter);

            WebFilter webFilter = customFilter.getClass().getAnnotation(WebFilter.class);
            FilterRegistration.Dynamic customFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter(filterName, customFilter);

            if (webFilter.initParams() != null) {
                for (WebInitParam initParam : webFilter.initParams()) {
                    customFilterReg.setInitParameter(initParam.name(), initParam.value());
                }
            }
            customFilterReg.setAsyncSupported(webFilter.asyncSupported());
            customFilterReg.addMappingForUrlPatterns(EnumSet.copyOf(Arrays.asList(webFilter.dispatcherTypes())),
                    true, webFilter.urlPatterns());
        }

        // FilterControl -> @WebFilter(servletNames = {"ServletControl"})
        Filter filterControl = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.FilterControl"));
        FilterRegistration.Dynamic filterControlReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("FilterControl", filterControl);

        filterControlReg.setAsyncSupported(true);
        filterControlReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // OutputFilter -> @WebFilter(servletNames = {"ServletControl"})
        Filter outputFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.OutputFilter"));
        FilterRegistration.Dynamic outputFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("OutputFilter", outputFilter);

        outputFilterReg.setAsyncSupported(true);
        outputFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // AsyncFilter -> @WebFilter(servletNames = {"ServletControl"})
        // Filter used case AsyncContext is dispatched internally by AsyncBean implementation
        Filter asyncFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.AsyncFilter"));
        FilterRegistration.Dynamic asyncFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("AsyncFilter", asyncFilter);

        asyncFilterReg.setAsyncSupported(true);
        asyncFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.ASYNC), true, "ServletControl");

        // SessionControl -> @WebListener
        EventListener sessionListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.SessionControl"));
        servletContext.addListener(sessionListener);

        // RequestControl -> @WebListener
        EventListener requestListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.RequestControl"));
        servletContext.addListener(requestListener);

        // Custom WebServlet -> Custom Servlets created by application
        for (String servletName : HANDLER.webServlets.keySet()) {
            Servlet customServlet = servletContext
                    .createServlet((Class<? extends Servlet>) HANDLER.webServlets.get(servletName));
            HANDLER.executeInjection(customServlet);

            WebServlet webServlet = customServlet.getClass().getAnnotation(WebServlet.class);
            ServletRegistration.Dynamic customReg = (ServletRegistration.Dynamic) servletContext
                    .addServlet(servletName, customServlet);

            customReg.setLoadOnStartup(webServlet.loadOnStartup());
            customReg.setAsyncSupported(webServlet.asyncSupported());

            WebInitParam[] customInitParams = webServlet.initParams();
            if (customInitParams != null) {
                for (WebInitParam customInitParam : customInitParams) {
                    customReg.setInitParameter(customInitParam.name(), customInitParam.value());
                }
            }

            // Add mapping url for custom servlet
            customReg.addMapping(webServlet.urlPatterns());

            if (customServlet.getClass().isAnnotationPresent(MultipartConfig.class)) {
                customReg.setMultipartConfig(new MultipartConfigElement(
                        customServlet.getClass().getAnnotation(MultipartConfig.class)));
            }
        }

        // Controller Dispatcher for Spring MVC
        Set<String> requestPaths = HANDLER.requestPaths.keySet();
        if (!requestPaths.isEmpty()) {
            ServletRegistration.Dynamic mvcDispatcherReg = servletContext.addServlet("DispatcherServlet",
                    new DispatcherServlet(configWebAppContext));
            mvcDispatcherReg.setLoadOnStartup(1);
            mvcDispatcherReg.addMapping(requestPaths.toArray(new String[requestPaths.size()]));

            // RequestPathFilter -> @WebFilter(servletNames = {"DispatcherServlet"})
            Filter requestPathFilter = servletContext.createFilter((Class<? extends Filter>) Class
                    .forName("com.jsmartframework.web.manager.RequestPathFilter"));
            FilterRegistration.Dynamic reqPathFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter("RequestPathFilter", requestPathFilter);

            reqPathFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST,
                    DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE, DispatcherType.ASYNC),
                    true, "DispatcherServlet");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.atmosphere.vibe.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override//from   ww w .  ja  v  a 2 s  .c o m
        public void on(final ServerSocket socket) {
            socket.on("abort", new VoidAction() {
                @Override
                public void on() {
                    socket.close();
                }
            }).on("echo", new Action<Object>() {
                @Override
                public void on(Object data) {
                    socket.send("echo", data);
                }
            }).on("/reply/inbound", new Action<Reply<Map<String, Object>>>() {
                @Override
                public void on(Reply<Map<String, Object>> reply) {
                    Map<String, Object> data = reply.data();
                    switch ((String) data.get("type")) {
                    case "resolved":
                        reply.resolve(data.get("data"));
                        break;
                    case "rejected":
                        reply.reject(data.get("data"));
                        break;
                    }
                }
            }).on("/reply/outbound", new Action<Map<String, Object>>() {
                @Override
                public void on(Map<String, Object> data) {
                    switch ((String) data.get("type")) {
                    case "resolved":
                        socket.send("test", data.get("data"), new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    case "rejected":
                        socket.send("test", data.get("data"), null, new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    }
                }
            });
        }
    });
    final HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server);
    final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server);

    org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server();
    ServerConnector connector = new ServerConnector(jetty);
    connector.setPort(8000);
    jetty.addConnector(connector);
    ServletContextHandler handler = new ServletContextHandler();
    handler.addEventListener(new ServletContextListener() {
        @Override
        @SuppressWarnings("serial")
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            // /setup
            ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                    Map<String, String[]> params = req.getParameterMap();
                    if (params.containsKey("heartbeat")) {
                        server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0]));
                    }
                    if (params.containsKey("_heartbeat")) {
                        server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0]));
                    }
                }
            });
            regSetup.addMapping("/setup");
            // /vibe
            Servlet servlet = new VibeAtmosphereServlet().onhttp(httpTransportServer)
                    .onwebsocket(wsTransportServer);
            ServletRegistration.Dynamic reg = context.addServlet(VibeAtmosphereServlet.class.getName(),
                    servlet);
            reg.setAsyncSupported(true);
            reg.setInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR, Boolean.TRUE.toString());
            reg.addMapping("/vibe");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
    jetty.setHandler(handler);
    jetty.start();

    CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node")
            .addArgument("./src/test/resources/runner").addArgument("--vibe.transports")
            .addArgument("websocket,httpstream,httplongpoll");
    DefaultExecutor executor = new DefaultExecutor();
    // The exit value of mocha is the number of failed tests.
    executor.execute(cmdLine);

    jetty.stop();
}

From source file:org.jumpmind.metl.ui.init.AppInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    Properties properties = loadProperties();
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.scan("org.jumpmind.metl");
    MutablePropertySources sources = applicationContext.getEnvironment().getPropertySources();
    sources.addLast(new PropertiesPropertySource("passed in properties", properties));
    servletContext.addListener(new ContextLoaderListener(applicationContext));
    servletContext.addListener(this);
    servletContext.addListener(new RequestContextListener());

    AnnotationConfigWebApplicationContext dispatchContext = new AnnotationConfigWebApplicationContext();
    dispatchContext.setParent(applicationContext);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(dispatchContext));
    dispatcher.setLoadOnStartup(1);/*from w w  w . j  a  va  2 s . co  m*/
    dispatcher.addMapping("/api/*");
    applicationContextRef.set(dispatchContext);

    ServletRegistration.Dynamic apidocs = servletContext.addServlet("apidocs", DefaultServlet.class);
    apidocs.addMapping("/api.html", "/doc/*");

    ServletRegistration.Dynamic vaadin = servletContext.addServlet("vaadin", AppServlet.class);
    vaadin.setAsyncSupported(true);
    vaadin.setInitParameter("org.atmosphere.cpr.asyncSupport", JSR356AsyncSupport.class.getName());
    vaadin.setInitParameter("beanName", "appUI");
    vaadin.addMapping("/*");
}