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.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 w w .j a va2s. c o 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); 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 w w . j a v a 2s . c o 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:com.dhcc.framework.web.context.DhccContextLoader.java
/** * Return the {@link ApplicationContextInitializer} implementation classes to use * if any have been specified by {@link #CONTEXT_INITIALIZER_CLASSES_PARAM}. * @param servletContext current servlet context * @see #CONTEXT_INITIALIZER_CLASSES_PARAM *///from www . j ava 2 s .c o m @SuppressWarnings("unchecked") protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> determineContextInitializerClasses( ServletContext servletContext) { String classNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM); List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes = new ArrayList<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>(); if (classNames != null) { for (String className : StringUtils.tokenizeToStringArray(classNames, ",")) { try { Class<?> clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader()); Assert.isAssignable(ApplicationContextInitializer.class, clazz, "class [" + className + "] must implement ApplicationContextInitializer"); classes.add((Class<ApplicationContextInitializer<ConfigurableApplicationContext>>) clazz); } catch (ClassNotFoundException ex) { throw new ApplicationContextException( "Failed to load context initializer class [" + className + "]", ex); } } } return classes; }
From source file:io.joynr.runtime.MessagingServletConfig.java
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); // properties from appProperties will extend and override the default // properties Properties properties = new LowerCaseProperties( PropertyLoader.loadProperties(DEFAULT_SERVLET_MESSAGING_PROPERTIES)); String appPropertiesFileName = servletContext.getInitParameter("properties"); if (appPropertiesFileName != null) { Properties appProperties = ServletPropertyLoader.loadProperties(appPropertiesFileName, servletContext); properties.putAll(appProperties); } else {// ww w.jav a 2 s. c o m logger.warn("to load properties, set the initParameter 'properties' "); } // add OS environment properties properties.putAll(System.getenv()); servletModuleName = properties.getProperty(INIT_PARAM_SERVLET_MODULE_CLASSNAME); servletModuleName = servletModuleName == null ? DEFAULT_SERVLET_MODULE_NAME : servletModuleName; // create a reflection set used to find // * all plugin application classes implementing the JoynApplication interface // * all servlets annotated as WebServlet // * the class implementing JoynrInjectorFactory (should be only one) Object[] appPackages = mergeAppPackages(properties); // Add Java system properties (set with -D) properties.putAll(System.getProperties()); // TODO if reflections is ever a performance problem, can statically scan and save the reflections data using // Maven, // then work on the previously scanned data // see: https://code.google.com/p/reflections/wiki/UseCases Reflections reflections = new Reflections("io.joynr.runtime", appPackages); final Set<Class<?>> classesAnnotatedWithWebServlet = reflections .getTypesAnnotatedWith(JoynrWebServlet.class); final Set<Class<?>> classesAnnotatedWithProvider = reflections .getTypesAnnotatedWith(javax.ws.rs.ext.Provider.class); // The jerseyServletModule injects the servicing classes using guice, // instead of letting jersey do it natively jerseyServletModule = new AbstractJoynrServletModule() { @SuppressWarnings("unchecked") @Override protected void configureJoynrServlets() { bind(GuiceContainer.class); bind(JacksonJsonProvider.class).asEagerSingleton(); bind(MessagingService.class); //get all classes annotated with @Provider and bind them for (Class<?> providerClass : classesAnnotatedWithProvider) { bind(providerClass).in(Scopes.SINGLETON); } for (Class<?> webServletClass : classesAnnotatedWithWebServlet) { if (!HttpServlet.class.isAssignableFrom(webServletClass)) { continue; } bind(webServletClass); JoynrWebServlet webServletAnnotation = webServletClass.getAnnotation(JoynrWebServlet.class); if (webServletAnnotation == null) { logger.error("webServletAnnotation was NULL."); continue; } serve(webServletAnnotation.value()).with((Class<? extends HttpServlet>) webServletClass); } } // this @SuppressWarnings is needed for the build on jenkins @SuppressWarnings("unused") @Provides public IServletMessageReceivers providesMessageReceivers() { return messageReceivers; } }; Class<?> servletModuleClass = null; Module servletModule = null; try { servletModuleClass = this.getClass().getClassLoader().loadClass(servletModuleName); servletModule = (Module) servletModuleClass.newInstance(); } catch (ClassNotFoundException e) { logger.debug("Servlet module class not found will use default configuration"); } catch (Exception e) { logger.error("", e); } if (servletModule == null) { servletModule = new EmptyModule(); } properties.put(MessagingPropertyKeys.PROPERTY_SERVLET_CONTEXT_ROOT, servletContext.getContextPath()); String hostPath = properties.getProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH); if (hostPath == null) { hostPath = properties.getProperty("hostpath"); } if (hostPath != null) { properties.setProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH, hostPath); } // find all plugin application classes implementing the JoynApplication interface Set<Class<? extends JoynrApplication>> joynrApplicationsClasses = reflections .getSubTypesOf(JoynrApplication.class); Set<Class<? extends AbstractJoynrInjectorFactory>> joynrInjectorFactoryClasses = reflections .getSubTypesOf(AbstractJoynrInjectorFactory.class); assert (joynrInjectorFactoryClasses.size() == 1); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { } }); AbstractJoynrInjectorFactory injectorFactory = injector .getInstance(joynrInjectorFactoryClasses.iterator().next()); appLauncher = injector.getInstance(JoynrApplicationLauncher.class); logger.info("starting joynr with properties: {}", properties); appLauncher.init(properties, joynrApplicationsClasses, injectorFactory, Modules.override(jerseyServletModule, new CCInProcessRuntimeModule()).with(servletModule, new ServletMessagingModule())); super.contextInitialized(servletContextEvent); }
From source file:com.dhcc.framework.web.context.DhccContextLoader.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// w ww . jav a 2s . c o m * @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, DhccContextLoader.class.getClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException( "Failed to load default context class [" + contextClassName + "]", ex); } } }
From source file:org.springframework.web.context.ContextLoader.java
/** * Return the {@link ApplicationContextInitializer} implementation classes to use * if any have been specified by {@link #CONTEXT_INITIALIZER_CLASSES_PARAM}. * @param servletContext current servlet context * @see #CONTEXT_INITIALIZER_CLASSES_PARAM *///from w w w .j a v a 2 s .com protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> determineContextInitializerClasses( ServletContext servletContext) { List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes = new ArrayList<>(); String globalClassNames = servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM); if (globalClassNames != null) { for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) { classes.add(loadInitializerClass(className)); } } String localClassNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM); if (localClassNames != null) { for (String className : StringUtils.tokenizeToStringArray(localClassNames, INIT_PARAM_DELIMITERS)) { classes.add(loadInitializerClass(className)); } } return classes; }
From source file:com.googlecode.psiprobe.Tomcat55ContainerAdaptor.java
public List getApplicationInitParams(Context context) { // We'll try to determine if a parameter value comes from a deployment descriptor or a context descriptor. // assumption: Context.findParameter() returns only values of parameters that are declared in a deployment descriptor. // If a parameter is declared in a context descriptor with override=false and redeclared in a deployment descriptor, // Context.findParameter() still returns its value, even though the value is taken from a context descriptor. // context.findApplicationParameters() returns all parameters that are declared in a context descriptor regardless // of whether they are overridden in a deployment descriptor or not or not. // creating a set of parameter names that are declared in a context descriptor // and can not be ovevridden in a deployment descriptor. Set nonOverridableParams = new HashSet(); ApplicationParameter[] appParams = context.findApplicationParameters(); for (int i = 0; i < appParams.length; i++) { if (appParams[i] != null && !appParams[i].getOverride()) { nonOverridableParams.add(appParams[i].getName()); }/*from w w w. jav a 2 s . co m*/ } List initParams = new ArrayList(); ServletContext servletCtx = context.getServletContext(); for (Enumeration e = servletCtx.getInitParameterNames(); e.hasMoreElements();) { String paramName = (String) e.nextElement(); ApplicationParam param = new ApplicationParam(); param.setName(paramName); param.setValue(servletCtx.getInitParameter(paramName)); // if the parameter is declared in a deployment descriptor // and it is not declared in a context descriptor with override=false, // the value comes from the deployment descriptor param.setFromDeplDescr( context.findParameter(paramName) != null && !nonOverridableParams.contains(paramName)); initParams.add(param); } return initParams; }
From source file:org.exoplatform.frameworks.jcr.command.web.GenericWebAppContext.java
public GenericWebAppContext(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, SessionProvider sessionProvider, ManageableRepository repository) { initialize(servletContext, request, response); this.sessionProvider = sessionProvider; this.repository = repository; // log.info("WEb context ---------------"); // initialize context with all props Enumeration en = servletContext.getInitParameterNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, servletContext.getInitParameter(name)); LOG.debug("ServletContext init param: " + name + "=" + servletContext.getInitParameter(name)); }// w w w.j a va 2s . c om en = servletContext.getAttributeNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, servletContext.getAttribute(name)); LOG.debug("ServletContext: " + name + "=" + servletContext.getAttribute(name)); } HttpSession session = request.getSession(false); if (session != null) { en = session.getAttributeNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, session.getAttribute(name)); LOG.debug("Session: " + name + "=" + session.getAttribute(name)); } } en = request.getAttributeNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, request.getAttribute(name)); } en = request.getParameterNames(); while (en.hasMoreElements()) { String name = (String) en.nextElement(); put(name, request.getParameter(name)); LOG.debug("Request: " + name + "=" + request.getParameter(name)); } }
From source file:org.red5.net.websocket.WebSocketPlugin.java
/** * Returns a new instance of WsServerContainer if one does not already exist. * //www.j a v a2s . c om * @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.apache.velocity.tools.view.servlet.VelocityViewServlet.java
/** * Looks up an init parameter with the specified key in either the * ServletConfig or, failing that, in the ServletContext. *//*from www. ja v a 2 s. co m*/ protected String findInitParameter(ServletConfig config, String key) { // check the servlet config String param = config.getInitParameter(key); if (param == null || param.length() == 0) { // check the servlet context ServletContext servletContext = config.getServletContext(); param = servletContext.getInitParameter(key); } return param; }