List of usage examples for javax.servlet ServletContext setAttribute
public void setAttribute(String name, Object object);
From source file:org.quartz.ee.servlet.QuartzInitializerListener.java
public void contextInitialized(ServletContextEvent sce) { log.info("Quartz Initializer Servlet loaded, initializing Scheduler..."); ServletContext servletContext = sce.getServletContext(); StdSchedulerFactory factory;//from w w w . jav a2 s .co m try { String configFile = servletContext.getInitParameter("config-file"); String shutdownPref = servletContext.getInitParameter("shutdown-on-unload"); if (shutdownPref != null) { performShutdown = Boolean.valueOf(shutdownPref).booleanValue(); } // get Properties if (configFile != null) { factory = new StdSchedulerFactory(configFile); } else { factory = new StdSchedulerFactory(); } // Always want to get the scheduler, even if it isn't starting, // to make sure it is both initialized and registered. scheduler = factory.getScheduler(); // Should the Scheduler being started now or later String startOnLoad = servletContext.getInitParameter("start-scheduler-on-load"); int startDelay = 0; String startDelayS = servletContext.getInitParameter("start-delay-seconds"); try { if (startDelayS != null && startDelayS.trim().length() > 0) startDelay = Integer.parseInt(startDelayS); } catch (Exception e) { log.error("Cannot parse value of 'start-delay-seconds' to an integer: " + startDelayS + ", defaulting to 5 seconds."); startDelay = 5; } /* * If the "start-scheduler-on-load" init-parameter is not specified, * the scheduler will be started. This is to maintain backwards * compatability. */ if (startOnLoad == null || (Boolean.valueOf(startOnLoad).booleanValue())) { if (startDelay <= 0) { // Start now scheduler.start(); log.info("Scheduler has been started..."); } else { // Start delayed scheduler.startDelayed(startDelay); log.info("Scheduler will start in " + startDelay + " seconds."); } } else { log.info("Scheduler has not been started. Use scheduler.start()"); } String factoryKey = servletContext.getInitParameter("servlet-context-factory-key"); if (factoryKey == null) { factoryKey = QUARTZ_FACTORY_KEY; } log.info("Storing the Quartz Scheduler Factory in the servlet context at key: " + factoryKey); servletContext.setAttribute(factoryKey, factory); } catch (Exception e) { log.error("Quartz Scheduler failed to initialize: " + e.toString()); e.printStackTrace(); } }
From source file:com.concursive.connect.config.ApplicationPrefs.java
/** * Description of the Method// w w w. j av a 2 s. c o m * * @param context Description of the Parameter */ public void configureConnectionPool(ServletContext context) { LOG.info("configureConnectionPool"); //Define the ConnectionPool, else defaults from the ContextListener will be used ConnectionPool cp = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL); if (cp != null) { // Apply any settings if (this.has(CONNECTION_POOL_DEBUG)) { cp.setDebug(this.get(CONNECTION_POOL_DEBUG)); } if (this.has(CONNECTION_POOL_TEST_CONNECTIONS)) { cp.setTestConnections(this.get(CONNECTION_POOL_TEST_CONNECTIONS)); } if (this.has(CONNECTION_POOL_ALLOW_SHRINKING)) { cp.setAllowShrinking(this.get(CONNECTION_POOL_ALLOW_SHRINKING)); } if (this.has(CONNECTION_POOL_MAX_CONNECTIONS)) { cp.setMaxConnections(this.get(CONNECTION_POOL_MAX_CONNECTIONS)); } if (this.has(CONNECTION_POOL_MAX_IDLE_TIME)) { cp.setMaxIdleTimeSeconds(this.get(CONNECTION_POOL_MAX_IDLE_TIME)); } if (this.has(CONNECTION_POOL_MAX_DEAD_TIME)) { cp.setMaxDeadTimeSeconds(this.get(CONNECTION_POOL_MAX_DEAD_TIME)); } // Clone it for RSS Feeds if (this.get(CONNECTION_POOL_MAX_RSS_CONNECTIONS) != null) { ConnectionPool rssCP = new ConnectionPool(); rssCP.setDebug(cp.getDebug()); rssCP.setTestConnections(cp.getTestConnections()); rssCP.setAllowShrinking(cp.getAllowShrinking()); rssCP.setMaxConnections(this.get(CONNECTION_POOL_MAX_RSS_CONNECTIONS)); rssCP.setMaxIdleTime(cp.getMaxIdleTime()); rssCP.setMaxDeadTime(cp.getMaxDeadTime()); context.setAttribute(Constants.CONNECTION_POOL_RSS, rssCP); } else { context.setAttribute(Constants.CONNECTION_POOL_RSS, cp); } // Clone it for API Requests if (this.get(CONNECTION_POOL_MAX_API_CONNECTIONS) != null) { ConnectionPool apiCP = new ConnectionPool(); apiCP.setDebug(cp.getDebug()); apiCP.setTestConnections(cp.getTestConnections()); apiCP.setAllowShrinking(cp.getAllowShrinking()); apiCP.setMaxConnections(this.get(CONNECTION_POOL_MAX_API_CONNECTIONS)); apiCP.setMaxIdleTime(cp.getMaxIdleTime()); apiCP.setMaxDeadTime(cp.getMaxDeadTime()); context.setAttribute(Constants.CONNECTION_POOL_API, apiCP); } else { context.setAttribute(Constants.CONNECTION_POOL_API, cp); } } else { LOG.error("ConnectionPool is null"); } }
From source file:hudson.model.Hudson.java
private static void computeVersion(ServletContext context) { // set the version Properties props = new Properties(); try {/*from w w w . j av a2s. co m*/ InputStream is = Hudson.class.getResourceAsStream("hudson-version.properties"); if (is != null) props.load(is); } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } String ver = props.getProperty("version"); if (ver == null) ver = "?"; VERSION = ver; context.setAttribute("version", ver); VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); if (ver.equals("?") || Boolean.getBoolean("hudson.script.noCache")) RESOURCE_PATH = ""; else RESOURCE_PATH = "/static/" + VERSION_HASH; VIEW_RESOURCE_PATH = "/resources/" + VERSION_HASH; }
From source file:org.sindice.servlet.sparqlqueryservlet.ServletConfigurationContextListener.java
@Override public void contextInitialized(ServletContextEvent sce) { final ServletContext context = sce.getServletContext(); String contextPath = context.getContextPath().replaceFirst("^/", ""); if (contextPath.equals("")) { // application deployed in ROOT context String applicationName = context.getInitParameter("applicationName"); if (applicationName != null && !applicationName.equals("")) { contextPath = "ROOT_" + applicationName; } else {// w ww .j a v a 2 s . c om contextPath = "ROOT"; } logger.warn("Application deployed in ROOT context."); } else { logger.info("Application deployed in [" + contextPath + "] context."); } logger.info("Will use [" + contextPath + "] as a part of a path for reading/storing configuration"); String servletContextName = context.getServletContextName(); addEnvToContext(context); String sindiceHome = null; // FOR DEBIAN PACKAGE LOD2 PROJECT INTEGRATION // check that following directory exists // if yes please use it if (new File("/etc/" + contextPath + "/config.xml").exists()) { sindiceHome = "/etc"; logger.info("Found config.xml at [/etc/" + contextPath + "/config.xml]. Setting sindiceHome to : [" + sindiceHome + "]"); } else { logger.info( "File /etc/" + contextPath + "/config.xml does not exists will try to determine sindiceHome"); } // END DEBIAN PACKAGE LOD2 PROJECT INTEGRATION if (sindiceHome == null && context.getAttribute("sindice.home") != null) { sindiceHome = (String) context.getAttribute("sindice.home"); logger.info("Setting sindiceHome from sindice.home env variable to [" + sindiceHome + "]"); } if (sindiceHome == null && context.getAttribute("SINDICE_HOME") != null) { sindiceHome = (String) context.getAttribute("SINDICE_HOME"); logger.info("Setting sindiceHome from SINDICE_HOME env variable to [" + sindiceHome + "]"); } if (sindiceHome == null || "".equals(sindiceHome.trim())) { String userHome = (String) context.getAttribute("user.home"); sindiceHome = (userHome == null ? "" : userHome) + File.separatorChar + "sindice"; logger.warn("Neither sindice.home nor SINDICE_HOME are not defined, assuming {}", sindiceHome); } logger.info("Looking for configuration in [" + sindiceHome + File.separatorChar + contextPath + "]"); // important to set these two as they are used later in logback.xml context.setAttribute("sindice.home", sindiceHome); context.setAttribute("app.name", contextPath); File configFolder = new File(sindiceHome + File.separatorChar + contextPath); if (!(configFolder.exists() && configFolder.isDirectory())) { logger.warn("Missing configuration folder {}", configFolder); if (configFolder.mkdirs()) { logger.warn("Creating default configuration at " + configFolder); } else { // set logging level to INFO configureLogging(context, configFolder); return; } } // does a specific folder exist for this servlet context? if (servletContextName == null) { logger.error("specify display-name element in web.xml !!! "); } else { File specificFolder = new File(configFolder, servletContextName); if (specificFolder.exists() && specificFolder.isDirectory()) { configFolder = specificFolder; } } logger.info("loading configuration from folder {}", configFolder); configureLogging(context, configFolder); final XMLConfiguration config = createXMLConfiguration(context); File applicationConfigFile = new File(configFolder, "config.xml"); if (!applicationConfigFile.exists()) { logger.warn("missing application config file {}", applicationConfigFile); loadDefaultConfiguration(config, applicationConfigFile); } else { try { config.load(applicationConfigFile); logger.info("parsed {}", applicationConfigFile); } catch (ConfigurationException e) { logger.error("Could not load configuration from {}", applicationConfigFile, e); loadDefaultConfiguration(config, null); } } context.setAttribute("config", config); logger.info("config now availabe via the following line of code\n" + " XMLConfiguration appConfig = (XMLConfiguration) servletContext.getAttribute(\"config\");"); logger.info("Starting up {}", servletContextName); }
From source file:org.sindice.analytics.servlet.ServletConfigurationContextListener.java
@Override public void contextInitialized(ServletContextEvent sce) { final ServletContext context = sce.getServletContext(); String contextPath = context.getContextPath().replaceFirst("^/", ""); if (contextPath.equals("")) { // application deployed in ROOT context String applicationName = context.getInitParameter("applicationName"); if (applicationName != null && !applicationName.equals("")) { contextPath = "ROOT_" + applicationName; } else {//from w ww .j av a2 s . co m contextPath = "ROOT"; } logger.warn("Application deployed in ROOT context."); } else { logger.info("Application deployed in [" + contextPath + "] context."); } logger.info("Will use [" + contextPath + "] as a part of a path for reading/storing configuration"); String servletContextName = context.getServletContextName(); addEnvToContext(context); String sindiceHome = null; // FOR DEBIAN PACKAGE LOD2 PROJECT INTEGRATION // check that following directory exists // if yes please use it if (new File("/etc/" + contextPath + "/config.xml").exists()) { sindiceHome = "/etc"; logger.info("Found config.xml at [/etc/" + contextPath + "/config.xml]. Setting sindiceHome to : [" + sindiceHome + "]"); } else { logger.info( "File /etc/" + contextPath + "/config.xml does not exists will try to determine sindiceHome"); } // END DEBIAN PACKAGE LOD2 PROJECT INTEGRATION if (sindiceHome == null && context.getAttribute("sindice.home") != null) { sindiceHome = (String) context.getAttribute("sindice.home"); logger.info("Setting sindiceHome from sindice.home env variable to [" + sindiceHome + "]"); } if (sindiceHome == null && context.getAttribute("SINDICE_HOME") != null) { sindiceHome = (String) context.getAttribute("SINDICE_HOME"); logger.info("Setting sindiceHome from SINDICE_HOME env variable to [" + sindiceHome + "]"); } if (sindiceHome == null || "".equals(sindiceHome.trim())) { String userHome = (String) context.getAttribute("user.home"); sindiceHome = (userHome == null ? "" : userHome) + File.separatorChar + "sindice"; logger.warn("Neither sindice.home nor SINDICE_HOME are not defined, assuming {}", sindiceHome); } logger.info("Looking for configuration in [" + sindiceHome + File.separatorChar + contextPath + "]"); // important to set these two as they are used later in logback.xml context.setAttribute("sindice.home", sindiceHome); context.setAttribute("app.name", contextPath); configFolder = new File(sindiceHome + File.separatorChar + contextPath); if (!(configFolder.exists() && configFolder.isDirectory())) { logger.warn("Missing configuration folder {}", configFolder); if (configFolder.mkdirs()) { logger.warn("Creating default configuration at " + configFolder); } else { // set logging level to INFO configureLogging(context, configFolder); return; } } // does a specific folder exist for this servlet context? if (servletContextName == null) { logger.error("specify display-name element in web.xml !!! "); } else { File specificFolder = new File(configFolder, servletContextName); if (specificFolder.exists() && specificFolder.isDirectory()) { configFolder = specificFolder; } } logger.info("loading configuration from folder {}", configFolder); configureLogging(context, configFolder); final XMLConfiguration config = createXMLConfiguration(context); File applicationConfigFile = new File(configFolder, "config.xml"); if (!applicationConfigFile.exists()) { logger.warn("missing application config file {}", applicationConfigFile); loadDefaultConfiguration(config, applicationConfigFile); } else { try { config.load(applicationConfigFile); logger.info("parsed {}", applicationConfigFile); } catch (ConfigurationException e) { logger.error("Could not load configuration from {}", applicationConfigFile, e); loadDefaultConfiguration(config, null); } } context.setAttribute("config", config); logger.info("config now availabe via the following line of code\n" + " XMLConfiguration appConfig = (XMLConfiguration) servletContext.getAttribute(\"config\");"); logger.info("Starting up {}", servletContextName); }
From source file:org.wso2.carbon.mdm.mobileservices.windows.common.util.ConfigInitializerContextListener.java
/** * This method loads wap-provisioning file / property file, sets wap-provisioning file and * extracted properties as attributes in servlet context. * * @param servletContextEvent - Uses when servlet communicating with servlet container. *//*w ww . j ava 2s .c o m*/ @Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); File propertyFile = new File(getClass().getClassLoader() .getResource(PluginConstants.CertificateEnrolment.PROPERTIES_XML).getFile()); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; Document document = null; try { docBuilder = docBuilderFactory.newDocumentBuilder(); if (docBuilder != null) { document = docBuilder.parse(propertyFile); } } catch (ParserConfigurationException e) { log.error("Parser configuration failure while reading properties.xml."); } catch (SAXException e) { log.error("Parsing error occurred while reading properties.xml."); } catch (IOException e) { log.error("File reading error occurred while accessing properties.xml."); } String password = null; String privateKeyPassword = null; String signedCertCommonName = null; String authPolicy = null; String domain = null; int signedCertNotBeforeDate = INITIAL_VALUE; int signedCertNotAfterDate = INITIAL_VALUE; if (document != null) { password = document.getElementsByTagName(PropertyName.PROPERTY_PASSWORD.getValue()).item(0) .getTextContent(); privateKeyPassword = document .getElementsByTagName(PropertyName.PROPERTY_PRIVATE_KEY_PASSWORD.getValue()).item(0) .getTextContent(); signedCertCommonName = document.getElementsByTagName(PropertyName.PROPERTY_SIGNED_CERT_CN.getValue()) .item(0).getTextContent(); authPolicy = document.getElementsByTagName(PropertyName.AUTH_POLICY.getValue()).item(0) .getTextContent(); signedCertNotBeforeDate = Integer .valueOf(document.getElementsByTagName(PropertyName.PROPERTY_SIGNED_CERT_NOT_BEFORE.getValue()) .item(0).getTextContent()); signedCertNotAfterDate = Integer .valueOf(document.getElementsByTagName(PropertyName.PROPERTY_SIGNED_CERT_NOT_AFTER.getValue()) .item(0).getTextContent()); domain = document.getElementsByTagName(PropertyName.DOMAIN.getValue()).item(0).getTextContent(); } WindowsPluginProperties properties = new WindowsPluginProperties(); properties.setKeyStorePassword(password); properties.setPrivateKeyPassword(privateKeyPassword); properties.setCommonName(signedCertCommonName); properties.setNotBeforeDays(signedCertNotBeforeDate); properties.setNotAfterDays(signedCertNotAfterDate); properties.setAuthPolicy(authPolicy); properties.setDomain(domain); servletContext.setAttribute(PluginConstants.WINDOWS_PLUGIN_PROPERTIES, properties); File wapProvisioningFile = new File(getClass().getClassLoader() .getResource(PluginConstants.CertificateEnrolment.WAP_PROVISIONING_XML).getFile()); servletContext.setAttribute(PluginConstants.CONTEXT_WAP_PROVISIONING_FILE, wapProvisioningFile); }
From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java
/** * Initialise the ToasterServlet - build the required service and database connection pools. *//*from w w w . j ava 2 s . c o m*/ public void init(ServletConfig config) throws ServletException { /* Perform servlet initialisation... */ super.init(config); ServletContext context = getServletContext(); Properties servletProperties = null; try { servletProperties = getAjaxToasterProperties(); loggingType = servletProperties.getProperty(LOGGING_TYPE); Logger.setLoggerType(loggingType); log = Logger.getLogger(AjaxToasterServlet.class.getName()); if (loggingType.equals(Logger.LOG4J_LOGGING_STR)) { PropertyConfigurator.configureAndWatch(propertiesPath); } } catch (Exception ex) { log = Logger.getLogger(AjaxToasterServlet.class.getName()); log.error("Exception initialising", ex); } log.info("AjaxToaster version " + getVersion()); log.info("Using XMLToaster version " + com.inverse2.xmltoaster.Version.getVersion()); if (servletProperties == null) { println("**** ERROR: Could not cache the AjaxToaster properties file."); return; } // Read response format of output returned to client - XML or JSON. response_format_prop = servletProperties.getProperty(PROP_RESPONSE_FORMAT); if (response_format_prop != null && response_format_prop.equalsIgnoreCase("JSON")) { response_format_prop = "JSON"; } else { response_format_prop = "XML"; } log.info(" Response format >> [" + response_format_prop + "]"); sleepInterval = getSleepInterval(servletProperties); // Create a new service pool servicePool = new ServicePool(sleepInterval, this); context.setAttribute(ATTRIB_SERVICE_POOL, servicePool); try { println("**** INFO: CREATING NEW SERVICE POOL - sleepInterval = " + sleepInterval + ", scriptPath=" + scriptPath); servicePool.initialise(scriptPath); servicePool.start(); } catch (Exception ex) { println("**** ERROR: Exception creating AjaxToaster service pool: " + ex.toString()); } /* Initialise the service mapping object... */ try { serviceMapper = new ServiceURIMapper(scriptPath, URI_MAPPINGS_FILE); serviceMapper.start(); } catch (Exception ex) { log.error("Exception setting up the Service URI Mapper: " + ex.toString()); ex.printStackTrace(); } initDBPools(servletProperties, context); /* Start a thread that will watch for changes in the servlet's properties file */ try { monitorProperties = true; monitorPropertiesThread = new Thread(this); monitorPropertiesThread.start(); } catch (Exception ex) { log.warn("Could not start a thread to watch for changes in the properties file: " + ex.toString()); } }
From source file:com.aurel.track.ApplicationStarter.java
/** Initializes the application */ @Override/* w ww .jav a 2s .c o m*/ public void run() { setLoaderResourceBundleMessages(); ServletContext servletContext = getServletConfig().getServletContext(); appBean = initApplicationBeanStep1(servletContext); LOGGER.info("-------------------------------------------------------------"); LOGGER.info(ApplicationBean.getInstance().getAppTypeString() + ": System initializaton for version " + appBean.getVersion() + " build " + appBean.getBuild() + " started..."); LOGGER.info("TRACKPLUS_HOME set to " + HandleHome.getTrackplus_Home()); updateOrCreateDbSchema(servletContext); TSiteBean site = initDatabaseAndAdjustHome(appBean.getVersion(), servletContext); initExtraLoggers(servletContext); printSystemInfo(); Support.loadLastURIs(); try { setColumnSizes(); InitDatabase.upgradeDatabase(site, servletContext, appBean.getVersion(), appBean.getBuild()); } catch (Exception e) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); ApplicationBean.getInstance().setInstallProblem(createInstallProblemMessage(e)); LOGGER.error("Problem when printing system info or upgrading database."); emergencyExit(e); } // Initialize the length of short descriptions in the report page initDescriptionLength(); initEmailSubsystem(); initCookieTimeout(); initLDAP(); initWebService(); // Update the versions of the application and database scheme. updateVersions(servletContext); LuceneUtil.initLuceneParameters(); site = siteDAO.load1(); appBean = initLicSys(site); ClusterBL.processCluster(false); String myIp = ClusterBL.getIPAddress(); if (ApplicationBean.getInetAddress() != null) { TClusterNodeBean clusterNodeBean = ClusterBL.loadByIP(myIp); appBean.setClusterNodeBean(clusterNodeBean); } HandleHome.initGroovyPlugins(servletContext); Constants.setGroovyScriptEngine(); servletContext.setAttribute("SITECONFIG", site); servletContext.setAttribute(Constants.APPLICATION_BEAN, appBean); initJobs(servletContext); getDesignPaths(servletContext); servletContext.setAttribute("FirstTime", "FT"); initLucene(myIp); EventPublisher evp = EventPublisher.getInstance(); EventPublisher.init(); // only first time, don't repeat if (evp != null) { List<Integer> events = new ArrayList<Integer>(); events.add(Integer.valueOf(IEventSubscriber.EVENT_POST_SYSTEM_STARTED)); evp.notify(events, site); } // // Verify the reportTemplates // actualizePercentComplete(ApplicationStarter.REPORT_COPY, ApplicationStarter.REPORT_COPY_READY_TEXT); InitReportTemplateBL.verifyReportTemplates(); // remove stuck locks ItemLockBL.removeAllLocks(); Set<String> fieldTypeResourceBundleNames = FieldTypeDescriptorUtil.getCustomFieldTypeResourceBundles(); if (fieldTypeResourceBundleNames != null) { for (String resourceBundleName : fieldTypeResourceBundleNames) { // add the resource bundles specified in the fieldType // plugins // to the struts' default resource bundles. // needed for example to report the conversion errors // during configuring the custom fields // (by conversion error text there is not possible to // specify the bundle explicitly) LocalizedTextUtil.addDefaultResourceBundle(resourceBundleName); } } actualizePercentComplete(100 - getPercentComplete(), ApplicationStarter.READY_TEXT); String version = site.getTrackVersion(); LOGGER.info(appBean.getAppTypeString() + " system version " + version + " Build " + appBean.getBuild() + " started..."); // ------------------------------------------------------------ // Initialize general logging with settings from the database initGeneralLogging(servletContext); servletContext.setAttribute(READY, new Boolean(true)); serverIsReady = true; try { FileMonitor.monitor(); } catch (Exception e) { LOGGER.info(e.getMessage()); } // This is for unit test purposes File lock = new File(HandleHome.getTrackplus_Home() + "/lock"); if (lock.exists()) { lock.delete(); } try { DetectorFactory .loadProfile(HandleHome.getTrackplus_Home() + File.separator + "LanguageDetectionProfiles"); } catch (Exception e) { LOGGER.warn("Unable to load language profiles: " + e.getMessage()); } }
From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java
private void configure(ServletContext servletContext, Logger log) throws Exception { long start = System.currentTimeMillis(); ArtifactoryHome artifactoryHome = (ArtifactoryHome) servletContext .getAttribute(ArtifactoryHome.SERVLET_CTX_ATTR); VersionProviderImpl versionProvider = (VersionProviderImpl) servletContext .getAttribute(ArtifactoryHome.ARTIFACTORY_VERSION_PROVIDER_OBJ); ConverterManager converterManager = (ConverterManager) servletContext .getAttribute(ArtifactoryHome.ARTIFACTORY_CONVERTER_OBJ); if (artifactoryHome == null) { throw new IllegalStateException("Artifactory home not initialized."); }// ww w . j a v a 2 s .c o m CompoundVersionDetails runningVersionDetails = versionProvider.getRunning(); logAsciiArt(log, artifactoryHome, runningVersionDetails); ApplicationContext context; try { ArtifactoryHome.bind(artifactoryHome); //todo consider moving to org.artifactory.webapp.servlet.ArtifactoryHomeConfigListener.contextInitialized() if (artifactoryHome.isHaConfigured()) { log.debug("Not using Artifactory lock file on HA environment"); } else { artifactoryLockFile = new ArtifactoryLockFile( new File(artifactoryHome.getDataDir(), LOCK_FILENAME)); artifactoryLockFile.tryLock(); } Class<?> contextClass = ClassUtils.forName("org.artifactory.spring.ArtifactoryApplicationContext", ClassUtils.getDefaultClassLoader()); Constructor<?> constructor = contextClass.getConstructor(String.class, SpringConfigPaths.class, ArtifactoryHome.class, ConverterManager.class, VersionProviderImpl.class); //Construct the context name based on the context path //(will not work with multiple servlet containers on the same vm!) String contextUniqueName = HttpUtils.getContextId(servletContext); SpringConfigPaths springConfigPaths = SpringConfigResourceLoader.getConfigurationPaths(artifactoryHome); context = (ApplicationContext) constructor.newInstance(contextUniqueName, springConfigPaths, artifactoryHome, converterManager, versionProvider); } finally { ArtifactoryHome.unbind(); } log.info("\n" + "###########################################################\n" + "### Artifactory successfully started (" + String.format("%-17s", (DurationFormatUtils.formatPeriod(start, System.currentTimeMillis(), "s.S")) + " seconds)") + " ###\n" + "###########################################################\n"); //Register the context for easy retrieval for faster destroy servletContext.setAttribute(ArtifactoryContext.APPLICATION_CONTEXT_KEY, context); }
From source file:org.cipango.sipatra.DefaultContextLoader.java
public void contextInitialized(ServletContextEvent sce) { ServletContext servletContext = sce.getServletContext(); String appPath = servletContext.getRealPath("/WEB-INF/sipatra"); String scriptPath = PropertyUtils.getStringProperty(Properties.SIPATRA_PATH_PROPERTY, null, servletContext); if (scriptPath == null) { scriptPath = appPath + "/application.rb"; } else {//from w w w . ja v a 2 s .c o m File file = new File(scriptPath); if (!file.exists()) { _log.error(file.getAbsolutePath() + " does not exist!"); scriptPath = null; } if (file.isFile()) { if (!file.getName().endsWith(".rb")) _log.warn(file.getAbsolutePath() + " is not a ruby file!"); if (file.getParentFile() != null) appPath = file.getParentFile().getAbsolutePath(); else _log.error(file.getAbsolutePath() + " got no parent directory!"); } else if (file.isDirectory()) { appPath = new File(scriptPath).getAbsolutePath(); } } Config conf = new Config(); conf.maxActive = PropertyUtils.getIntegerProperty(Properties.SIPATRA_POOL_MAX_ACTIVE_PROPERTY, -1, servletContext); conf.maxIdle = PropertyUtils.getIntegerProperty(Properties.SIPATRA_POOL_MAX_IDLE_PROPERTY, -1, servletContext); conf.maxWait = PropertyUtils.getIntegerProperty(Properties.SIPATRA_POOL_MAX_WAIT_PROPERTY, -1, servletContext); conf.minIdle = PropertyUtils.getIntegerProperty(Properties.SIPATRA_POOL_MIN_IDLE_PROPERTY, -1, servletContext); conf.minEvictableIdleTimeMillis = PropertyUtils .getLongProperty(Properties.SIPATRA_POOL_MIN_EVICTABLE_PROPERTY, 1000L * 60L * 30L, servletContext); conf.lifo = PropertyUtils.getBooleanProperty(Properties.SIPATRA_POOL_LIFO, false, servletContext); conf.numTestsPerEvictionRun = PropertyUtils.getIntegerProperty(Properties.SIPATRA_POOL_TEST_EVICTION_RUN, 3, servletContext); conf.softMinEvictableIdleTimeMillis = PropertyUtils .getLongProperty(Properties.SIPATRA_POOL_SOFT_MIN_EVICTABLE, -1L, servletContext); conf.testOnBorrow = PropertyUtils.getBooleanProperty(Properties.SIPATRA_POOL_TEST_BORROW, false, servletContext); conf.testOnReturn = PropertyUtils.getBooleanProperty(Properties.SIPATRA_POOL_TEST_RETURN, false, servletContext); conf.testWhileIdle = PropertyUtils.getBooleanProperty(Properties.SIPATRA_POOL_TEST_IDLE, false, servletContext); conf.timeBetweenEvictionRunsMillis = PropertyUtils.getLongProperty(Properties.SIPATRA_POOL_TIME_EVICTION, -1L, servletContext); GenericObjectPool pool = new GenericObjectPool(new JRubyRuntimeFactory(appPath, scriptPath), conf); startPool(pool, PropertyUtils.getIntegerProperty(Properties.SIPATRA_POOL_INIT_POOL_SIZE, 1, servletContext)); servletContext.setAttribute(Attributes.POOL, pool); }