Example usage for javax.servlet ServletRegistration addMapping

List of usage examples for javax.servlet ServletRegistration addMapping

Introduction

In this page you can find the example usage for javax.servlet ServletRegistration 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.openmrs.web.WebComponentRegistrar.java

private void addMappings(ServletRegistration reg, String... mappings) {
    for (String mapping : mappings) {
        reg.addMapping(mapping);
    }//  w ww. j ava2  s . co  m
}

From source file:org.openmrs.web.WebComponentRegistrar.java

@Override
public void setServletContext(ServletContext servletContext) {

    try {/*from   ww w. ja v a2  s .  c  o m*/
        ServletRegistration openmrsServletReg = servletContext.getServletRegistration("openmrs");
        addMappings(openmrsServletReg, "*.htm", "*.form", "*.list", "*.json", "*.field", "*.portlet", "*.page",
                "*.action");

        addMappings(servletContext.getServletRegistration("jsp"), "*.withjstl");

        ServletRegistration servletReg = servletContext.addServlet("logoutServlet", new LogoutServlet());
        servletReg.addMapping("/logout");

        Dynamic filter = servletContext.addFilter("forcePasswordChangeFilter", new ForcePasswordChangeFilter());
        filter.setInitParameter("changePasswordForm", "/admin/users/changePassword.form");
        filter.setInitParameter("excludeURL", "changePasswordForm,logout,.js,.css,.gif,.jpg,.jpeg,.png");
        filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

        filter = servletContext.addFilter("adminPageFilter", new AdminPageFilter());
        filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/admin");

        servletContext.addListener(new SessionListener());
        /*
         * EfficientShutdownServletContextAttributeListener is used instead of
         * EfficientShutdownServletContextListener since the latter implements ServletContextListener,
         * which is not supported by ServletContext.addListener.
        */
        servletContext.addListener(new EfficientShutdownServletContextAttributeListener());
    } catch (Exception ex) {
        //TODO not yet looked into what caused this to fail.
    }
}

From source file:com.dm.platform.listener.base.MyServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    System.out.println("MyServletContextListener");
    ServletContext sc = sce.getServletContext();

    ServletRegistration sr = sc.addServlet("spring", DispatcherServlet.class);
    sr.setInitParameter("contextConfigLocation", "/WEB-INF/dispatcher-servlet.xml");
    sr.addMapping("/spring/*");

    FilterRegistration fr = sc.addFilter(DynamicRegistFilter.class.getSimpleName(), DynamicRegistFilter.class);
    fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/platform/*");
    //          fr = sc.addFilter(DelegatingFilterProxy.class.getSimpleName(), DelegatingFilterProxy.class);
    //        fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/platform/*");

    sc.addListener(new ContextLoaderListener());
}

From source file:com.dm.platform.listener.PlatformServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    System.out.println("contextInitialized");

    ServletContext sc = sce.getServletContext();
    sc.setInitParameter("contextConfigLocation", "/WEB-INF/applicationContext.xml");
    //    sc.addListener(ContextLoaderListener.class);
    FilterRegistration fr = sc.addFilter(DelegatingFilterProxy.class.getSimpleName(),
            DelegatingFilterProxy.class);
    fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/spring/*");

    ServletRegistration sr = sc.addServlet("spring", DispatcherServlet.class);
    sr.setInitParameter("contextConfigLocation",
            "/WEB-INF/dispatcher-servlet.xml /WEB-INF/platform-security.xml");
    sr.addMapping("/spring/*");

    fr = sc.addFilter(DynamicRegistFilter.class.getSimpleName(), DynamicRegistFilter.class);
    fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/platform/*");

}

From source file:dinistiq.web.DinistiqContextLoaderListener.java

/**
 * Web related dinistiq initialization with parameters taken from the web.xml.
 *
 * Looks up relevant packages for scanning and a custom class resolver's implementation class name. Exposes any
 * bean from the dinistiq scope to the application scope (servlet context) of the web layer including an instance
 * of dinistiq itself./* w  ww .j  av  a 2s. c  o m*/
 *
 * @param contextEvent
 */
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
    // just to check what our log instance looks like
    LOG.warn("contextInitialized() log: {}", LOG.getClass().getName());
    ServletContext context = contextEvent.getServletContext();
    Set<String> packages = new HashSet<>();
    String packagNameString = context.getInitParameter(DINISTIQ_PACKAGES);
    if (StringUtils.isNotBlank(packagNameString)) {
        for (String packageName : packagNameString.split(",")) {
            packageName = packageName.trim();
            packages.add(packageName);
        } // for
    } // if
    String classResolverName = context.getInitParameter(DINISTIQ_CLASSRESOLVER);
    ClassResolver classResolver = null;
    if (StringUtils.isNotBlank(classResolverName)) {
        try {
            Class<?> forName = Class.forName(classResolverName);
            Object[] args = new Object[1];
            args[0] = packages;
            classResolver = (ClassResolver) forName.getConstructors()[0].newInstance(args);
        } catch (Exception e) {
            LOG.error("contextInitialized() cannot obtain custom class resolver", e);
        } // try/catch
    } // if
    LOG.info("contextInitialized() classResolver: {} :{}", classResolver, classResolverName);
    classResolver = (classResolver == null) ? new SimpleClassResolver(packages) : classResolver;
    try {
        Map<String, Object> externalBeans = new HashMap<>();
        externalBeans.put("servletContext", context);
        Dinistiq dinistiq = new Dinistiq(classResolver, externalBeans);
        context.setAttribute(DINISTIQ_INSTANCE, dinistiq);
        for (String name : dinistiq.getAllBeanNames()) {
            context.setAttribute(name, dinistiq.findBean(Object.class, name));
        } // for
        Collection<RegisterableServlet> servlets = dinistiq.findBeans(RegisterableServlet.class);
        List<RegisterableServlet> orderedServlets = new ArrayList<>(servlets.size());
        orderedServlets.addAll(servlets);
        Collections.sort(orderedServlets);
        LOG.debug("contextInitialized() servlets {}", orderedServlets);
        for (RegisterableServlet servlet : orderedServlets) {
            ServletRegistration registration = context.addServlet(servlet.getClass().getSimpleName(), servlet);
            for (String urlPattern : servlet.getUrlPatterns()) {
                LOG.debug("contextInitialized() * {}", urlPattern);
                registration.addMapping(urlPattern);
            } // for
        } // for
    } catch (Exception ex) {
        LOG.error("init()", ex);
    } // try/catch
}

From source file:com.strandls.alchemy.webservices.testbase.JerseyTestEnv.java

/**
 * Get the test container factory.//from ww  w .j av  a 2 s  .  c  o m
 *
 * @param contextListener
 * @return
 * @throws TestContainerException
 */
@Provides
@Inject
@TestScoped
protected TestContainerFactory getTestContainerFactory(final WebserviceTestBaseContextListener contextListener)
        throws TestContainerException {
    return new TestContainerFactory() {

        /*
         * Create a test container.
         */
        @Override
        public TestContainer create(final URI baseUri, final DeploymentContext deploymentContext) {
            return new TestContainer() {
                private HttpServer server;

                @Override
                public URI getBaseUri() {
                    return baseUri;
                }

                @Override
                public ClientConfig getClientConfig() {
                    return null;
                }

                public WebappContext getContext(final URI baseUri) {
                    if (baseUri == null) {
                        throw new IllegalArgumentException("The URI must not be null");
                    }

                    String path = baseUri.getPath();
                    if (path == null) {
                        throw new IllegalArgumentException(
                                "The URI path, of the URI " + baseUri + ", must be non-null");
                    } else if (path.isEmpty()) {
                        throw new IllegalArgumentException(
                                "The URI path, of the URI " + baseUri + ", must be present");
                    } else if (path.charAt(0) != '/') {
                        throw new IllegalArgumentException(
                                "The URI path, of the URI " + baseUri + ". must start with a '/'");
                    }

                    path = String.format("/%s",
                            UriComponent.decodePath(baseUri.getPath(), true).get(1).toString());

                    final WebappContext context = new WebappContext("GrizzlyContext", path);
                    final FilterRegistration filterRegistration = context.addFilter("Guice Filter",
                            GuiceFilter.class);
                    filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), "/*");

                    // Initialize and register JSP Servlet
                    final ServletRegistration jspRegistration = context.addServlet("Jersey Servlet Container",
                            ServletContainer.class);
                    jspRegistration.addMapping("/*");

                    context.addListener(contextListener);
                    return context;
                }

                @Override
                public void start() {
                    try {
                        final WebappContext context = getContext(getBaseUri());
                        server = GrizzlyHttpServerFactory.createHttpServer(getBaseUri(),
                                deploymentContext.getResourceConfig());
                        server.getHttpHandler().setAllowEncodedSlash(true);
                        context.setAttribute(ServerProperties.RESOURCE_VALIDATION_IGNORE_ERRORS, true);
                        context.deploy(server);
                    } catch (final ProcessingException e) {
                        throw new TestContainerException(e);
                    }
                }

                @Override
                public void stop() {
                    this.server.shutdown();
                }
            };
        }
    };
}

From source file:io.cettia.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override/*from w ww  . j a  v  a 2 s  .c  o m*/
        public void on(final ServerSocket socket) {
            log.debug("socket.uri() is {}", socket.uri());
            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);
    jetty.addConnector(connector);
    connector.setPort(8000);
    ServletContextHandler handler = new ServletContextHandler();
    jetty.setHandler(handler);
    handler.addEventListener(new ServletContextListener() {
        @Override
        @SuppressWarnings("serial")
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            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");
            // For HTTP transport
            Servlet servlet = new AsityServlet().onhttp(httpTransportServer);
            ServletRegistration.Dynamic reg = context.addServlet(AsityServlet.class.getName(), servlet);
            reg.setAsyncSupported(true);
            reg.addMapping("/cettia");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
    // For WebSocket transport
    ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler);
    ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class, "/cettia")
            .configurator(new Configurator() {
                @Override
                public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
                    return endpointClass.cast(new AsityServerEndpoint().onwebsocket(wsTransportServer));
                }
            }).build();
    container.addEndpoint(config);

    jetty.start();

    CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node")
            .addArgument("./src/test/resources/runner").addArgument("--cettia.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.atmosphere.vibe.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override//from   w w w  . j  a  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.kuali.coeus.sys.framework.config.KcConfigurer.java

@Override
protected void doAdditionalModuleStartLogic() throws Exception {
    if (StringUtils.isNotBlank(dispatchServletName)) {
        DispatcherServlet loaderServlet = new DispatcherServlet(
                (WebApplicationContext) ((SpringResourceLoader) rootResourceLoader.getResourceLoaders().get(0))
                        .getContext());/* w ww .j a  v a  2s  .  c om*/
        ServletRegistration registration = getServletContext().addServlet(dispatchServletName, loaderServlet);
        registration.addMapping("/" + dispatchServletName + "/*");
        for (String filterName : filtersToMap) {
            FilterRegistration filter = getServletContext().getFilterRegistration(filterName);
            filter.addMappingForServletNames(null, true, dispatchServletName);
        }
        if (enableSpringSecurity) {
            DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(SPRING_SECURITY_FILTER_CHAIN,
                    (WebApplicationContext) ((SpringResourceLoader) rootResourceLoader.getResourceLoaders()
                            .get(0)).getContext());
            FilterRegistration.Dynamic securityFilter = getServletContext()
                    .addFilter(KC_PREFIX + getModuleName() + SPRING_SECURITY_FILTER_PROXY, filterProxy);
            securityFilter.addMappingForServletNames(null, true, dispatchServletName);
        }
    }
}