Example usage for javax.servlet ServletContext getInitParameter

List of usage examples for javax.servlet ServletContext getInitParameter

Introduction

In this page you can find the example usage for javax.servlet ServletContext getInitParameter.

Prototype

public String getInitParameter(String name);

Source Link

Document

Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.

Usage

From source file:net.sf.sail.webapp.spring.impl.CustomContextLoader.java

/**
 * The behaviour of this method is the same as the superclass except for
 * setting of the config locations./*from w w w. j ava  2  s  .c  o  m*/
 * 
 * @throws ClassNotFoundException
 * 
 * @see org.springframework.web.context.ContextLoader#createWebApplicationContext(javax.servlet.ServletContext,
 *      org.springframework.context.ApplicationContext)
 */
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext,
        ApplicationContext parent) throws BeansException {

    Class<?> contextClass = determineContextClass(servletContext);
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
        throw new ApplicationContextException("Custom context class [" + contextClass.getName()
                + "] is not of type ConfigurableWebApplicationContext");
    }

    ConfigurableWebApplicationContext webApplicationContext = (ConfigurableWebApplicationContext) BeanUtils
            .instantiateClass(contextClass);
    webApplicationContext.setParent(parent);
    webApplicationContext.setServletContext(servletContext);

    String configClass = servletContext.getInitParameter(CONFIG_CLASS_PARAM);
    if (configClass != null) {
        try {
            SpringConfiguration springConfig = (SpringConfiguration) BeanUtils
                    .instantiateClass(Class.forName(configClass));
            webApplicationContext.setConfigLocations(springConfig.getRootApplicationContextConfigLocations());
        } catch (ClassNotFoundException e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(CONFIG_CLASS_PARAM + " <" + configClass + "> not found.", e);
            }
            throw new InvalidParameterException("ClassNotFoundException: " + configClass);
        }
    } else {
        throw new InvalidParameterException("No value defined for the required: " + CONFIG_CLASS_PARAM);
    }

    webApplicationContext.refresh();
    return webApplicationContext;
}

From source file:org.opencms.main.CmsServletContainerSettings.java

/**
 * Creates a new object.<p>/*from w w  w .j  av a  2 s .c  o  m*/
 * 
 * @param context used to find out specifics of the servlet container
 */
public CmsServletContainerSettings(ServletContext context) {

    // CmsSystemInfo<init> has to call this with null (for setup)
    if (context != null) {
        // check for OpenCms home (base) directory path
        String webInfRfsPath = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_HOME);
        if (CmsStringUtil.isEmpty(webInfRfsPath)) {
            webInfRfsPath = CmsFileUtil.searchWebInfFolder(context.getRealPath("/"));
            if (CmsStringUtil.isEmpty(webInfRfsPath)) {
                throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_FOLDER_0));
            }
        }

        // set the default web application name
        // read the the default name from the servlet context parameters
        String defaultWebApplication = context.getInitParameter("DefaultWebApplication");

        // read the the OpenCms servlet mapping from the servlet context parameters
        String servletMapping = context.getInitParameter(OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_SERVLET);
        if (servletMapping == null) {
            throw new CmsInitException(Messages.get().container(Messages.ERR_CRITICAL_INIT_SERVLET_0));
        }

        // read the servlet container name
        String servletContainerName = context.getServerInfo();

        // web application context: 
        // read it from the servlet context parameters
        //      this is needed in case an application server specific deployment descriptor is used to changed the webapp context
        String webApplicationContext = context
                .getInitParameter(OpenCmsServlet.SERVLET_PARAM_WEB_APPLICATION_CONTEXT);
        if (CmsStringUtil.isEmptyOrWhitespaceOnly(webApplicationContext)) {
            try {
                URL contextRelativeUrl = context.getResource("/");
                webApplicationContext = contextRelativeUrl.getPath();
                String[] pathTokens = CmsStringUtil.splitAsArray(webApplicationContext, '/');
                if (pathTokens.length == 1) {
                    /*
                     * There may be a "" context configured (e.g. in GlassFish).
                     */
                    webApplicationContext = "";
                } else {

                    webApplicationContext = pathTokens[pathTokens.length - 1];
                }
            } catch (MalformedURLException e) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_INIT_CONTEXTNAME_0), e);
            }

        }
        // init values: 
        init(webInfRfsPath, defaultWebApplication, servletMapping, servletContainerName, webApplicationContext);
        // finally care for the speciality of different servlet containers: 
        initContainerSpecifics(context);
    }
}

From source file:xbdd.webapp.resource.feature.PrintPDF.java

@GET
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/")
public Response viewPDF(@BeanParam final Coordinates coord, @Context final HttpServletRequest request,
        @Context final ServletContext context, @QueryParam("view") final String view)
        throws URISyntaxException {

    final String urlcontext = request.getScheme() + "://" + request.getServerName() + ":"
            + request.getServerPort() + request.getContextPath();
    final String previousPage = request.getHeader("Referer");

    final String productString = "/" + coord.getProduct() + "/" + coord.getVersionString() + "/"
            + coord.getBuild();//from w w w .  java  2s .c  om
    final String urlstring = urlcontext + "/print/" + productString;

    // Getting the location of PHANTOMJS_HOME environment variable
    final String phantomjsloc = Objects.toString(context.getInitParameter(XBDD_PHANTOMJS_HOME_INIT_PARAMETER),
            System.getProperty("PHANTOMJS_HOME"));
    if (phantomjsloc == null) {
        final URI location = new URI(previousPage + "&phantom=no");
        return Response.temporaryRedirect(location).build();
    } else {
        final String username = Objects.toString(
                context.getInitParameter(XBDD_PHANTOMJS_USERNAME_INIT_PARAMETER),
                System.getProperty("PHANTOMJS_USER"));
        final String password = Objects.toString(
                context.getInitParameter(XBDD_PHANTOMJS_PASSWORD_INIT_PARAMETER),
                System.getProperty("PHANTOMJS_PASSWORD"));
        final StreamingOutput stream = createPDFStream(urlstring, phantomjsloc,
                context.getRealPath("/WEB-INF/rasterize.js"), username, password);

        String viewType = "inline";
        // View in browser or download as attachment
        if (view != null) {
            viewType = view;
        }

        final ResponseBuilder response = Response.ok(stream);
        response.type("application/pdf");
        response.status(200);
        response.header("Content-Disposition", viewType + "; filename=\"" + coord.getProduct() + " Version="
                + coord.getVersionString() + ", Build=" + coord.getBuild() + ".pdf\"");
        return response.build();
    }
}

From source file:WebAppProperties.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    ServletContext context = getServletContext();
    String displayName = context.getServletContextName();
    if (displayName == null) {
        displayName = "(no display-name element defined)";
    }/*  w  ww  .  j a  v a 2s  .  co m*/

    out.println("<html>");
    out.println("<body>");
    out.println("<br>Name: " + displayName);
    out.println("<br>Context: " + req.getContextPath());

    out.println("<h2><center>");
    out.println("Initialization Parameters</center></h2>");
    out.println("<br>");

    out.println("<center><table>");

    Enumeration e = context.getInitParameterNames();

    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println("<tr>");
        out.println("<td>" + name + "</td>");
        out.println("<td>" + context.getInitParameter(name) + "</td>");
        out.println("</tr>");
    }
    out.println("</table></center>");

    out.println("</body>");
    out.println("</html>");
    out.flush();
}

From source file:org.sindice.analytics.servlet.ServletConfigurationContextListener.java

private XMLConfiguration createXMLConfiguration(final ServletContext context) {
    final XMLConfiguration config = new XMLConfiguration();
    ConfigurationInterpolator interpolator = config.getInterpolator();
    final StrLookup defaultLookup = interpolator.getDefaultLookup();
    interpolator.setDefaultLookup(new StrLookup() {
        @Override//w w  w.j av  a 2s  .c  o  m
        public String lookup(String key) {
            if (context.getAttribute(key) != null) {
                return context.getAttribute(key).toString();
            }
            if (context.getInitParameter(key) != null) {
                return context.getInitParameter(key);
            }
            return defaultLookup.lookup(key);
        }
    });
    return config;
}

From source file:edu.isi.wings.portal.classes.Config.java

private PropertyListConfiguration getPortalConfiguration(HttpServletRequest request) {
    ServletContext app = request.getSession().getServletContext();
    this.configFile = app.getInitParameter("config.file");
    if (this.configFile == null) {
        String home = System.getProperty("user.home");
        if (home != null && !home.equals(""))
            this.configFile = home + File.separator + ".wings" + File.separator + "portal.properties";
        else/*from   www. j a v a 2  s. co  m*/
            this.configFile = "/etc/wings/portal.properties";
    }
    // Create configFile if it doesn't exist (portal.properties)
    File cfile = new File(this.configFile);
    if (!cfile.exists()) {
        if (!cfile.getParentFile().mkdirs()) {
            System.err.println("Cannot create config file directory : " + cfile.getParent());
            return null;
        }
        createDefaultPortalConfig(request);
    }

    // Load properties from configFile
    PropertyListConfiguration props = new PropertyListConfiguration();
    try {
        props.load(this.configFile);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return props;
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 *//*from w w w.  ja va2 s .c om*/
public void contextInitialized(final ServletContextEvent sContextEvent) {
    final String methodName = SecurityServiceListener.CNAME
            + "#contextInitialized(final ServletContextEvent sContextEvent)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletContextEvent: {}", sContextEvent);
    }

    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ServletContext sContext = sContextEvent.getServletContext();
    final ClassLoader classLoader = SecurityServiceListener.class.getClassLoader();

    if (DEBUG) {
        DEBUGGER.debug("ServletContext: {}", sContext);
        DEBUGGER.debug("ClassLoader: {}", classLoader);
    }

    try {
        if (sContext != null) {
            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSLOGGING_FILE)) {
                System.err.println("Logging configuration not found. No logging enabled !");
            } else {
                DOMConfigurator.configure(Loader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSLOGGING_FILE)));
            }

            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSCONFIG_FILE)) {
                xmlURL = classLoader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSCONFIG_FILE));

            } else {
                ERROR_RECORDER.error("System configuration not found. Shutting down !");

                throw new SecurityServiceException(
                        "System configuration file location not provided by application. Cannot continue.");
            }

            if (DEBUG) {
                DEBUGGER.debug("xmlURL: {}", xmlURL);
            }

            if (xmlURL != null) {
                context = JAXBContext.newInstance(SecurityConfigurationData.class);
                marshaller = context.createUnmarshaller();
                configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

                SecurityServiceListener.svcBean.setConfigData(configData);

                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(SecurityServiceConstants.DS_CONTEXT);

                DAOInitializer.configureAndCreateAuthConnection(
                        new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                        false, SecurityServiceListener.svcBean);

                Map<String, DataSource> dsMap = new HashMap<String, DataSource>();

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    dsMap.put(mgr.getDsName(), (DataSource) envContext.lookup(mgr.getDataSource()));
                }

                SecurityServiceListener.svcBean.setDataSources(dsMap);
            } else {
                throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
            }
        } else {
            throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
        }
    } catch (NamingException nx) {
        ERROR_RECORDER.error(nx.getMessage(), nx);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
    } catch (JAXBException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);
    }
}

From source file:edu.isi.wings.portal.classes.config.Config.java

public PropertyListConfiguration getPortalConfiguration(HttpServletRequest request) {
    ServletContext app = request.getSession().getServletContext();
    this.configFile = app.getInitParameter("config.file");
    if (this.configFile == null) {
        String home = System.getProperty("user.home");
        if (home != null && !home.equals(""))
            this.configFile = home + File.separator + ".wings" + File.separator + "portal.properties";
        else//  w w w .  ja v a 2s .  c  o  m
            this.configFile = "/etc/wings/portal.properties";
    }
    // Create configFile if it doesn't exist (portal.properties)
    File cfile = new File(this.configFile);
    if (!cfile.exists()) {
        if (!cfile.getParentFile().mkdirs()) {
            System.err.println("Cannot create config file directory : " + cfile.getParent());
            return null;
        }
        if (request != null)
            createDefaultPortalConfig(request);
    }

    // Load properties from configFile
    PropertyListConfiguration props = new PropertyListConfiguration();
    try {
        props.load(this.configFile);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return props;
}

From source file:org.glite.slcs.acl.impl.XMLFileAccessControlList.java

public void init(FilterConfig filterConfig) throws SLCSException {

    // initialize the AttributeDefintions from the servlet context
    ServletContext context = filterConfig.getServletContext();
    AttributeDefinitionsFactory.initialize(context);

    String filename = filterConfig.getInitParameter(ACLFILE_CONFIG_PARAM);
    LOG.info(ACLFILE_CONFIG_PARAM + "=" + filename);
    if (filename == null) {
        LOG.info("Parameter '" + ACLFILE_CONFIG_PARAM + "' is not defined, trying parameter '"
                + ACLFILE_CONTEXT_PARAM + "'");
        String contextKey = filterConfig.getInitParameter(ACLFILE_CONTEXT_PARAM);
        LOG.info(ACLFILE_CONTEXT_PARAM + "=" + contextKey);
        if (contextKey != null) {
            filename = context.getInitParameter(contextKey);
            if (filename == null) {
                throw new SLCSConfigurationException(
                        "Filter parameter ContextParamACLFile references a undefined Context parameter.");
            }/*from  w w  w  .j a v  a 2 s. c  o m*/
            LOG.debug("ACL filename=" + filename);
        } else {
            throw new SLCSConfigurationException("Filter parameter ACLFile or ContextParamACLFile not defined");
        }
    }

    // load the XML file
    aclXMLConfiguration_ = createACLXMLConfiguration(filename);

    // create the access control rules list
    accessControlRules_ = createACLAccessControlRules(aclXMLConfiguration_);

    // deals with the FileConfigurationMonitor
    String monitoringInterval = filterConfig.getInitParameter("ACLFileMonitoringInterval");
    if (monitoringInterval != null) {
        LOG.info("ACLFileMonitoringInterval=" + monitoringInterval);
        File file = aclXMLConfiguration_.getFile();
        aclConfigurationMonitor_ = FileConfigurationMonitor.createFileConfigurationMonitor(file,
                monitoringInterval, this);
        // and start
        aclConfigurationMonitor_.start();
    }
}

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java

@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {

    Resource resource = null;/*from   w  w w.j a  v a2s  .  co  m*/
    ServletContext servletContext = applicationContext.getServletContext();
    WebApplicationContextUtils.initServletPropertySources(
            applicationContext.getEnvironment().getPropertySources(), servletContext,
            applicationContext.getServletConfig());

    ServletConfig servletConfig = applicationContext.getServletConfig();
    String locations = servletConfig == null ? null
            : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
    resource = getResource(servletContext, applicationContext, locations);

    if (resource == null) {
        servletContext.log("No YAML environment properties from servlet.  Defaulting to servlet context.");
        locations = servletContext.getInitParameter(PROFILE_CONFIG_FILE_LOCATIONS);
        resource = getResource(servletContext, applicationContext, locations);
    }

    try {
        servletContext.log("Loading YAML environment properties from location: " + resource);
        YamlMapFactoryBean factory = new YamlMapFactoryBean();
        factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);

        List<Resource> resources = new ArrayList<Resource>();

        String defaultLocation = servletConfig == null ? null
                : servletConfig.getInitParameter(PROFILE_CONFIG_FILE_DEFAULT);
        if (defaultLocation != null) {
            Resource defaultResource = new ClassPathResource(defaultLocation);
            if (defaultResource.exists()) {
                resources.add(defaultResource);
            }
        }

        resources.add(resource);
        factory.setResources(resources.toArray(new Resource[resources.size()]));

        Map<String, Object> map = factory.getObject();
        String yamlStr = (new Yaml()).dump(map);
        map.put(rawYamlKey, yamlStr);
        NestedMapPropertySource properties = new NestedMapPropertySource("servletConfigYaml", map);
        applicationContext.getEnvironment().getPropertySources().addLast(properties);
        applySpringProfiles(applicationContext.getEnvironment(), servletContext);
        applyLog4jConfiguration(applicationContext.getEnvironment(), servletContext);

    } catch (Exception e) {
        servletContext.log("Error loading YAML environment properties from location: " + resource, e);
    }

}