Example usage for javax.servlet ServletContextListener ServletContextListener

List of usage examples for javax.servlet ServletContextListener ServletContextListener

Introduction

In this page you can find the example usage for javax.servlet ServletContextListener ServletContextListener.

Prototype

ServletContextListener

Source Link

Usage

From source file:at.irian.demo.embedded.AppStarter.java

@Bean
public ServletContextListener contextListener() {
    final CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
    return new ServletContextListener() {
        @Override//from   ww w .j  a v a  2s .c o  m
        public void contextInitialized(ServletContextEvent sce) {
            cdiContainer.boot();
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            cdiContainer.shutdown();
        }
    };
}

From source file:org.brutusin.rpc.RpcWebInitializer.java

public void onStartup(final ServletContext ctx) throws ServletException {
    final RpcServlet rpcServlet = registerRpcServlet(ctx);
    final WebsocketFilter websocketFilter = new WebsocketFilter();
    FilterRegistration.Dynamic dynamic = ctx.addFilter(WebsocketFilter.class.getName(), websocketFilter);
    dynamic.addMappingForUrlPatterns(null, false, RpcConfig.getInstance().getPath() + "/wskt");
    JsonCodec.getInstance().registerStringFormat(MetaDataInputStream.class, "inputstream");
    final Bean<RpcSpringContext> rpcCtxBean = new Bean<RpcSpringContext>();
    ctx.addListener(new ServletRequestListener() {

        public void requestDestroyed(ServletRequestEvent sre) {
            GlobalThreadLocal.clear();//from w  w  w.jav  a 2  s. c  om
        }

        public void requestInitialized(ServletRequestEvent sre) {
            GlobalThreadLocal.set(new GlobalThreadLocal((HttpServletRequest) sre.getServletRequest(), null));
        }
    });
    ctx.addListener(new ServletContextListener() {

        public void contextInitialized(ServletContextEvent sce) {
            RpcSpringContext rpcCtx = createRpcSpringContext(ctx);
            rpcCtxBean.setValue(rpcCtx);
            rpcServlet.setRpcCtx(rpcCtx);
            initWebsocketRpcRuntime(ctx, rpcCtx);
            ctx.setAttribute(RpcSpringContext.class.getName(), rpcCtx);
        }

        public void contextDestroyed(ServletContextEvent sce) {
            LOGGER.info("Destroying RPC context");
            if (rpcCtxBean.getValue() != null) {
                rpcCtxBean.getValue().destroy();
            }
        }
    });
    ctx.addListener(new ServletContextAttributeListener() {
        public void attributeAdded(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        public void attributeRemoved(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        public void attributeReplaced(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        private void updateRootContext() {
            WebApplicationContext rootCtx = WebApplicationContextUtils.getWebApplicationContext(ctx);
            if (rootCtx != null) {
                if (rpcCtxBean.getValue() != null) {
                    rpcCtxBean.getValue().setParent(rootCtx);
                }
                if (rootCtx.containsBean("springSecurityFilterChain")) {
                    LOGGER.info("Moving WebsocketFilter behind springSecurityFilterChain");
                    websocketFilter.disable();
                    FilterChainProxy fcp = (FilterChainProxy) rootCtx.getBean("springSecurityFilterChain");
                    fcp.getFilterChains().get(0).getFilters().add(new WebsocketFilter());
                }
            }
        }
    });
}

From source file:net.officefloor.plugin.servlet.OfficeFloorServletIntegrationToContainerTest.java

/**
 * Ensure able to render JSP from HTTP state objects.
 *//*from   w ww .  j a va2  s  .  c om*/
public void testJspStateIntegration() throws Exception {

    // Add the servlet for handling requests
    this.context.addEventListener(new MockJspIntergateServlet());

    // Add the JSP
    this.context.addServlet(new ServletHolder(JspServlet.class), "*.jsp");
    this.context.setClassLoader(Thread.currentThread().getContextClassLoader());

    // Add listener to initialise application object
    this.context.addEventListener(new ServletContextListener() {
        @Override
        public void contextInitialized(ServletContextEvent event) {
            // Load the application object
            MockApplicationObject object = new MockApplicationObject();
            object.text = "INIT";
            event.getServletContext().setAttribute("ApplicationBean", object);
        }

        @Override
        public void contextDestroyed(ServletContextEvent event) {
            // Do nothing
        }
    });

    // Start the server
    this.server.start();

    // Ensure can invoke JSP directly (without initialising)
    this.assertHttpRequest("/Template.jsp", "INIT null null");

    // Invoke to use template submit to create state for JSP
    this.assertHttpRequest("/template-submit.integrate", "application session request");
}

From source file:io.cettia.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override/*www.  j av  a2  s . com*/
        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:com.streamsets.datacollector.http.TestWebServerTaskHttpHttps.java

@Test
public void testWebAppSSOServiceDelegation() throws Exception {
    final DummySSOService delegatedTo = new DummySSOService();
    WebAppProvider webAppProvider = new WebAppProvider() {
        @Override/*from  ww w.  ja va 2 s  .co m*/
        public ServletContextHandler get() {
            ServletContextHandler handler = new ServletContextHandler();
            handler.setContextPath("/webapp");
            handler.addEventListener(new ServletContextListener() {
                @Override
                public void contextInitialized(ServletContextEvent sce) {
                    SSOService ssoService = (SSOService) sce.getServletContext()
                            .getAttribute(SSOService.SSO_SERVICE_KEY);
                    ssoService.setDelegateTo(delegatedTo);
                }

                @Override
                public void contextDestroyed(ServletContextEvent sce) {

                }
            });
            handler.addServlet(new ServletHolder(new PingServlet()), "/ping");
            return handler;
        }

        @Override
        public void postStart() {
        }
    };
    Configuration conf = new Configuration();
    int httpPort = getRandomPort();
    conf.set(WebServerTask.DPM_ENABLED, true);
    conf.set(WebServerTask.HTTP_PORT_KEY, httpPort);
    final WebServerTask ws = createWebServerTask(createTestDir(), conf, ImmutableSet.of(webAppProvider));
    try {
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        Thread.sleep(1000);

        Assert.assertTrue(delegatedTo.inited);
    } finally {
        ws.stopTask();
    }
}

From source file:org.alfresco.repo.web.util.AbstractJettyComponent.java

protected void configure(WebAppContext webAppContext) {
    try {//from ww w  .  j  ava2 s .c  om
        ClassLoader classLoader = BaseApplicationContextHelper.buildClassLoader(classLocations);
        webAppContext.setClassLoader(classLoader);
    } catch (IOException e) {
        throw new ExceptionInInitializerError(e);
    }

    webAppContext.addEventListener(new ServletContextListener() {
        public void contextInitialized(ServletContextEvent sce) {
            // create a Spring web application context, wrapping and providing access to
            // the application context
            try {
                ServletContext servletContext = sce.getServletContext();

                // initialise web application context
                WebApplicationContextLoader.getApplicationContext(servletContext, configLocations,
                        classLocations);

                if (logger.isDebugEnabled()) {
                    logger.debug("contextInitialized " + sce);
                }
            } catch (Throwable t) {
                logger.error("Failed to start Jetty server: " + t);
                throw new AlfrescoRuntimeException("Failed to start Jetty server", t);
            }
        }

        public void contextDestroyed(ServletContextEvent sce) {
            if (logger.isDebugEnabled()) {
                logger.debug("contextDestroyed " + sce);
            }
        }
    });

    // with a login-config in web.xml, jetty seems to require this in order to start successfully
    webAppContext.getSecurityHandler().setLoginService(new HashLoginService());

    // arbitrary temporary file location
    File tmp = new File(TempFileProvider.getSystemTempDir(), String.valueOf(System.currentTimeMillis()));
    webAppContext.setResourceBase(tmp.getAbsolutePath());
}

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/*  w  w w  .  j av a2  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();
}