List of usage examples for javax.servlet.http HttpSessionListener HttpSessionListener
HttpSessionListener
From source file:fr.univlorraine.mondossierweb.Initializer.java
/** * @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext) *//*ww w . j av a2s. co m*/ @Override public void onStartup(ServletContext servletContext) throws ServletException { addContextParametersToSystemProperties(servletContext); /* Configure les sessions */ Set<SessionTrackingMode> sessionTrackingModes = new HashSet<SessionTrackingMode>(); sessionTrackingModes.add(SessionTrackingMode.COOKIE); servletContext.setSessionTrackingModes(sessionTrackingModes); servletContext.addListener(new HttpSessionListener() { @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { // sans nouvelle requte, on garde la session active 4 minutes httpSessionEvent.getSession().setMaxInactiveInterval(240); } @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { } }); /* Gestion des sessions dans Atmosphere (Push Vaadin) */ servletContext.addListener(SessionSupport.class); /* Configure Spring */ AnnotationConfigWebApplicationContext springContext = new AnnotationConfigWebApplicationContext(); if (!Boolean.valueOf(servletContext.getInitParameter(Constants.SERVLET_PARAMETER_PRODUCTION_MODE))) { springContext.getEnvironment().setActiveProfiles(DEBUG_PROFILE); } springContext.register(SpringConfig.class); servletContext.addListener(new ContextLoaderListener(springContext)); servletContext.addListener(new RequestContextListener()); /* Filtre Spring Security */ FilterRegistration.Dynamic springSecurityFilterChain = servletContext.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class); springSecurityFilterChain.addMappingForUrlPatterns(null, false, "/*"); /* Filtre passant l'utilisateur courant Logback */ FilterRegistration.Dynamic userMdcServletFilter = servletContext.addFilter("userMdcServletFilter", UserMdcServletFilter.class); userMdcServletFilter.addMappingForUrlPatterns(null, false, "/*"); /* Filtre Spring Mobile permettant de dtecter le device */ FilterRegistration.Dynamic springMobileServletFilter = servletContext .addFilter("deviceResolverRequestFilter", DeviceResolverRequestFilter.class); springMobileServletFilter.addMappingForUrlPatterns(null, false, "/*"); /* Servlet Spring-Vaadin */ //ServletRegistration.Dynamic springVaadinServlet = servletContext.addServlet("springVaadin", JMeterServlet.class); //ServletRegistration.Dynamic springVaadinServlet = servletContext.addServlet("springVaadin", SpringVaadinServlet.class); ServletRegistration.Dynamic springVaadinServlet = servletContext.addServlet("springVaadin", fr.univlorraine.mondossierweb.utils.MdwSpringVaadinServlet.class); springVaadinServlet.setLoadOnStartup(1); springVaadinServlet.addMapping("/*"); /* Dfini le bean UI */ //springVaadinServlet.setInitParameter(Constants.SERVLET_PARAMETER_UI_PROVIDER, "fr.univlorraine.mondossierweb.MdwUIProvider"); /* Utilise les messages Spring pour les messages d'erreur Vaadin (cf. http://vaadin.xpoft.ru/#system_messages) */ springVaadinServlet.setInitParameter("systemMessagesBeanName", "DEFAULT"); /* Dfini la frquence du heartbeat en secondes (cf. https://vaadin.com/book/vaadin7/-/page/application.lifecycle.html#application.lifecycle.ui-expiration) */ springVaadinServlet.setInitParameter(Constants.SERVLET_PARAMETER_HEARTBEAT_INTERVAL, String.valueOf(30)); /* Configure le Push */ springVaadinServlet.setInitParameter(Constants.SERVLET_PARAMETER_PUSH_MODE, Boolean.valueOf(servletContext.getInitParameter("enablePush")) ? PushMode.AUTOMATIC.name() : PushMode.DISABLED.name()); /* Active le support des servlet 3 et des requtes asynchrones (cf. https://vaadin.com/wiki/-/wiki/Main/Working+around+push+issues) */ springVaadinServlet.setInitParameter(ApplicationConfig.WEBSOCKET_SUPPORT_SERVLET3, String.valueOf(true)); /* Active le support des requtes asynchrones */ springVaadinServlet.setAsyncSupported(true); /* Ajoute l'interceptor Atmosphere permettant de restaurer le SecurityContext dans le SecurityContextHolder (cf. https://groups.google.com/forum/#!msg/atmosphere-framework/8yyOQALZEP8/ZCf4BHRgh_EJ) */ springVaadinServlet.setInitParameter(ApplicationConfig.ATMOSPHERE_INTERCEPTORS, RecoverSecurityContextAtmosphereInterceptor.class.getName()); /* Spring-Vaadin Touchkit Servlet */ ServletRegistration.Dynamic springTouchkitVaadinServlet = servletContext.addServlet("springTouchkitVaadin", MDWTouchkitServlet.class); //springTouchkitVaadinServlet.setLoadOnStartup(1); springTouchkitVaadinServlet.addMapping("/m/*"); /* Dfini le bean UI */ //springTouchkitVaadinServlet.setInitParameter(Constants.SERVLET_PARAMETER_UI_PROVIDER, "fr.univlorraine.mondossierweb.MdwTouchkitUIProvider"); /* Utilise les messages Spring pour les messages d'erreur Vaadin (cf. http://vaadin.xpoft.ru/#system_messages) */ springTouchkitVaadinServlet.setInitParameter("systemMessagesBeanName", "DEFAULT"); springTouchkitVaadinServlet.setInitParameter(Constants.PARAMETER_WIDGETSET, "fr.univlorraine.mondossierweb.AppWidgetset"); /* Configure le Push */ springTouchkitVaadinServlet.setInitParameter(Constants.SERVLET_PARAMETER_PUSH_MODE, PushMode.DISABLED.name()); /* Active le support des servlet 3 et des requtes asynchrones (cf. https://vaadin.com/wiki/-/wiki/Main/Working+around+push+issues) */ springTouchkitVaadinServlet.setInitParameter(ApplicationConfig.WEBSOCKET_SUPPORT_SERVLET3, String.valueOf(true)); /* Active le support des requtes asynchrones */ springTouchkitVaadinServlet.setAsyncSupported(true); /* Ajoute l'interceptor Atmosphere permettant de restaurer le SecurityContext dans le SecurityContextHolder (cf. https://groups.google.com/forum/#!msg/atmosphere-framework/8yyOQALZEP8/ZCf4BHRgh_EJ) */ springTouchkitVaadinServlet.setInitParameter(ApplicationConfig.ATMOSPHERE_INTERCEPTORS, RecoverSecurityContextAtmosphereInterceptor.class.getName()); }
From source file:org.apache.drill.cv.exec.server.rest.CvDrillWebServer.java
/** * @return A {@link SessionHandler} which contains a {@link HashSessionManager} *///from w w w. j a v a 2s. c o m private SessionHandler createSessionHandler(final SecurityHandler securityHandler) { SessionManager sessionManager = new HashSessionManager(); sessionManager.setMaxInactiveInterval(config.getInt(ExecConstants.HTTP_SESSION_MAX_IDLE_SECS)); sessionManager.addEventListener(new HttpSessionListener() { @Override public void sessionCreated(HttpSessionEvent se) { // No-op } @Override public void sessionDestroyed(HttpSessionEvent se) { final HttpSession session = se.getSession(); if (session == null) { return; } final Object authCreds = session.getAttribute(SessionAuthentication.__J_AUTHENTICATED); if (authCreds != null) { final SessionAuthentication sessionAuth = (SessionAuthentication) authCreds; securityHandler.logout(sessionAuth); session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED); } } }); return new SessionHandler(sessionManager); }
From source file:org.apache.drill.yarn.appMaster.http.WebServer.java
/** * @return A {@link SessionHandler} which contains a * {@link HashSessionManager}//from w w w . j av a 2 s. c o m */ private SessionHandler createSessionHandler(Config config, final SecurityHandler securityHandler) { SessionManager sessionManager = new HashSessionManager(); sessionManager.setMaxInactiveInterval(config.getInt(DrillOnYarnConfig.HTTP_SESSION_MAX_IDLE_SECS)); sessionManager.addEventListener(new HttpSessionListener() { @Override public void sessionCreated(HttpSessionEvent se) { // No-op } @Override public void sessionDestroyed(HttpSessionEvent se) { final HttpSession session = se.getSession(); if (session == null) { return; } final Object authCreds = session.getAttribute(SessionAuthentication.__J_AUTHENTICATED); if (authCreds != null) { final SessionAuthentication sessionAuth = (SessionAuthentication) authCreds; securityHandler.logout(sessionAuth); session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED); } } }); return new SessionHandler(sessionManager); }
From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java
public void test_Sessions01() { final AtomicBoolean valueBound = new AtomicBoolean(false); final AtomicBoolean valueUnbound = new AtomicBoolean(false); final HttpSessionBindingListener bindingListener = new HttpSessionBindingListener() { @Override/*from w ww .j av a 2 s . com*/ public void valueUnbound(HttpSessionBindingEvent event) { valueUnbound.set(true); } @Override public void valueBound(HttpSessionBindingEvent event) { valueBound.set(true); } }; final AtomicBoolean sessionCreated = new AtomicBoolean(false); final AtomicBoolean sessionDestroyed = new AtomicBoolean(false); HttpSessionListener sessionListener = new HttpSessionListener() { @Override public void sessionDestroyed(HttpSessionEvent se) { sessionDestroyed.set(true); } @Override public void sessionCreated(HttpSessionEvent se) { sessionCreated.set(true); } }; HttpServlet sessionServlet = new HttpServlet() { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); if (session.getAttribute("test.attribute") == null) { session.setAttribute("test.attribute", bindingListener); response.getWriter().print("created"); } else { session.invalidate(); response.getWriter().print("invalidated"); } } }; ServiceRegistration<Servlet> servletReg = null; ServiceRegistration<HttpSessionListener> sessionListenerReg = null; Dictionary<String, Object> servletProps = new Hashtable<String, Object>(); servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/sessions"); String actual = null; CookieHandler previous = CookieHandler.getDefault(); CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); try { servletReg = getBundleContext().registerService(Servlet.class, sessionServlet, servletProps); Dictionary<String, String> listenerProps = new Hashtable<String, String>(); listenerProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_LISTENER, "true"); sessionListenerReg = getBundleContext().registerService(HttpSessionListener.class, sessionListener, listenerProps); sessionCreated.set(false); valueBound.set(false); sessionDestroyed.set(false); valueUnbound.set(false); // first call will create the session actual = requestAdvisor.request("sessions"); assertEquals("Wrong result", "created", actual); assertTrue("No sessionCreated called", sessionCreated.get()); assertTrue("No valueBound called", valueBound.get()); assertFalse("sessionDestroyed was called", sessionDestroyed.get()); assertFalse("valueUnbound was called", valueUnbound.get()); sessionCreated.set(false); valueBound.set(false); sessionDestroyed.set(false); valueUnbound.set(false); // second call will invalidate the session actual = requestAdvisor.request("sessions"); assertEquals("Wrong result", "invalidated", actual); assertFalse("sessionCreated was called", sessionCreated.get()); assertFalse("valueBound was called", valueBound.get()); assertTrue("No sessionDestroyed called", sessionDestroyed.get()); assertTrue("No valueUnbound called", valueUnbound.get()); sessionCreated.set(false); sessionDestroyed.set(false); valueBound.set(false); valueUnbound.set(false); // calling again should create the session again actual = requestAdvisor.request("sessions"); assertEquals("Wrong result", "created", actual); assertTrue("No sessionCreated called", sessionCreated.get()); assertTrue("No valueBound called", valueBound.get()); } catch (Exception e) { fail("Unexpected exception: " + e); } finally { if (servletReg != null) { servletReg.unregister(); } if (sessionListenerReg != null) { sessionListenerReg.unregister(); } CookieHandler.setDefault(previous); } }
From source file:org.jboss.test.faces.jetty.JettyServer.java
private void createContext() { webAppContext = new WebAppContext(); webAppContext.setContextPath("/"); webAppContext.setBaseResource(serverRoot); webAppContext.setClassLoader(getClassLoader()); org.mortbay.jetty.servlet.ServletHolder defaultServletHolder = new org.mortbay.jetty.servlet.ServletHolder( new DefaultServlet()); //defaultServletHolder.setInitParameter("aliases", Boolean.FALSE.toString()); webAppContext.addServlet(defaultServletHolder, "/"); webAppContext.addEventListener(new HttpSessionListener() { public void sessionDestroyed(HttpSessionEvent se) { session = null;//w w w. ja va2 s. c o m } public void sessionCreated(HttpSessionEvent se) { session = se.getSession(); } }); }
From source file:org.red5.net.websocket.WebSocketPlugin.java
/** * Returns a new instance of WsServerContainer if one does not already exist. * // ww w . j ava 2s .c o m * @param servletContext * @return WsServerContainer */ public static ServerContainer getWsServerContainerInstance(ServletContext servletContext) { String path = servletContext.getContextPath(); // handle root if (path.length() == 0) { path = "/"; } log.info("getWsServerContainerInstance: {}", path); DefaultWsServerContainer container; if (containerMap.containsKey(path)) { container = containerMap.get(path); } else { // instance a server container for WS container = new DefaultWsServerContainer(servletContext); if (log.isDebugEnabled()) { log.debug("Attributes: {} params: {}", Collections.list(servletContext.getAttributeNames()), Collections.list(servletContext.getInitParameterNames())); } // get a configurator instance ServerEndpointConfig.Configurator configurator = (ServerEndpointConfig.Configurator) WebSocketPlugin .getWsConfiguratorInstance(); // check for sub protocols log.debug("Checking for subprotocols"); List<String> subProtocols = new ArrayList<>(); Optional<Object> subProtocolsAttr = Optional .ofNullable(servletContext.getInitParameter("subProtocols")); if (subProtocolsAttr.isPresent()) { String attr = (String) subProtocolsAttr.get(); log.debug("Subprotocols: {}", attr); if (StringUtils.isNotBlank(attr)) { if (attr.contains(",")) { // split them up Stream.of(attr.split(",")).forEach(entry -> { subProtocols.add(entry); }); } else { subProtocols.add(attr); } } } else { // default to allowing any subprotocol subProtocols.add("*"); } log.debug("Checking for CORS"); // check for allowed origins override in this servlet context Optional<Object> crossOpt = Optional.ofNullable(servletContext.getAttribute("crossOriginPolicy")); if (crossOpt.isPresent() && Boolean.valueOf((String) crossOpt.get())) { Optional<String> opt = Optional.ofNullable((String) servletContext.getAttribute("allowedOrigins")); if (opt.isPresent()) { ((DefaultServerEndpointConfigurator) configurator).setAllowedOrigins(opt.get().split(",")); } } log.debug("Checking for endpoint override"); // check for endpoint override and use default if not configured String wsEndpointClass = Optional.ofNullable((String) servletContext.getAttribute("wsEndpointClass")) .orElse("org.red5.net.websocket.server.DefaultWebSocketEndpoint"); try { // locate the endpoint class Class<?> endpointClass = Class.forName(wsEndpointClass); log.debug("startWebSocket - endpointPath: {} endpointClass: {}", path, endpointClass); // build an endpoint config ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(endpointClass, path) .configurator(configurator).subprotocols(subProtocols).build(); // set the endpoint on the server container container.addEndpoint(serverEndpointConfig); } catch (Throwable t) { log.warn("WebSocket endpoint setup exception", t); } // store container for lookup containerMap.put(path, container); // add session listener servletContext.addListener(new HttpSessionListener() { @Override public void sessionCreated(HttpSessionEvent se) { log.debug("sessionCreated: {}", se.getSession().getId()); ServletContext sc = se.getSession().getServletContext(); // Don't trigger WebSocket initialization if a WebSocket Server Container is already present if (sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE) == null) { // grab the container using the servlet context for lookup DefaultWsServerContainer serverContainer = (DefaultWsServerContainer) WebSocketPlugin .getWsServerContainerInstance(sc); // set the container to the context for lookup sc.setAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE, serverContainer); } } @Override public void sessionDestroyed(HttpSessionEvent se) { log.debug("sessionDestroyed: {}", se); container.closeAuthenticatedSession(se.getSession().getId()); } }); } // set the container to the context for lookup servletContext.setAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE, container); return container; }