List of usage examples for javax.servlet ServletContext addListener
public void addListener(Class<? extends EventListener> listenerClass);
From source file:com.dm.estore.config.WebAppInitializer.java
private void registerListener(ServletContext servletContext) { AnnotationConfigWebApplicationContext rootContext = createContext(ApplicationModule.class); // find all classes marked as @Configuration in classpath ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( false);//from w w w. ja v a 2 s. com scanner.addIncludeFilter(new AnnotationTypeFilter(Configuration.class)); //TypeFilter tf = new AssignableTypeFilter(CLASS_YOU_WANT.class); //s.addIncludeFilter(tf); //s.scan("package.you.want1", "package.you.want2"); //String[] beans = bdr.getBeanDefinitionNames(); for (BeanDefinition bd : scanner.findCandidateComponents("com.dm.estore")) { final String beanClassName = bd.getBeanClassName(); final String simpleName = ClassUtils.getShortCanonicalName(beanClassName); if (!excludeFromAutoSearch.contains(beanClassName) && !simpleName.toLowerCase().startsWith(TEST_RESOURCES_PREFIX)) { LOG.warn("Load configuration from: " + bd.getBeanClassName()); try { Class<?> clazz = WebAppInitializer.class.getClassLoader().loadClass(bd.getBeanClassName()); rootContext.register(clazz); } catch (ClassNotFoundException ex) { LOG.error("Unable to load class: " + bd.getBeanClassName(), ex); } } } rootContext.refresh(); servletContext.addListener(new ContextLoaderListener(rootContext)); }
From source file:com.techtrip.dynbl.context.config.WebAppinitializer.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { // Setup Context to Accept Annotated Classes on Input (including plain Spring {@code @Component} // Stereotypes in addition to JSR-330 Compliant Classes using {@code javax.inject} AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); //context.setConfigLocation(APP_CONFIG_LOCATION); context.setConfigLocation(APP_CONFIG_LOCATION); /* // w w w. j a v a 2 s. c o m * Add a Spring Security Filter using the JEE6 Filter Registration Filter Method from {@code FilterRegistration) that allows filters to be registered * and configured with the specified context */ /* FilterRegistration.Dynamic securityFilter = servletContext.addFilter(ProjectKeyValConsts.SECURITY_FILTER.getKey(), new DelegatingFilterProxy(ProjectKeyValConsts.SECURITY_FILTER.getValue())); securityFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, ProjectConsts.BASE_URL_MAPPING_PATTERN.getValue()); // where the filter will be applied */ // Add a Character Encoding Filter that specifies an encoding for mapped requests FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter()); characterEncodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, ROOT_CONTEXT); // where the filter will be applied characterEncodingFilter.setInitParameter("encoding", "UTF-8"); characterEncodingFilter.setInitParameter("forceEncoding", Boolean.TRUE.toString()); characterEncodingFilter.setAsyncSupported(true); servletContext.addListener(new ContextLoaderListener(context)); servletContext.setInitParameter("defaultHtmlEscape", Boolean.TRUE.toString()); DispatcherServlet servlet = new DispatcherServlet(); // no explicit configuration reference here: everything is configured in the root container for simplicity servlet.setContextConfigLocation(""); /* TMT From JEE 6 API Docs: * Registers the given servlet instance with this ServletContext under the given servletName. * The registered servlet may be further configured via the returned ServletRegistration object. */ ServletRegistration.Dynamic appServlet = servletContext.addServlet(APP_SERVLET, servlet); appServlet.setLoadOnStartup(1); appServlet.setAsyncSupported(true); Set<String> mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { throw new IllegalStateException(String.format( "The servlet named '%s' cannot be mapped to '/' under Tomcat versions <= 7.0.14", APP_SERVLET)); } // TMT servletContext.addListener(new Log4jConfigListener()); System.out.println("Application inplemented on Spring Version: " + SpringVersion.getVersion()); }
From source file:fr.treeptik.cloudunit.initializer.ApplicationConfig.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(CloudUnitApplicationContext.class); ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(rootContext)); dispatcher.setLoadOnStartup(1);// w w w. j av a 2 s .com dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING); dispatcher.setAsyncSupported(true); FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); EnumSet<DispatcherType> securityDispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/user/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/file/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/logs/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/messages/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/application/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/server/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/snapshot/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/module/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/admin/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/image/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/nopublic/*"); security.setAsyncSupported(true); servletContext.addListener(new ContextLoaderListener(rootContext)); }
From source file:cn.org.once.cstack.initializer.ApplicationConfig.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(CloudUnitApplicationContext.class); ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(rootContext)); dispatcher.setLoadOnStartup(1);//from ww w.jav a 2s .c om dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING); dispatcher.setAsyncSupported(true); FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); EnumSet<DispatcherType> securityDispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/user/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/file/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/logs/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/messages/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/application/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/server/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/snapshot/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/module/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/admin/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/image/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/scripting/*"); security.addMappingForUrlPatterns(securityDispatcherTypes, false, "/gitlab/*"); security.setAsyncSupported(true); servletContext.addListener(new ContextLoaderListener(rootContext)); }
From source file:org.smigo.config.WebAppInitializer.java
@Override protected void beforeSpringSecurityFilterChain(ServletContext servletContext) { super.beforeSpringSecurityFilterChain(servletContext); log.info("Starting servlet context"); log.info("contextName: " + servletContext.getServletContextName()); log.info("contextPath:" + servletContext.getContextPath()); log.info("effectiveMajorVersion:" + servletContext.getEffectiveMajorVersion()); log.info("effectiveMinorVersion:" + servletContext.getEffectiveMinorVersion()); log.info("majorVersion:" + servletContext.getMajorVersion()); log.info("minorVersion:" + servletContext.getMinorVersion()); log.info("serverInfo:" + servletContext.getServerInfo()); // ", virtualServerName:" + servletContext.getVirtualServerName() + log.info("toString:" + servletContext.toString()); for (Enumeration<String> e = servletContext.getAttributeNames(); e.hasMoreElements();) { log.info("Attribute:" + e.nextElement()); }/*from w ww . j a va 2 s . c o m*/ for (Map.Entry<String, String> env : System.getenv().entrySet()) { log.info("System env:" + env.toString()); } for (Map.Entry<Object, Object> prop : System.getProperties().entrySet()) { log.info("System prop:" + prop.toString()); } final String profile = System.getProperty("smigoProfile", EnvironmentProfile.PRODUCTION); log.info("Starting with profile " + profile); WebApplicationContext context = new AnnotationConfigWebApplicationContext() { { register(WebConfiguration.class); setDisplayName("SomeRandomName"); getEnvironment().setActiveProfiles(profile); } }; FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("CharacterEncodingFilter", new CharacterEncodingFilter()); characterEncodingFilter.setInitParameter("encoding", "UTF-8"); characterEncodingFilter.setInitParameter("forceEncoding", "true"); characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*"); servletContext.addListener(new RequestContextListener()); servletContext.addListener(new ContextLoaderListener(context)); //http://stackoverflow.com/questions/4811877/share-session-data-between-2-subdomains // servletContext.getSessionCookieConfig().setDomain(getDomain()); DispatcherServlet dispatcherServlet = new DispatcherServlet(context); dispatcherServlet.setThrowExceptionIfNoHandlerFound(false); servletContext.addServlet("dispatcher", dispatcherServlet).addMapping("/"); }
From source file:com.jsmartframework.web.manager.ContextControl.java
@Override @SuppressWarnings("unchecked") public void contextInitialized(ServletContextEvent event) { try {//from www . ja va 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.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);/*w w w. java 2s . 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("/*"); }
From source file:org.red5.net.websocket.WebSocketPlugin.java
/** * Returns a new instance of WsServerContainer if one does not already exist. * /* w w w. j a v a 2s . com*/ * @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; }
From source file:org.springframework.boot.context.embedded.ServletListenerRegistrationBean.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { if (!isEnabled()) { logger.info("Listener " + this.listener + " was not registered (disabled)"); return;/*from w w w.j av a 2s .co m*/ } try { servletContext.addListener(this.listener); } catch (RuntimeException ex) { throw new IllegalStateException("Failed to add listener '" + this.listener + "' to servlet context", ex); } }
From source file:org.springframework.boot.context.web.SpringBootServletInitializer.java
@Override public void onStartup(ServletContext servletContext) throws ServletException { // Logger initialization is deferred in case a ordered // LogServletContextInitializer is being used this.logger = LogFactory.getLog(getClass()); WebApplicationContext rootAppContext = createRootApplicationContext(servletContext); if (rootAppContext != null) { servletContext.addListener(new ContextLoaderListener(rootAppContext) { @Override//w w w . j a va 2 s . co m public void contextInitialized(ServletContextEvent event) { // no-op because the application context is already initialized } }); } else { this.logger.debug("No ContextLoaderListener registered, as " + "createRootApplicationContext() did not " + "return an application context"); } }