Example usage for javax.servlet ServletConfig getInitParameter

List of usage examples for javax.servlet ServletConfig getInitParameter

Introduction

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

Prototype

public String getInitParameter(String name);

Source Link

Document

Gets the value of the initialization parameter with the given name.

Usage

From source file:fr.norad.servlet.sample.html.template.IndexTemplateServlet.java

void loadProperties(ServletConfig config) {
    @SuppressWarnings("unchecked")
    Enumeration<String> initParameterNames = config.getInitParameterNames();
    while (initParameterNames.hasMoreElements()) {
        String initParamName = initParameterNames.nextElement();
        if (initParamName.endsWith(".property")) {
            String initParamValue = config.getInitParameter(initParamName);
            String value = loadValue(initParamValue);
            String name = initParamNameToName(initParamName);
            properties.put(name, value);
        }/*from   w  w  w.  j  av a  2 s  .c om*/
    }
}

From source file:it.marcoberri.mbfasturl.cron.QuartzInitServlet.java

/**
 * //from ww  w  .ja  v  a2s  .c  o  m
 * @param cfg
 * @throws javax.servlet.ServletException
 */
@Override
public void init(ServletConfig cfg) throws javax.servlet.ServletException {

    super.init(cfg);
    this.application = cfg.getServletContext();

    StdSchedulerFactory schedulerFactory = null;
    final String shutdownPref = cfg.getInitParameter("shutdown-on-unload");

    if (shutdownPref != null) {
        performShutdown = Boolean.valueOf(shutdownPref).booleanValue();
    }

    final Properties prop = new Properties();
    prop.setProperty("org.quartz.scheduler.instanceName", "OsQuarz_mbfasturl2");
    prop.setProperty("org.quartz.scheduler.instanceId", "" + System.nanoTime());
    prop.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
    prop.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
    prop.setProperty("org.quartz.threadPool.threadCount", "1");

    Commons.log.debug("Init Schduler");

    try {

        schedulerFactory = new StdSchedulerFactory(prop);
        scheduler = schedulerFactory.getScheduler();

        // StartUp
        Commons.log.debug("configure : StartUp");

        final Iterator<JSONObject> iterator = ConfigurationHelper.getCron().iterator();
        while (iterator.hasNext()) {
            final JSONObject c = iterator.next();
            final String name = Default.toString(c.get("name"));
            Commons.log.debug("name:" + name);

            final String clazz = Default.toString(c.get("class"));
            Commons.log.debug("clazz:" + clazz);

            final Boolean enable = Default.toBoolean(c.get("enable"));
            Commons.log.debug("enable:" + enable);

            final String cronTab = Default.toString(c.get("cron"));
            Commons.log.debug("cronTab:" + cronTab);

            if (!enable) {
                Commons.log.info(name + " enbale:" + enable);
                continue;
            }

            try {
                final Class classForCron = Class.forName(clazz);
                Commons.log.debug("start configure:" + name);
                final JobDetail job = JobBuilder.newJob(classForCron).withIdentity("job" + name, "group" + name)
                        .build();

                final Trigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity("trigger" + name, "group" + name)
                        .withSchedule(CronScheduleBuilder.cronSchedule(cronTab)).build();

                scheduler.scheduleJob(job, trigger);

            } catch (ClassNotFoundException ex) {

                Commons.log.fatal(ex);
            }

        }

        scheduler.start();
        application.setAttribute(QUARTZ_FACTORY_KEY, schedulerFactory);
        Commons.log.debug("cron started :" + QUARTZ_FACTORY_KEY);
    } catch (SchedulerException ex) {
        Commons.log.fatal("Fatal conf Job", ex);
    }

}

From source file:mondrian.xmla.impl.Olap4jXmlaServlet.java

@Override
protected XmlaHandler.ConnectionFactory createConnectionFactory(ServletConfig servletConfig)
        throws ServletException {
    final String olap4jDriverClassName = servletConfig.getInitParameter(OLAP_DRIVER_CLASS_NAME_PARAM);
    final String olap4jDriverConnectionString = servletConfig
            .getInitParameter(OLAP_DRIVER_CONNECTION_STRING_PARAM);
    final String olap4jUsePreConfiguredDiscoverDatasourcesRes = servletConfig
            .getInitParameter(OLAP_DRIVER_PRECONFIGURED_DISCOVER_DATASOURCES_RESPONSE);
    boolean hardcodedDiscoverDatasources = olap4jUsePreConfiguredDiscoverDatasourcesRes != null
            && Boolean.parseBoolean(olap4jUsePreConfiguredDiscoverDatasourcesRes);

    final String idleConnTimeoutStr = servletConfig
            .getInitParameter(OLAP_DRIVER_IDLE_CONNECTIONS_TIMEOUT_MINUTES);
    final int idleConnectionsCleanupTimeoutMs = idleConnTimeoutStr != null
            ? Integer.parseInt(idleConnTimeoutStr) * 60 * 1000
            : DEFAULT_IDLE_CONNECTIONS_TIMEOUT_MS;

    final String maxNumConnPerUserStr = servletConfig
            .getInitParameter(OLAP_DRIVER_MAX_NUM_CONNECTIONS_PER_USER);
    int maxNumConnectionsPerUser = maxNumConnPerUserStr != null ? Integer.parseInt(maxNumConnPerUserStr) : 1;
    try {/*from w w  w . j a v a 2 s .c  om*/
        Map<String, String> connectionProperties = getOlap4jConnectionProperties(servletConfig,
                OLAP_DRIVER_CONNECTION_PROPERTIES_PREFIX);
        final Map<String, Object> ddhcRes;
        if (hardcodedDiscoverDatasources) {
            ddhcRes = getDiscoverDatasourcesPreConfiguredResponse(servletConfig);
        } else {
            ddhcRes = null;
        }

        return new Olap4jPoolingConnectionFactory(olap4jDriverClassName, olap4jDriverConnectionString,
                connectionProperties, idleConnectionsCleanupTimeoutMs, maxNumConnectionsPerUser, ddhcRes);
    } catch (Exception ex) {
        String msg = "Exception [" + ex + "] while trying to create " + "olap4j connection to ["
                + olap4jDriverConnectionString + "] using driver " + "[" + olap4jDriverClassName + "]";
        LOGGER.error(msg, ex);
        throw new ServletException(msg, ex);
    }
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationResponseServlet.java

/**
 * {@inheritDoc}//from www .j a v  a  2  s  . c om
 */
@Override
public void init(ServletConfig config) throws ServletException {
    this.responseSessionAttribute = getRequiredInitParameter("ResponseSessionAttribute", config);

    this.redirectPage = getRequiredInitParameter("RedirectPage", config);
    this.errorPage = config.getInitParameter(ERROR_PAGE_INIT_PARAM);
    this.errorMessageSessionAttribute = config.getInitParameter(ERROR_MESSAGE_SESSION_ATTRIBUTE_INIT_PARAM);

}

From source file:net.handle.servlet.OpenHandleServlet.java

/**
 * <p>// ww w.ja v a  2s.c  o  m
 * Performs steps necessary to correctly configure and initialize this
 * servlet. At present, this consists of the following:
 * </p>
 * <ol>
 * <li>Attempting to load a custom config, if one is specified as an
 * init-param using the key 'config'.</li>
 * <li>Loading the default config if no custom config is available.</li>
 * <li>Loading up an instance of {@link Settings} from the config.</li>
 * <li>Initializing an instance of {@link OpenHandle} to act as a resolver.</li>
 * </ol>
 * <p>
 * A custom configuration detailing available templates, handle client
 * options, and request parameter names can be specified as an init-param:
 * </p>
 *
 * <pre>
 * &lt;init-param&gt;
 *     &lt;param-name&gt;config&lt;/param-name&gt;
 *     &lt;param-value&gt;/WEB-INF/OpenHandle.xml&lt;/param-value&gt;
 * &lt;/init-param&gt;
 * </pre>
 *
 * <p>
 * The path specified as a value must point to a resource obtainable via
 * {@link ServletContext#getResource(String)}.
 * </p>
 *
 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
 */
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // start with a null configuration
    Configuration configuration = null;

    // has a custom config been specified?
    String customConfig = config.getInitParameter("config");
    if (isNotBlank(customConfig)) {
        try {
            configuration = new XMLConfiguration(getServletContext().getResource(customConfig));
        } catch (Exception e) {
            LOG.error("Could not load custom configuration '" + customConfig
                    + "'. Proceeding to load default configuration.", e);
        }
    }

    // load the default config
    try {
        configuration = new XMLConfiguration(OpenHandleServlet.class.getResource("/OpenHandle.xml"));
    } catch (Exception e) {
        throw new ServletException("Could not load default configuration", e);
    }

    try {
        // load settings
        settings = new Settings(configuration);

        // initialize resolver
        resolver = new OpenHandle(settings.getPreferredProtocols(), settings.isTraceMessages());
    } catch (SettingsException e) {
        throw new ServletException(e);
    }

    try {
        Properties properties = new Properties();
        properties.load(OpenHandleServlet.class.getResourceAsStream("/velocity.properties"));
        velocity = new VelocityEngine();
        velocity.setApplicationAttribute(ServletContext.class.getName(), getServletContext());
        velocity.init(properties);
    } catch (Exception e) {
        throw new ServletException("Could not initialize velocity engine", e);
    }
}

From source file:org.owasp.csrfguard.util.CsrfGuardUtils.java

public static String getInitParameter(ServletConfig servletConfig, String name,
        String configFileDefaultParamValue, String defaultValue) {
    String value = servletConfig.getInitParameter(name);

    if (value == null || "".equals(value.trim())) {
        value = configFileDefaultParamValue;
    }//from ww  w  . j  a v  a 2  s .com

    if (value == null || "".equals(value.trim())) {
        value = defaultValue;
    }

    return value;
}

From source file:com.autentia.wuija.web.JasperReportsServlet.java

/**
 * Get initial parameter or default value if it is not present
 * //from ww w  .j  a  v  a2 s .  c  o  m
 * @param cfg servlet configuration
 * @param paramName parameter name
 * @param defaultValue parameter default value
 * @param normalizeDir whether or not to add a trailing / to directory values
 * @return value of parameter
 */
private String getInitParam(ServletConfig cfg, String paramName, String defaultValue, boolean normalizeDir) {
    String ret = cfg.getInitParameter(paramName);
    ret = (ret == null) ? defaultValue : ret;
    if (normalizeDir && ret.length() > 0 && !ret.endsWith("/")) {
        ret = ret + "/";
    }
    return ret;
}

From source file:net.ontopia.topicmaps.db2tm.SynchronizationServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    log.info("Initializing synchronization servlet.");

    try {/*from   w w w. j a  va  2  s  .  c om*/
        // no default starttime
        Date time = null;
        long delay = 180 * 1000;
        String timeval = config.getInitParameter("start-time");
        if (timeval != null) {
            Date d = df.parse(timeval);
            Calendar c0 = Calendar.getInstance();
            Calendar c = Calendar.getInstance();
            c.set(Calendar.HOUR_OF_DAY, 1);
            c.set(Calendar.MINUTE, 0);
            c.add(Calendar.MILLISECOND, (int) d.getTime());
            if (c.before(c0))
                c.add(Calendar.HOUR_OF_DAY, 24);
            time = c.getTime();
            log.info("Setting synchronization start time to {} ms.", time);
        } else {
            // default delay is 180 sec.
            delay = getLongProperty(config, "delay", delay);
            log.info("Setting synchronization delay to {} ms.", delay);
        }

        // default interval is 24 hours.
        long interval = getLongProperty(config, "interval", 1000 * 60 * 60 * 24);
        log.info("Setting synchronization interval to {} ms.", interval);

        // load relation mapping file
        String mapping = config.getInitParameter("mapping");
        if (mapping == null)
            throw new OntopiaRuntimeException("Servlet init-param 'mapping' must be specified.");

        // get relation names (comma separated)
        Collection<String> relnames = null;
        String relations = config.getInitParameter("relations");
        if (relations != null)
            relnames = Arrays.asList(StringUtils.split(relations, ","));

        // get hold of the topic map
        String tmid = config.getInitParameter("topicmap");
        if (tmid == null)
            throw new OntopiaRuntimeException("Servlet init-param 'topicmap' must be specified.");
        TopicMapRepositoryIF rep = NavigatorUtils.getTopicMapRepository(config.getServletContext());
        TopicMapReferenceIF ref = rep.getReferenceByKey(tmid);

        // make sure delay is at least 10 seconds to make sure that it doesn't
        // start too early
        if (time == null)
            task = new SynchronizationTask(config.getServletName(), (delay < 10000 ? 10000 : delay), interval);
        else
            task = new SynchronizationTask(config.getServletName(), time, interval);

        task.setRelationMappingFile(mapping);
        task.setRelationNames(relnames);
        task.setTopicMapReference(ref);
        task.setBaseLocator(null);

    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.github.peholmst.springsecuritydemo.servlet.SpringApplicationServlet.java

@SuppressWarnings("unchecked")
@Override// ww w  . ja v  a  2s. c  o m
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    /*
     * Look up the name of the Vaadin application bean. The bean should be
     * either a prototype or have session scope.
     */
    applicationBean = servletConfig.getInitParameter("applicationBean");
    if (applicationBean == null) {
        if (logger.isErrorEnabled()) {
            logger.error("ApplicationBean not specified in servlet parameters");
        }
        throw new ServletException("ApplicationBean not specified in servlet parameters");
    }

    if (logger.isInfoEnabled()) {
        logger.info("Using applicationBean '" + applicationBean + "'");
    }

    /*
     * Fetch the Spring web application context
     */
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());

    if (applicationContext.isSingleton(applicationBean)) {
        if (logger.isErrorEnabled()) {
            logger.error("ApplicationBean must not be a singleton");
        }
        throw new ServletException("ApplicationBean must not be a singleton");
    }
    if (!applicationContext.isPrototype(applicationBean) && logger.isWarnEnabled()) {
        logger.warn("ApplicationBean is not a prototype");
    }

    /*
     * Get the application class from the application context
     */
    applicationClass = (Class<? extends Application>) applicationContext.getType(applicationBean);
    if (logger.isDebugEnabled()) {
        logger.debug("Vaadin application class is [" + applicationClass + "]");
    }
    /*
     * Initialize the locale resolver
     */
    initLocaleResolver(applicationContext);
}

From source file:org.apache.ojb.broker.locking.LockManagerServlet.java

public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    // if lock manager was instantiated not yet
    if (lockmanager == null) {
        lastError = null;/*from   ww w.j a v  a2s .  c o  m*/
        numRequests = 0;
        String strLockManager = servletConfig.getInitParameter(STR_LOCK_MANAGER);
        try {
            lockmanager = (LockManager) (strLockManager != null ? ClassHelper.newInstance(strLockManager)
                    : ClassHelper.newInstance(LockManagerInMemoryImpl.class));
        } catch (Exception e) {
            lastError = new LockRuntimeException(
                    "Can't instance lock manager, init parameter 'lockManager': " + strLockManager);
            e.printStackTrace();
        }
        String strTimeout = servletConfig.getInitParameter(STR_LOCK_TIMEOUT);
        if (NumberUtils.isNumber(strTimeout)) {
            try {
                Long lockTimeout = NumberUtils.createLong(strTimeout);
                lockmanager.setLockTimeout(lockTimeout.longValue());
            } catch (Exception e) {
                if (lastError == null) {
                    lastError = new LockRuntimeException(
                            "Can't convert 'lockTimeout' init parameter: " + strTimeout);
                }
                e.printStackTrace();
            }
        }
        String strBlock = servletConfig.getInitParameter(STR_BLOCK_TIMEOUT);
        if (NumberUtils.isNumber(strBlock)) {
            try {
                Long blockTimeout = NumberUtils.createLong(strBlock);
                lockmanager.setLockTimeout(blockTimeout.longValue());
            } catch (Exception e) {
                if (lastError == null) {
                    lastError = new LockRuntimeException(
                            "Can't convert 'blockTimeout' init parameter: " + strBlock);
                }
                e.printStackTrace();
            }
        }
    }
}