List of usage examples for javax.servlet ServletContextEvent getServletContext
public ServletContext getServletContext()
From source file:no.kantega.publishing.spring.LogInitListener.java
public void contextInitialized(ServletContextEvent servletContextEvent) { loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); if (notAksessRun()) { final File dataDirectory = (File) servletContextEvent.getServletContext() .getAttribute(DataDirectoryContextListener.DATA_DIRECTORY_ATTR); if (dataDirectory == null) { throw new NullPointerException("dataDirectory attribute " + DataDirectoryContextListener.DATA_DIRECTORY_ATTR + " was not set"); }// www. ja v a2 s . c om // Ensure log directory exists final File logsDirectory = new File(dataDirectory, "logs"); logsDirectory.mkdirs(); try { String autoConfig = System.getProperty("logback.autoconfig"); if (autoConfig == null) { final File configFile = new File(new File(dataDirectory, "conf"), "logback.groovy"); if (!configFile.exists()) { writeDefaultConfigFile(configFile); } loggerContext.reset(); loggerContext.putProperty("logdir", logsDirectory.getAbsolutePath()); System.setProperty("logdir", logsDirectory.getAbsolutePath()); ContextInitializer contextInitializer = new ContextInitializer(loggerContext); contextInitializer.configureByResource(configFile.toURI().toURL()); LoggerFactory.getLogger(getClass()).info("Configured logging using logdir {}", logsDirectory.getAbsolutePath()); } } catch (Exception je) { je.printStackTrace(); } StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); } }
From source file:ejportal.webapp.listener.StartupListener.java
/** * {@inheritDoc}//from w w w . j a v a2 s . co m */ @SuppressWarnings("unchecked") public void contextInitialized(final ServletContextEvent event) { StartupListener.log.debug("Initializing context..."); final ServletContext context = event.getServletContext(); // Orion starts Servlets before Listeners, so check if the config // object already exists Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG); if (config == null) { config = new HashMap<String, Object>(); } if (context.getInitParameter(Constants.CSS_THEME) != null) { config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME)); } final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); /* * String[] beans = ctx.getBeanDefinitionNames(); for (String bean : * beans) { log.debug(bean); } */ PasswordEncoder passwordEncoder = null; try { final ProviderManager provider = (ProviderManager) ctx.getBean("_authenticationManager"); for (final Object o : provider.getProviders()) { final AuthenticationProvider p = (AuthenticationProvider) o; if (p instanceof RememberMeAuthenticationProvider) { config.put("rememberMeEnabled", Boolean.TRUE); } else if (ctx.getBean("passwordEncoder") != null) { passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder"); } } } catch (final NoSuchBeanDefinitionException n) { StartupListener.log.debug("authenticationManager bean not found, assuming test and ignoring..."); // ignore, should only happen when testing } context.setAttribute(Constants.CONFIG, config); // output the retrieved values for the Init and Context Parameters if (StartupListener.log.isDebugEnabled()) { StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled")); if (passwordEncoder != null) { StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName()); } StartupListener.log.debug("Populating drop-downs..."); } StartupListener.setupContext(context); }
From source file:it.tidalwave.northernwind.frontend.util.NorthernWindContextLoaderListener.java
/******************************************************************************************************************* * * {@inheritDoc}/*from w w w. j a va2 s . com*/ * ******************************************************************************************************************/ @Override public void contextInitialized(final @Nonnull ServletContextEvent event) { try { log.log("Initializing Spring..."); super.contextInitialized( new ServletContextEvent(new ServletContextDecorator(event.getServletContext()))); } catch (Throwable t) { event.getServletContext().setAttribute(ATTRIBUTE_BOOT_THROWABLE, t); } }
From source file:org.smartfrog.avalanche.server.AvalancheContextListener.java
/** * Needs following attributes in the web.xml for webapp * xmppServer (default is localhost) // w ww. j av a 2 s . c o m * xmppServerPort (default is 5223) * useSSLForXMPP ( default is true ) * xmppServerAdminUsername (mandatory) * xmppServerAdminPassword (mandatory) * avalancheHome (AVALANCHE_HOME on server) */ public void contextInitialized(ServletContextEvent evt) { // set up Avalanche XMPP adapters, this assumes XMPP server is already up // running try { String securityOn = evt.getServletContext().getInitParameter("securityOn"); setup.getFactory().setAttribute(setup.getFactory().SECURITY_ON, securityOn); String xmppServer = evt.getServletContext().getInitParameter("xmppServer"); if (null != xmppServer) { setup.setXmppServer(xmppServer); setup.getFactory().setAttribute(setup.getFactory().XMPP_SERVER_NAME, xmppServer); } String xmppServerPort = evt.getServletContext().getInitParameter("xmppServerPort"); if (null != xmppServerPort) { setup.setXmppServerPort(Integer.parseInt(xmppServerPort)); } String useSSL = evt.getServletContext().getInitParameter("useSSLForXMPP"); if (null != useSSL) { setup.setUseSSLForXMPP(Boolean.parseBoolean(useSSL)); } String xmppAdmin = evt.getServletContext().getInitParameter("xmppServerAdminUsername"); String xmppAdminPass = evt.getServletContext().getInitParameter("xmppServerAdminPassword"); setup.setXmppServerAdminUser(xmppAdmin); setup.setXmppServerAdminPassword(xmppAdminPass); String avalancheHome = evt.getServletContext().getInitParameter("avalancheHome"); setup.setAvalancheHome(avalancheHome); // String avalancheServerOS = evt.getServletContext().getInitParameter("avalancheServerOS"); // setup.setAvalancheServerOS(avalancheServerOS); String avalancheServerName = evt.getServletContext().getInitParameter("avalancheServerName"); setup.getFactory().setAttribute(setup.getFactory().AVALANCHE_SERVER_NAME, avalancheServerName); //Start Quartz Scheduler log.info("Initializing"); SchedulerFactory schedFact = new StdSchedulerFactory(); scheduler = schedFact.getScheduler(); log.info("Initialization Complete"); scheduler.start(); log.info("Started Scheduler"); // setup.setScheduler(scheduler); //Scheduler scheduler1 = setup.getScheduler(); //log.info("Scheduler===" + scheduler1.getSchedulerName()); setup.startup(); evt.getServletContext().setAttribute("avalancheFactory", setup.getFactory()); evt.getServletContext().setAttribute("scheduler", scheduler); } catch (Exception e) { log.fatal("Avalanche InitializAtion failed : ", e); } }
From source file:alpha.portal.webapp.listener.StartupListener.java
/** * {@inheritDoc}/*from w w w.j a v a 2s .c o m*/ */ @SuppressWarnings("unchecked") public void contextInitialized(final ServletContextEvent event) { StartupListener.log.debug("Initializing context..."); final ServletContext context = event.getServletContext(); // Orion starts Servlets before Listeners, so check if the config // object already exists Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG); if (config == null) { config = new HashMap<String, Object>(); } if (context.getInitParameter(Constants.CSS_THEME) != null) { config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME)); } final ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); /* * String[] beans = ctx.getBeanDefinitionNames(); for (String bean : * beans) { log.debug(bean); } */ PasswordEncoder passwordEncoder = null; try { final ProviderManager provider = (ProviderManager) ctx .getBean("org.springframework.security.authentication.ProviderManager#0"); for (final Object o : provider.getProviders()) { final AuthenticationProvider p = (AuthenticationProvider) o; if (p instanceof RememberMeAuthenticationProvider) { config.put("rememberMeEnabled", Boolean.TRUE); } else if (ctx.getBean("passwordEncoder") != null) { passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder"); } } } catch (final NoSuchBeanDefinitionException n) { StartupListener.log.debug("authenticationManager bean not found, assuming test and ignoring..."); // ignore, should only happen when testing } context.setAttribute(Constants.CONFIG, config); // output the retrieved values for the Init and Context Parameters if (StartupListener.log.isDebugEnabled()) { StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled")); if (passwordEncoder != null) { StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName()); } StartupListener.log.debug("Populating drop-downs..."); } StartupListener.setupContext(context); }
From source file:edu.du.penrose.systems.fedoraProxy.util.FedoraProxyServletContextListener.java
public void contextInitialized(ServletContextEvent context) { FedoraProxyServletContextListener.myServletContext = context.getServletContext(); String realPath = myServletContext.getRealPath("/"); if (!realPath.endsWith("" + File.separatorChar)) { realPath = realPath + File.separatorChar; }/*w w w . j ava 2 s . c o m*/ System.setProperty("fedoraProxy.root", realPath); }
From source file:org.musicrecital.webapp.listener.StartupListener.java
/** * {@inheritDoc}/* ww w. jav a2 s . c o m*/ */ @SuppressWarnings("unchecked") public void contextInitialized(ServletContextEvent event) { log.debug("Initializing context..."); ServletContext context = event.getServletContext(); // Orion starts Servlets before Listeners, so check if the config // object already exists Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG); if (config == null) { config = new HashMap<String, Object>(); } ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); PasswordEncoder passwordEncoder = null; try { ProviderManager provider = (ProviderManager) ctx .getBean("org.springframework.security.authentication.ProviderManager#0"); for (Object o : provider.getProviders()) { AuthenticationProvider p = (AuthenticationProvider) o; if (p instanceof RememberMeAuthenticationProvider) { config.put("rememberMeEnabled", Boolean.TRUE); } else if (ctx.getBean("passwordEncoder") != null) { passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder"); } } } catch (NoSuchBeanDefinitionException n) { log.debug("authenticationManager bean not found, assuming test and ignoring..."); // ignore, should only happen when testing } context.setAttribute(Constants.CONFIG, config); // output the retrieved values for the Init and Context Parameters if (log.isDebugEnabled()) { log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled")); if (passwordEncoder != null) { log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName()); } log.debug("Populating drop-downs..."); } setupContext(context); // Determine version number for CSS and JS Assets String appVersion = null; try { InputStream is = context.getResourceAsStream("/META-INF/MANIFEST.MF"); if (is == null) { log.warn("META-INF/MANIFEST.MF not found."); } else { Manifest mf = new Manifest(); mf.read(is); Attributes atts = mf.getMainAttributes(); appVersion = atts.getValue("Implementation-Version"); } } catch (IOException e) { log.error("I/O Exception reading manifest: " + e.getMessage()); } // If there was a build number defined in the war, then use it for // the cache buster. Otherwise, assume we are in development mode // and use a random cache buster so developers don't have to clear // their browser cache. if (appVersion == null || appVersion.contains("SNAPSHOT")) { appVersion = "" + new Random().nextInt(100000); } log.info("Application version set to: " + appVersion); context.setAttribute(Constants.ASSETS_VERSION, appVersion); }
From source file:org.tonguetied.web.servlet.ServletContextInitializer.java
/** * Perform server servlet initialization. When the servlet is first * initialized, the server system properties are set. These server * properties are used in the domain layer, but are not known until the web * application is deployed and started. Also loads application wide * variables including://from w ww . j a v a2s. c om * <ul> * <li>the list of supported languages</li> * </ul> * * This method also performs database management. It determines if this * server should run an embedded database, ie it is in demo mode, and * starts the database. It also creates the database, the first time it * connects to the server. * * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ public void contextInitialized(ServletContextEvent event) { loadSupportedLanguages(event.getServletContext()); WebApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(event.getServletContext()); AdministrationService administrationService = (AdministrationService) applicationContext .getBean("administrationService"); Properties props = loadProperties(event.getServletContext(), DIR_WEB_INF + "/jdbc.properties"); final String dialect = props.getProperty(KEY_HIBERNATE_DIALECT); if (EmbeddedDatabaseServer.isEmbeddable(dialect)) EmbeddedDatabaseServer.startDatabase(props); ServerData serverData = administrationService.getLatestData(); // If server data does not exist then assume the database has not been // created if (serverData == null) { if (logger.isDebugEnabled()) logger.debug("attempting to create database"); final String[] schemas = loadSchemas(event.getServletContext(), dialect, administrationService); administrationService.createDatabase(schemas); serverData = createServerData(event.getServletContext()); if (serverData != null) administrationService.saveOrUpdate(serverData); } // check if we need to update else { if (logger.isDebugEnabled()) logger.debug("attempting to update database"); ServerData curServerData = createServerData(event.getServletContext()); if (curServerData.compareTo(serverData) > 0) { // final String[] schemas = loadSchemas(event.getServletContext(), dialect, curServerData.getVersion()); // administrationService.createDatabase(schemas); administrationService.saveOrUpdate(curServerData); } } if (logger.isInfoEnabled()) { logger.info("Charset for this JVM: " + Charset.defaultCharset()); } }
From source file:org.apache.usergrid.chop.webapp.ChopUiConfig.java
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { context = servletContextEvent.getServletContext(); context.setAttribute(Injector.class.getName(), getInjector()); Injector injector = getInjector();// w w w .jav a 2s .c o m ElasticSearchFig elasticSearchFig = injector.getInstance(ElasticSearchFig.class); ChopUiFig chopUiFig = injector.getInstance(ChopUiFig.class); /* * -------------------------------------------------------------------- * Archaius Configuration Settings * -------------------------------------------------------------------- */ ConcurrentCompositeConfiguration ccc = new ConcurrentCompositeConfiguration(); Env env = Env.getEnvironment(); boolean embedded = false; if (env == Env.ALL) { ConfigurationManager.getDeploymentContext().setDeploymentEnvironment("PROD"); LOG.info("Setting environment to: PROD"); /* * -------------------------------------------------------------------- * Extract Configuration Settings from CommandLine * -------------------------------------------------------------------- */ if (ChopUiJettyRunner.getCommandLine() != null) { CommandLine cl = ChopUiJettyRunner.getCommandLine(); if (cl.hasOption('d')) { String dataDir = cl.getOptionValue('d'); LOG.info("The -d option is given, replacing data directory with {}", dataDir); elasticSearchFig.bypass(ElasticSearchFig.DATA_DIR_KEY, dataDir); } if (cl.hasOption('e')) { startEmbeddedES(elasticSearchFig); } if (cl.hasOption('c')) { String serverHostPort = cl.getOptionValue('c'); int seperatorIndex = serverHostPort.indexOf(":"); String serverHost = serverHostPort.substring(0, seperatorIndex); String serverPort = serverHostPort.substring(seperatorIndex + 1, serverHostPort.length()); LOG.info("The -c option is given, replacing host with {} and port with {}", serverHost, serverPort); elasticSearchFig.bypass(ElasticSearchFig.SERVERS_KEY, serverHost); elasticSearchFig.bypass(ElasticSearchFig.PORT_KEY, serverPort); } if (cl.hasOption('n')) { String clusterName = cl.getOptionValue('n'); elasticSearchFig.bypass(ElasticSearchFig.CLUSTER_NAME_KEY, clusterName); } } else { LOG.warn("ChopUi not started via Launcher - no command line argument processing will take place."); } } else if (env == Env.UNIT) { LOG.info("Operating in UNIT environment"); } try { ConfigurationManager.loadCascadedPropertiesFromResources("chop-ui"); } catch (IOException e) { LOG.warn("Failed to cascade load configuration properties: ", e); } /* * -------------------------------------------------------------------- * Environment Based Configuration Property Adjustments * -------------------------------------------------------------------- */ if (LOG.isDebugEnabled()) { Enumeration<String> names = context.getAttributeNames(); LOG.debug("Dumping attribute names: "); while (names.hasMoreElements()) { String name = names.nextElement(); LOG.debug("attribute {} = {}", name, context.getAttribute(name)); } } // Checking if a temp directory is defined - usually null String contextTempDir = (String) context.getAttribute(CONTEXT_TEMPDIR_KEY); LOG.info("From servlet context: {} = {}", CONTEXT_TEMPDIR_KEY, contextTempDir); if (contextTempDir == null) { LOG.info("From ChopUiFig {} = {}", CONTEXT_TEMPDIR_KEY, chopUiFig.getContextTempDir()); } setupStorage(); }
From source file:org.kimios.core.CoreListener.java
public void contextInitialized(ServletContextEvent event) { try {/*from w ww.jav a 2 s .c o m*/ this.contextLoader = this; /* Check config file exist */ String settingsPath = event.getServletContext().getRealPath("/WEB-INF/kimios.properties"); File f = new File(settingsPath); if (!f.exists()) { /* Load Port From environment */ try { String serverPort = System.getProperty("kimios.service.port"); String serverWebAppName = System.getenv("kimios.service.appname"); serverWebAppName = serverWebAppName != null && serverWebAppName.length() > 0 ? serverWebAppName : "kimios"; serverPort = serverPort != null && serverPort.length() > 0 ? serverPort : "8080"; log.info("Kimios Web Client is running on " + serverPort); /* Generate file and, include server port */ Properties webProperties = new Properties(); webProperties.setProperty(Config.DM_CHUNK_SIZE, "102400"); webProperties.setProperty(Config.DM_SERVER_URL, "http://127.0.0.1:" + serverPort + "/" + serverWebAppName); webProperties.setProperty(Config.DM_SERVICE_CONTEXT, "/services"); String temporaryPathName = "kimios-tmp"; File temporaryDirectory = new File(temporaryPathName); temporaryDirectory.mkdirs(); webProperties.setProperty(Config.DM_TMP_FILES_PATH, temporaryPathName); webProperties.store(new FileWriterWithEncoding(f, "UTF-8"), "Kimios Settings File generated by the Kimios Deployer\n\n" + "Copyright @ Devlib' 2012-2013" + "Authors: Jrme LUDMANN, Fabien ALIN"); } catch (Exception e) { log.error("Error while generating automatic settings", e); f = null; } } if (f != null && f.exists()) { SpringWebContextLauncher.launchApp(event.getServletContext(), this.contextLoader); InternationalizationManager.getInstance("EN"); CoreInitializer.contextInitialized(event.getServletContext().getRealPath("/")); Controller.init(event.getServletContext()); new FileCleaner().cleanTemporaryFiles( new File(ConfigurationManager.getValue(Config.DM_TMP_FILES_PATH).toString())); } else { log.error("Kimios Web Client Setting not found. Application unavailable"); } } catch (Exception e) { log.error("kimios Client Listener", e); } }