List of usage examples for javax.servlet ServletContext getInitParameter
public String getInitParameter(String name);
String
containing the value of the named context-wide initialization parameter, or null
if the parameter does not exist. From source file:org.springframework.web.context.ContextLoader.java
/** * Return the WebApplicationContext implementation class to use, either the * default XmlWebApplicationContext or a custom context class if specified. * @param servletContext current servlet context * @return the WebApplicationContext implementation class to use * @see #CONTEXT_CLASS_PARAM/*from w w w . java2 s . c om*/ * @see org.springframework.web.context.support.XmlWebApplicationContext */ protected Class<?> determineContextClass(ServletContext servletContext) { String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM); if (contextClassName != null) { try { return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException( "Failed to load custom context class [" + contextClassName + "]", ex); } } else { contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName()); try { return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException( "Failed to load default context class [" + contextClassName + "]", ex); } } }
From source file:org.apache.cocoon.servletservice.ServletServiceContext.java
public String getInitParameter(String name) { if (this.properties == null) { return null; }//from www. j a v a 2 s . c o m String value = (String) this.properties.get(name); // Ask the super servlet for the property if (value == null) { ServletContext superContext = this.getNamedContext(SUPER); if (superContext != null) { value = superContext.getInitParameter(name); } } // Ask the parent context if (value == null) { value = super.getInitParameter(name); } return value; }
From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java
private String getHome(ServletContext ctx) { String home = ctx.getInitParameter(Constants.INIT_OIOSAML_HOME); if (home == null) { home = System.getProperty(SAMLUtil.OIOSAML_HOME); }//w w w . j av a2s.c o m if (home == null) { String name = ctx.getInitParameter(Constants.INIT_OIOSAML_NAME); if (name != null) { home = System.getProperty("user.home") + "/.oiosaml-" + name; } } if (home == null) { home = System.getProperty("user.home") + "/.oiosaml"; File h = new File(home); if (h.exists() && !h.isDirectory()) { throw new IllegalStateException(home + " is not a directory"); } else if (!h.exists()) { log.info("Creating empty config dir in " + home); if (!h.mkdir()) { throw new IllegalStateException(h + " could not be created"); } } } return home; }
From source file:org.apache.axis.transport.http.AxisServletBase.java
/** * Retrieve option, in order of precedence: * (Managed) System property (see discovery.ManagedProperty), * servlet init param, context init param. * Use of system properties is discouraged in production environments, * as it overrides everything else.// www . j a v a 2 s .c o m */ protected String getOption(ServletContext context, String param, String dephault) { String value = AxisProperties.getProperty(param); if (value == null) value = getInitParameter(param); if (value == null) value = context.getInitParameter(param); try { AxisServer engine = getEngine(this); if (value == null && engine != null) value = (String) engine.getOption(param); } catch (AxisFault axisFault) { } return (value != null) ? value : dephault; }
From source file:com.alfaariss.oa.OAContextListener.java
/** * Starts the engine before all servlets are initialized. * // w w w . j av a 2 s. c o m * Searches for the properties needed for the configuration in: * <code>[Servlet context dir]/WEB-INF/[PROPERTIES_FILENAME]</code> * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent oServletContextEvent) { Properties pConfig = new Properties(); try { _logger.info("Starting Asimba"); Package pCurrent = OAContextListener.class.getPackage(); String sSpecVersion = pCurrent.getSpecificationVersion(); if (sSpecVersion != null) _logger.info("Specification-Version: " + sSpecVersion); String sImplVersion = pCurrent.getImplementationVersion(); if (sImplVersion != null) _logger.info("Implementation-Version: " + sImplVersion); ServletContext oServletContext = oServletContextEvent.getServletContext(); Enumeration enumContextAttribs = oServletContext.getInitParameterNames(); while (enumContextAttribs.hasMoreElements()) { String sName = (String) enumContextAttribs.nextElement(); pConfig.put(sName, oServletContext.getInitParameter(sName)); } if (pConfig.size() > 0) { _logger.info("Using configuration items found in servlet context: " + pConfig); } // Add MountingPoint to PathTranslator PathTranslator.getInstance().addKey(MP_WEBAPP_ROOT, oServletContext.getRealPath("")); // Try to see whether there is a system property with the location of the properties file: String sPropertiesFilename = System.getProperty(PROPERTIES_FILENAME_PROPERTY); if (null != sPropertiesFilename && !"".equals(sPropertiesFilename)) { File fConfig = new File(sPropertiesFilename); if (fConfig.exists()) { _logger.info("Reading Asimba properties from " + fConfig.getAbsolutePath()); pConfig.putAll(getProperties(fConfig)); } } String sWebInf = oServletContext.getRealPath("WEB-INF"); if (sWebInf != null) { _logger.info("Cannot find path in ServletContext for WEB-INF"); StringBuffer sbConfigFile = new StringBuffer(sWebInf); if (!sbConfigFile.toString().endsWith(File.separator)) sbConfigFile.append(File.separator); sbConfigFile.append(PROPERTIES_FILENAME); File fConfig = new File(sbConfigFile.toString()); if (fConfig.exists()) { _logger.info("Updating configuration items with the items in file: " + fConfig.toString()); pConfig.putAll(getProperties(fConfig)); } else { _logger.info("No optional configuration properties (" + PROPERTIES_FILENAME + ") file found at: " + fConfig.toString()); } } //Search for PROPERTIES_FILENAME file in servlet context classloader classpath //it looks first at this location: ./<context>/web-inf/classes/[PROPERTIES_FILENAME] //if previous location didn't contain PROPERTIES_FILENAME then checking: //./tomcat/common/classes/PROPERTIES_FILENAME URL urlProperties = oServletContext.getClass().getClassLoader().getResource(PROPERTIES_FILENAME); if (urlProperties != null) { String sProperties = urlProperties.getFile(); _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in classpath: " + sProperties); File fProperties = new File(sProperties); if (fProperties != null && fProperties.exists()) { _logger.info("Updating configuration items with the items in file: " + fProperties.getAbsolutePath()); pConfig.putAll(getProperties(fProperties)); } else _logger.info("Could not resolve: " + fProperties.getAbsolutePath()); } else _logger.info("No optional '" + PROPERTIES_FILENAME + "' configuration file found in servlet context classpath"); if (!pConfig.containsKey("configuration.handler.filename")) { StringBuffer sbOAConfigFile = new StringBuffer(sWebInf); if (!sbOAConfigFile.toString().endsWith(File.separator)) sbOAConfigFile.append(File.separator); sbOAConfigFile.append("conf"); sbOAConfigFile.append(File.separator); sbOAConfigFile.append("asimba.xml"); File fOAConfig = new File(sbOAConfigFile.toString()); if (fOAConfig.exists()) { pConfig.put("configuration.handler.filename", sbOAConfigFile.toString()); _logger.info( "Setting 'configuration.handler.filename' configuration property with configuration file found at: " + fOAConfig.toString()); } } _oEngineLauncher.start(pConfig); _logger.info("Started Engine with OAContextListener"); } catch (Exception e) { _logger.error("Can't start Engine with OAContextListener", e); _logger.debug("try stopping the server"); _oEngineLauncher.stop(); } }
From source file:com.haulmont.cuba.web.App.java
/** * Called when <em>the first</em> UI of the session is initialized. *///w ww. j a v a 2s.c o m protected void init(Locale requestLocale) { VaadinSession vSession = VaadinSession.getCurrent(); vSession.setAttribute(App.class, this); vSession.setLocale(messageTools.getDefaultLocale()); // set root error handler for all session vSession.setErrorHandler(event -> { try { getExceptionHandlers().handle(event); getAppLog().log(event); } catch (Throwable e) { //noinspection ThrowableResultOfMethodCallIgnored log.error("Error handling exception\nOriginal exception:\n{}\nException in handlers:\n{}", ExceptionUtils.getStackTrace(event.getThrowable()), ExceptionUtils.getStackTrace(e)); } }); appLog = new AppLog(); connection = createConnection(); exceptionHandlers = new ExceptionHandlers(this); cookies = new AppCookies(); themeConstants = loadTheme(); VaadinServlet vaadinServlet = VaadinServlet.getCurrent(); ServletContext sc = vaadinServlet.getServletContext(); String resourcesTimestamp = sc.getInitParameter("webResourcesTs"); if (StringUtils.isNotEmpty(resourcesTimestamp)) { this.webResourceTimestamp = resourcesTimestamp; } log.debug("Initializing application"); // get default locale from config Locale targetLocale = resolveLocale(requestLocale); setLocale(targetLocale); }
From source file:com.liferay.portal.servlet.PortletContextListener.java
public void contextInitialized(ServletContextEvent sce) { try {// w w w.j a v a2 s.c o m // Servlet context ServletContext ctx = sce.getServletContext(); _servletContextName = StringUtil.replace(ctx.getServletContextName(), StringPool.SPACE, StringPool.UNDERLINE); // Company ids _companyIds = StringUtil.split(ctx.getInitParameter("company_id")); // Class loader ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // Initialize portlets String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")), Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")) }; _portlets = PortletManagerUtil.initWAR(_servletContextName, xmls); // Portlet context wrapper Iterator itr1 = _portlets.iterator(); while (itr1.hasNext()) { Portlet portlet = (Portlet) itr1.next(); javax.portlet.Portlet portletInstance = (javax.portlet.Portlet) contextClassLoader .loadClass(portlet.getPortletClass()).newInstance(); Indexer indexerInstance = null; if (Validator.isNotNull(portlet.getIndexerClass())) { indexerInstance = (Indexer) contextClassLoader.loadClass(portlet.getIndexerClass()) .newInstance(); } Scheduler schedulerInstance = null; if (Validator.isNotNull(portlet.getSchedulerClass())) { schedulerInstance = (Scheduler) contextClassLoader.loadClass(portlet.getSchedulerClass()) .newInstance(); } PreferencesValidator prefsValidator = null; if (Validator.isNotNull(portlet.getPreferencesValidator())) { prefsValidator = (PreferencesValidator) contextClassLoader .loadClass(portlet.getPreferencesValidator()).newInstance(); try { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) { prefsValidator.validate( PortletPreferencesSerializer.fromDefaultXML(portlet.getDefaultPreferences())); } } catch (Exception e1) { _log.warn("Portlet with the name " + portlet.getPortletId() + " does not have valid default preferences"); } } Map resourceBundles = null; if (Validator.isNotNull(portlet.getResourceBundle())) { resourceBundles = CollectionFactory.getHashMap(); Iterator itr2 = portlet.getSupportedLocales().iterator(); while (itr2.hasNext()) { String supportedLocale = (String) itr2.next(); Locale locale = new Locale(supportedLocale); try { ResourceBundle resourceBundle = ResourceBundle.getBundle(portlet.getResourceBundle(), locale, contextClassLoader); resourceBundles.put(locale.getLanguage(), resourceBundle); } catch (MissingResourceException mre) { _log.warn(mre.getMessage()); } } } Map customUserAttributes = CollectionFactory.getHashMap(); Iterator itr2 = portlet.getCustomUserAttributes().entrySet().iterator(); while (itr2.hasNext()) { Map.Entry entry = (Map.Entry) itr2.next(); String attrName = (String) entry.getKey(); String attrCustomClass = (String) entry.getValue(); customUserAttributes.put(attrCustomClass, contextClassLoader.loadClass(attrCustomClass).newInstance()); } PortletContextWrapper pcw = new PortletContextWrapper(portlet.getPortletId(), ctx, portletInstance, indexerInstance, schedulerInstance, prefsValidator, resourceBundles, customUserAttributes); PortletContextPool.put(portlet.getPortletId(), pcw); } // Portlet class loader String servletPath = ctx.getRealPath("/"); if (!servletPath.endsWith("/") && !servletPath.endsWith("\\")) { servletPath += "/"; } File servletClasses = new File(servletPath + "WEB-INF/classes"); File servletLib = new File(servletPath + "WEB-INF/lib"); List urls = new ArrayList(); if (servletClasses.exists()) { urls.add(new URL("file:" + servletClasses + "/")); } if (servletLib.exists()) { String[] jars = FileUtil.listFiles(servletLib); for (int i = 0; i < jars.length; i++) { urls.add(new URL("file:" + servletLib + "/" + jars[i])); } } URLClassLoader portletClassLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0]), contextClassLoader); ctx.setAttribute(WebKeys.PORTLET_CLASS_LOADER, portletClassLoader); // Portlet display String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml")); Map newCategories = PortletManagerUtil.getWARDisplay(_servletContextName, xml); for (int i = 0; i < _companyIds.length; i++) { String companyId = _companyIds[i]; Map oldCategories = (Map) WebAppPool.get(companyId, WebKeys.PORTLET_DISPLAY); Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories); WebAppPool.put(companyId, WebKeys.PORTLET_DISPLAY, mergedCategories); } // Reinitialize portal properties PropsUtil.init(); } catch (Exception e2) { Logger.error(this, e2.getMessage(), e2); } }
From source file:thinwire.render.web.WebServlet.java
private Set<String> getStartArguments(HttpServletRequest request) { Set<String> args = new TreeSet<String>(); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String[]> e : ((Map<String, String[]>) request.getParameterMap()).entrySet()) { String key = e.getKey();/* w ww .ja v a 2 s . c o m*/ String[] values = e.getValue(); if (values.length > 1) { for (int i = 0; i < values.length; i++) { sb.append(key).append(i).append('=').append(values[i]); } } else { sb.append(key).append('=').append(values[0]); } args.add(sb.toString()); sb.setLength(0); } String extraArguments = getInitParameter(InitParam.EXTRA_ARGUMENTS.mixedCaseName()); if (extraArguments == null) extraArguments = ""; extraArguments = "," + extraArguments + ","; if (extraArguments.indexOf(",contextParam,") >= 0) { ServletContext sc = getServletContext(); for (Enumeration<String> ipn = sc.getInitParameterNames(); ipn.hasMoreElements();) { String name = ipn.nextElement(); sb.append("CONTEXT_PARAM_").append(name).append('=').append(sc.getInitParameter(name)); args.add(sb.toString()); sb.setLength(0); } } if (extraArguments.indexOf(",initParam,") >= 0) { InitParam[] initParams = InitParam.values(); ipn_loop: for (Enumeration<String> ipn = getInitParameterNames(); ipn.hasMoreElements();) { String name = ipn.nextElement(); for (InitParam ip : initParams) { if (ip.mixedCaseName().equals(name)) continue ipn_loop; } sb.append("INIT_PARAM_").append(name).append('=').append(getInitParameter(name)); args.add(sb.toString()); sb.setLength(0); } } if (extraArguments.indexOf(",header,") >= 0) { for (Enumeration<String> hn = request.getHeaderNames(); hn.hasMoreElements();) { String name = hn.nextElement(); sb.append("HEADER_").append(name.toUpperCase()).append('=').append(request.getHeader(name)); args.add(sb.toString()); sb.setLength(0); } } if (extraArguments.indexOf(",clientInfo,") >= 0) { sb.append("CLIENT_INFO_USER").append('=').append(request.getRemoteUser()); args.add(sb.toString()); sb.setLength(0); sb.append("CLIENT_INFO_HOST").append('=').append(request.getRemoteHost()); args.add(sb.toString()); sb.setLength(0); sb.append("CLIENT_INFO_ADDRESS").append('=').append(request.getRemoteAddr()); args.add(sb.toString()); sb.setLength(0); } return args; }
From source file:org.squale.jraf.initializer.struts.StrutsInitializer.java
public void init(ActionServlet in_actionServlet, ModuleConfig in_moduleConfig) throws ServletException { // initializer IInitializable lc_initialize = null; // map des parametres Map lc_paramMap = null;/*from www . j av a 2 s . c o m*/ // context ServletContext lc_context = in_actionServlet.getServletContext(); ServletConfig lc_config = in_actionServlet.getServletConfig(); // log log.info("Debut de l'initialisation de l'application Jraf..."); // repertoire racine String lc_rootPath = lc_context.getRealPath(""); // Initialisation lc_context.log("INIT Ok - Recupration du Bean initializer ... "); ApplicationContextFactoryInitializer .init(lc_context.getInitParameter(IBootstrapConstants.SPRING_CONTEXT_CONFIG)); // Rcupration du bean initialize. initializer = (Initializer) ApplicationContextFactoryInitializer.getApplicationContext() .getBean("initialize"); lc_context.log("Provider config file = " + initializer.getConfigFile()); // classe d'initialisation String lc_initClassName = initializer.getClass().getName(); // fichier de configuration d'un provider String lc_providerConfigFile = initializer.getConfigFile(); // bind jndi String lc_isJndi = Boolean.toString(initializer.isJndi()); try { // test des parametres recuperees if (lc_rootPath == null || lc_rootPath.equals("") || lc_providerConfigFile == null || lc_providerConfigFile.equals("")) { // affiche une erreur de configuration String lc_error = "Pb de configuration : le chemin du contexte racine est vide ou le fichier de configuration des plugins n'est pas specifie."; log.fatal(lc_error); throw new JrafConfigException(lc_error); } else { // les parametres ont bien ete recuperes // creation de l'initializer lc_initialize = InitializableHelper.instanciateInitializable(lc_initClassName); // recuperation/creation des parametres lc_paramMap = new HashMap(); lc_paramMap.put(IBootstrapConstants.ROOT_PATH_KEY, lc_rootPath); lc_paramMap.put(IBootstrapConstants.PROVIDER_CONFIG_KEY, lc_providerConfigFile); // si le bind jndi est positionne if (lc_isJndi != null) { lc_paramMap.put(IBootstrapConstants.JNDI_BIND, lc_isJndi); } // execution de la methode d'initialisation IBootstrapProvider lc_bootstrapProvider = (IBootstrapProvider) lc_initialize .initialize(lc_paramMap); // log de succes log.info("L'application s'est initialisee avec succes"); log.info("Les providers suivants ont ete initialises:" + lc_bootstrapProvider.getProviders()); } } catch (JrafConfigException e) { // log log.fatal("Probleme lors de l'intialisation de l'application : ", e); throw new ServletException("Probleme lors de l'intialisation de l'application : ", e); } catch (RuntimeException e) { // log log.fatal("Probleme lors de l'intialisation de l'application : ", e); throw new ServletException("Probleme lors de l'intialisation de l'application : ", e); } }
From source file:com.icesoft.net.messaging.jms.JMSAdapter.java
public JMSAdapter(final ServletContext servletContext) throws IllegalArgumentException { super(servletContext); String _messagingProperties = servletContext.getInitParameter(MESSAGING_PROPERTIES); if (LOG.isDebugEnabled()) { LOG.debug("Messaging Properties (web.xml): " + _messagingProperties); }/*from w w w .j a v a2s . c om*/ if (_messagingProperties != null) { try { this.jmsProviderConfigurations = new JMSProviderConfiguration[] { new JMSProviderConfigurationProperties( getClass().getResourceAsStream(_messagingProperties)) }; } catch (IOException exception) { if (LOG.isErrorEnabled()) { LOG.error("An error occurred " + "while reading properties: " + _messagingProperties, exception); } } } if (this.jmsProviderConfigurations == null) { this.jmsProviderConfigurations = new JMSProviderConfiguration[] { new JMSProviderConfigurationProperties() }; this.jmsProviderConfigurations[0].setTopicConnectionFactoryName("ConnectionFactory"); } ThreadFactory _threadFactory = new ThreadFactory(); _threadFactory.setPrefix("MessageReceiver Thread"); executorService = Executors.newCachedThreadPool(_threadFactory); }