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:ORG.oclc.os.SRW.SRWServletInfo.java

public void init(final ServletConfig config) {
    try {//from   www.java 2s . c  o  m
        String propsfilePath = EscidocConfiguration.getInstance()
                .get(EscidocConfiguration.SEARCH_PROPERTIES_DIRECTORY, "search/config");
        if (!propsfilePath.equals("")) {
            String escidocHome = EscidocConfiguration.getInstance().getEscidocHome();
            if (!escidocHome.isEmpty()) {
                if (!escidocHome.endsWith("/")) {
                    escidocHome += "/";
                }
                escidocHome += "conf/";
                if (propsfilePath.startsWith("/")) {
                    propsfilePath = propsfilePath.substring(1);
                }
                propsfilePath = escidocHome + propsfilePath;
            }
            if (!propsfilePath.endsWith("/")) {
                propsfilePath += "/";
            }
        }
        propsfileName = propsfilePath + "SRWServer.props";
        log.info("Reading properties file: " + propsfileName);
        srwHome = config.getServletContext().getRealPath("/");
        if (srwHome.endsWith("/"))
            srwHome = srwHome.substring(0, srwHome.length() - 1);
        if (srwHome.endsWith("\\"))
            srwHome = srwHome.substring(0, srwHome.length() - 1);
        log.debug("srwHome=" + srwHome);
        int off = srwHome.lastIndexOf('/');
        if (off < 0)
            off = srwHome.lastIndexOf('\\');
        if (off > 0) {
            webappHome = srwHome.substring(0, off);
            log.debug("webappHome=" + webappHome);
            off = webappHome.lastIndexOf('/');
            if (off < 0)
                off = webappHome.lastIndexOf('\\');
            if (off > 0)
                tomcatHome = webappHome.substring(0, off);
            log.debug("tomcatHome=" + tomcatHome);
        }
        InputStream is;
        try {
            is = Utilities.openInputStream(propsfileName, srwHome, null);
            properties.load(is);
            properties.setProperty("propsfilePath", propsfilePath);
            is.close();
        } catch (java.io.FileNotFoundException e) {
            log.info("Unable to load properties file: " + propsfileName);
            log.info("Will using web.xml for configuration parameters");
            Enumeration enumer = config.getInitParameterNames();
            String propName;
            while (enumer.hasMoreElements()) {
                propName = (String) enumer.nextElement();
                properties.setProperty(propName, config.getInitParameter(propName));
            }
        }
        buildDbList(properties, dbVector, dbnames, config.getServletContext().getRealPath("/"));
        srwHome = properties.getProperty("SRW.Home");
        if (srwHome == null) {
            srwHome = config.getServletContext().getRealPath("/");
        }
        log.info("SRW.Home=" + srwHome);
        pathInfoIndex = Integer
                .parseInt(properties.getProperty("pathInfoIndex", Integer.toString(pathInfoIndex)));
        log.info("pathInfoIndex=" + pathInfoIndex);
        resultSetIdleTime = Integer
                .parseInt(properties.getProperty("resultSetIdleTime", Integer.toString(resultSetIdleTime)));
        log.info("resultSetIdleTime=" + resultSetIdleTime + " seconds");
        defaultDatabase = properties.getProperty("default.database");
        if (defaultDatabase == null)
            defaultDatabase = "default.database not specified in properties file";
        log.info("default.database=" + defaultDatabase);
        indexDotHtmlLocation = properties.getProperty("index.html");
        if (indexDotHtmlLocation == null)
            indexDotHtmlLocation = srwHome + "index.html";
        String s = properties.getProperty("makeIndex.html");
        if (s != null)
            if (s.equalsIgnoreCase("true"))
                makeIndexDotHtml = true;

        // any dbs to open automatically?
        s = properties.getProperty("SRW.OpenAllDatabasesOnStartup");
        if (s == null) { // maybe a short list to open?
            s = properties.getProperty("SRW.OpenDatabasesInListOnStartup");
            if (s != null) {
                log.info("Opening databases: " + s);
                createDBs(s);
            } else
                log.info("Not opening databases yet");
        } else if (s.equalsIgnoreCase("true") || s.equalsIgnoreCase("t") || s.equals("1")) {
            Enumeration enumer = properties.propertyNames();
            int offset;
            String dbname, list = new String(","), t;
            while (enumer.hasMoreElements()) {
                t = (String) enumer.nextElement();
                if (t.startsWith("db.")) {
                    offset = t.indexOf(".", 3);
                    dbname = t.substring(3, offset);
                    if (list.indexOf(", " + dbname + ",") == -1) { // not yet in list
                        list = list + " " + dbname + ",";
                    }
                }
            }
            log.info("Opening all databases :" + list);
            createDBs(list);
        }

        // load the sru-srw extension mapping table
        Enumeration enumer = properties.propertyNames();
        String extension, namespace, sruParm, t;
        while (enumer.hasMoreElements()) {
            t = (String) enumer.nextElement();
            if (t.startsWith("extension.") && !t.endsWith(".namespace")) {
                sruParm = t.substring(10);
                extension = properties.getProperty(t);
                extensions.put(sruParm, extension);
                log.debug("added extension=" + extension + ", with sru parm=" + sruParm);
                namespace = properties.getProperty("extension." + extension + ".namespace");
                namespaces.put(sruParm, namespace);
                log.debug("added namespace=" + namespace + ", with sru parm=" + sruParm);
            }
        }

        log.info("SRWServletInfo initialization complete");
    } catch (Exception e) {
        log.error(e, e);
    }
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * @see javax.servlet.GenericServlet#init(ServletConfig)
 *//*ww w.  jav a  2 s.co m*/
@Override
public void init(ServletConfig config) throws ServletException {
    servletContextRealPath = config.getServletContext().getRealPath("/");

    if (config.getInitParameter("memory.growth.threshold") != null) {
        MEMORY_GROWTH_THRESHOLD = new Long(config.getInitParameter("memory.growth.threshold")).longValue();
    }

    defaultXsltInfoAndException = config.getInitParameter("exception-and-info-screen-xslt");
    xsltLoginScreenDefault = config.getInitParameter("login-screen-xslt");
    displayMostRecentVersion = new Boolean(config.getInitParameter("workflow.not-live.most-recent-version"))
            .booleanValue();
    try {
        yanelInstance = Yanel.getInstance();
        yanelInstance.init(); // TODO: Tell Yanel about alternative directory to look for configuration files, e.g. (File) getServletContext().getAttribute("javax.servlet.context.tempdir")

        map = yanelInstance.getMapImpl("map");

        sitetree = yanelInstance.getSitetreeImpl("repo-navigation");

        sslPort = config.getInitParameter("ssl-port");
        toolbarMasterSwitch = config.getInitParameter("toolbar-master-switch");
        reservedPrefix = yanelInstance.getReservedPrefix();
        String expires = config.getInitParameter("static-content-cache-expires");
        if (expires != null) {
            this.cacheExpires = Integer.parseInt(expires);
        }

        yanelUI = new YanelHTMLUI(map, reservedPrefix);

        // TODO: Make this value configurable also per realm or per individual user!
        logAccessEnabled = new Boolean(config.getInitParameter("log-access")).booleanValue();

        String TAG_SEP_PARAM_NAME = "access-log-tag-separator";
        if (config.getInitParameter(TAG_SEP_PARAM_NAME) != null) {
            if (config.getInitParameter(TAG_SEP_PARAM_NAME).equals("SPACE")) { // Note that the leading and trailing space around the parameter value is trimmed, hence we denote the space sign by SPACE.
                ACCESS_LOG_TAG_SEPARATOR = " ";
            } else {
                ACCESS_LOG_TAG_SEPARATOR = config.getInitParameter(TAG_SEP_PARAM_NAME);
            }
        } else {
            ACCESS_LOG_TAG_SEPARATOR = ",";
            log.warn("No access log tag separator parameter '" + TAG_SEP_PARAM_NAME
                    + "' configured, hence use default: " + ACCESS_LOG_TAG_SEPARATOR);
        }

        // TODO: Make this value configurable also per realm or per individual user!
        if (config.getInitParameter("detect-mobile-per-request") != null) {
            detectMobilePerRequest = new Boolean(config.getInitParameter("detect-mobile-per-request"))
                    .booleanValue();
        }

        if (config.getInitParameter("mobile-devices") != null) {
            mobileDevices = org.springframework.util.StringUtils
                    .tokenizeToStringArray(config.getInitParameter("mobile-devices"), ",", true, true);
        } else {
            mobileDevices = new String[] { "iPhone", "Android" };
            log.error(
                    "No mobile devices configured! Please make sure to update your web.xml configuration file accordingly. Fallback to hard-coded list: "
                            + mobileDevices);
        }

        if (yanelInstance.isSchedulerEnabled()) {
            try {
                log.debug("Startup scheduler ...");
                scheduler = StdSchedulerFactory.getDefaultScheduler();

                Realm[] realms = yanelInstance.getRealmConfiguration().getRealms();
                for (int i = 0; i < realms.length; i++) {
                    if (realms[i] instanceof org.wyona.yanel.core.map.RealmWithConfigurationExceptionImpl) {
                        String eMessage = ((org.wyona.yanel.core.map.RealmWithConfigurationExceptionImpl) realms[i])
                                .getConfigurationException().getMessage();
                        log.error("Realm '" + realms[i].getID() + "' has thrown a configuration exception: "
                                + eMessage);
                    } else {
                        String schedulerJobsPath = "/scheduler-jobs.xml";
                        if (realms[i].getRepository().existsNode(schedulerJobsPath)) {
                            log.debug("Scheduler jobs config found for realm: "
                                    + realms[i].getRepository().getID());
                            try {
                                // Get and filter scheduler config
                                InputStream istream = realms[i].getRepository().getNode(schedulerJobsPath)
                                        .getInputStream();
                                log.debug("Filter scheduler configuration of realm '" + realms[i].getID()
                                        + "' by target environment '" + yanelInstance.getTargetEnvironment()
                                        + "'...");
                                istream = ConfigurationUtil.filterEnvironment(istream,
                                        yanelInstance.getTargetEnvironment());
                                Document filteredConfiguration = XMLHelper.readDocument(istream);

                                // INFO: Debug filtered scheduler configuration
                                if (log.isDebugEnabled()) {
                                    org.wyona.yarep.core.Node filteredConfigDebugNode = null;
                                    if (realms[i].getRepository().existsNode(schedulerJobsPath + ".DEBUG")) {
                                        filteredConfigDebugNode = realms[i].getRepository()
                                                .getNode(schedulerJobsPath + ".DEBUG");
                                    } else {
                                        filteredConfigDebugNode = org.wyona.yarep.util.YarepUtil.addNodes(
                                                realms[i].getRepository(), schedulerJobsPath + ".DEBUG",
                                                org.wyona.yarep.core.NodeType.RESOURCE);
                                    }
                                    XMLHelper.writeDocument(filteredConfiguration,
                                            filteredConfigDebugNode.getOutputStream());
                                }

                                // INFO: Run scheduler util
                                org.wyona.yanel.impl.scheduler.QuartzSchedulerUtil.schedule(scheduler,
                                        filteredConfiguration, realms[i]);
                            } catch (Exception e) {
                                log.error(e, e); // INFO: Log error, but otherwise ignore and keep going ...
                            }
                        }
                    }
                }

                /* TODO: Make global scheduler jobs configurable
                                String groupName = "yanel";
                                JobDetail jobDetail = new JobDetail("heartbeatJob", groupName, org.wyona.yanel.servlet.HeartbeatJob.class);
                                Date startDate = new Date();
                                Date endDate = null;
                                Trigger trigger = new SimpleTrigger("heartbeatTrigger", groupName, startDate, endDate, SimpleTrigger.REPEAT_INDEFINITELY, 60L * 1000L);
                                scheduler.scheduleJob(jobDetail, trigger);
                */

                scheduler.start();
            } catch (Exception e) {
                log.error(e, e); // INFO: Let's be fault tolerant in case the scheduler should not start
            }
        } else {
            log.info("The scheduler is currently disabled.");
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:com.softwarementors.extjs.djn.servlet.DirectJNgineServlet.java

protected GlobalConfiguration createGlobalConfiguration(ServletConfig configuration) {
    assert configuration != null;

    ServletUtils.checkRequiredParameters(configuration, GlobalParameters.PROVIDERS_URL);

    boolean isDebug = ServletUtils.getBooleanParameter(configuration, GlobalParameters.DEBUG,
            GlobalConfiguration.DEFAULT_DEBUG_VALUE);
    String providersUrl = ServletUtils.getRequiredParameter(configuration, GlobalParameters.PROVIDERS_URL);
    String gsonConfiguratorClassName = ServletUtils.getParameter(configuration,
            GlobalParameters.GSON_BUILDER_CONFIGURATOR_CLASS,
            GlobalConfiguration.DEFAULT_GSON_BUILDER_CONFIGURATOR_CLASS.getName());
    String dispatcherClassName = ServletUtils.getParameter(configuration, GlobalParameters.DISPATCHER_CLASS,
            /*GlobalConfiguration.DEFAULT_DISPATCHER_CLASS.getName()*/ getDefaultDispatcherClass().getName());
    String jsonRequestProcessorThreadClassName = ServletUtils.getParameter(configuration,
            GlobalParameters.JSON_REQUEST_PROCESSOR_THREAD_CLASS,
            /*GlobalConfiguration.DEFAULT_JSON_REQUEST_PROCESSOR_THREAD_CLASS.getName()*/ getDefaultJsonRequestProcessoThreadClass()
                    .getName());/*from   w  w  w .  j a v  a2s . c  o m*/

    // Global multithreaded-batched requests support parameters
    boolean isBatchRequestsMultithreadingEnabled = ServletUtils.getBooleanParameter(configuration,
            GlobalParameters.BATCH_REQUESTS_MULTITHREADING_ENABLED,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_MULTITHREADING_ENABLED_VALUE);
    boolean minifyEnabled = ServletUtils.getBooleanParameter(configuration, GlobalParameters.MINIFY,
            GlobalConfiguration.DEFAULT_MINIFY_VALUE);

    int batchRequestsMinThreadsPoolSize = ServletUtils.getIntParameterGreaterOrEqualToValue(configuration,
            GlobalParameters.BATCH_REQUESTS_MIN_THREADS_POOOL_SIZE,
            GlobalConfiguration.MIN_BATCH_REQUESTS_MIN_THREAD_POOL_SIZE,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_MIN_THREAD_POOL_SIZE);
    int batchRequestsMaxThreadsPoolSize = ServletUtils.getIntParameterGreaterOrEqualToValue(configuration,
            GlobalParameters.BATCH_REQUESTS_MAX_THREADS_POOOL_SIZE,
            GlobalConfiguration.MIN_BATCH_REQUESTS_MAX_THREAD_POOL_SIZE,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_MAX_THREAD_POOL_SIZE);
    int batchRequestsThreadKeepAliveSeconds = ServletUtils.getIntParameterGreaterOrEqualToValue(configuration,
            GlobalParameters.BATCH_REQUESTS_THREAD_KEEP_ALIVE_SECONDS,
            GlobalConfiguration.MIN_BATCH_REQUESTS_THREAD_KEEP_ALIVE_SECONDS,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_THREAD_KEEP_ALIVE_SECONDS);
    int batchRequestsMaxThreadsPerRequest = ServletUtils.getIntParameterGreaterOrEqualToValue(configuration,
            GlobalParameters.BATCH_REQUESTS_MAX_THREADS_PER_REQUEST,
            GlobalConfiguration.MIN_BATCH_REQUESTS_MAX_THREADS_PER_REQUEST,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_MAX_THREADS_PER_REQUEST);
    String contextPath = configuration.getInitParameter(GlobalParameters.CONTEXT_PATH);
    boolean createSourceFiles = ServletUtils.getBooleanParameter(configuration,
            GlobalParameters.CREATE_SOURCE_FILES, GlobalConfiguration.DEFAULT_CREATE_SOURCE_FILES);

    if (batchRequestsMinThreadsPoolSize > batchRequestsMaxThreadsPoolSize) {
        ServletConfigurationException ex = ServletConfigurationException
                .forMaxThreadPoolSizeMustBeEqualOrGreaterThanMinThreadPoolSize(batchRequestsMinThreadsPoolSize,
                        batchRequestsMaxThreadsPoolSize);
        logger.fatal(ex.getMessage(), ex);
        throw ex;
    }

    if (logger.isInfoEnabled()) {
        String contextPathInfo = contextPath;
        if (contextPathInfo == null) {
            contextPathInfo = "--not specified: calculated via Javascript--";
        }
        logger.info("Servlet GLOBAL configuration: " + GlobalParameters.DEBUG + "=" + isDebug + ", "
                + GlobalParameters.PROVIDERS_URL + "=" + providersUrl + ", " + GlobalParameters.MINIFY + "="
                + minifyEnabled + ", " + GlobalParameters.BATCH_REQUESTS_MULTITHREADING_ENABLED + "="
                + isBatchRequestsMultithreadingEnabled + ", "
                + GlobalParameters.BATCH_REQUESTS_MIN_THREADS_POOOL_SIZE + "=" + batchRequestsMinThreadsPoolSize
                + ", " + GlobalParameters.BATCH_REQUESTS_MAX_THREADS_POOOL_SIZE + "="
                + batchRequestsMaxThreadsPoolSize + ", "
                + GlobalParameters.BATCH_REQUESTS_MAX_THREADS_PER_REQUEST + "="
                + batchRequestsMaxThreadsPerRequest + ", "
                + GlobalParameters.BATCH_REQUESTS_THREAD_KEEP_ALIVE_SECONDS + "="
                + batchRequestsThreadKeepAliveSeconds + ", " + GlobalParameters.GSON_BUILDER_CONFIGURATOR_CLASS
                + "=" + gsonConfiguratorClassName + ", " + GlobalParameters.DISPATCHER_CLASS + "="
                + dispatcherClassName + ", " + GlobalParameters.JSON_REQUEST_PROCESSOR_THREAD_CLASS + "="
                + jsonRequestProcessorThreadClassName + ", " + GlobalParameters.CONTEXT_PATH + "="
                + contextPathInfo + ", " + GlobalParameters.CREATE_SOURCE_FILES + "=" + createSourceFiles);
    }

    Class<? extends GsonBuilderConfigurator> gsonConfiguratorClass = getGsonBuilderConfiguratorClass(
            gsonConfiguratorClassName);
    Class<? extends Dispatcher> dispatcherClass = getDispatcherClass(dispatcherClassName);
    Class<? extends JsonRequestProcessorThread> jsonRequestProcessorClass = getJsonRequestProcessorThreadClass(
            jsonRequestProcessorThreadClassName);

    GlobalConfiguration result = new GlobalConfiguration(contextPath, providersUrl, isDebug,
            gsonConfiguratorClass, jsonRequestProcessorClass, dispatcherClass, minifyEnabled,
            isBatchRequestsMultithreadingEnabled, batchRequestsMinThreadsPoolSize,
            batchRequestsMaxThreadsPoolSize, batchRequestsThreadKeepAliveSeconds,
            batchRequestsMaxThreadsPerRequest, createSourceFiles);
    return result;
}

From source file:com.extjs.djn.ioc.servlet.BaseDirectJNgineServlet.java

protected GlobalConfiguration createGlobalConfiguration(ServletConfig configuration) {
    assert configuration != null;

    ServletUtils.checkRequiredParameters(configuration, GlobalParameters.PROVIDERS_URL);

    boolean isDebug = ServletUtils.getBooleanParameter(configuration, GlobalParameters.DEBUG,
            GlobalConfiguration.DEFAULT_DEBUG_VALUE);
    String providersUrl = ServletUtils.getRequiredParameter(configuration, GlobalParameters.PROVIDERS_URL);
    String gsonConfiguratorClassName = ServletUtils.getParameter(configuration,
            GlobalParameters.GSON_BUILDER_CONFIGURATOR_CLASS,
            GlobalConfiguration.DEFAULT_GSON_BUILDER_CONFIGURATOR_CLASS.getName());
    String dispatcherClassName = ServletUtils.getParameter(configuration, GlobalParameters.DISPATCHER_CLASS,
            /*//from  www  . ja  v  a 2s  .  c o  m
            * GlobalConfiguration.
            * DEFAULT_DISPATCHER_CLASS
            * .
            * getName
            * (
            * )
            */getDefaultDispatcherClass().getName());
    String jsonRequestProcessorThreadClassName = ServletUtils.getParameter(configuration,
            GlobalParameters.JSON_REQUEST_PROCESSOR_THREAD_CLASS, /*
                                                                  * GlobalConfiguration.
                                                                  * DEFAULT_JSON_REQUEST_PROCESSOR_THREAD_CLASS
                                                                  * .
                                                                  * getName
                                                                  * (
                                                                  * )
                                                                  */
            getDefaultJsonRequestProcessoThreadClass().getName());

    // Global multithreaded-batched requests support parameters
    boolean isBatchRequestsMultithreadingEnabled = ServletUtils.getBooleanParameter(configuration,
            GlobalParameters.BATCH_REQUESTS_MULTITHREADING_ENABLED,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_MULTITHREADING_ENABLED_VALUE);
    boolean minifyEnabled = ServletUtils.getBooleanParameter(configuration, GlobalParameters.MINIFY,
            GlobalConfiguration.DEFAULT_MINIFY_VALUE);

    int batchRequestsMinThreadsPoolSize = ServletUtils.getIntParameterGreaterOrEqualToValue(configuration,
            GlobalParameters.BATCH_REQUESTS_MIN_THREADS_POOOL_SIZE,
            GlobalConfiguration.MIN_BATCH_REQUESTS_MIN_THREAD_POOL_SIZE,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_MIN_THREAD_POOL_SIZE);
    int batchRequestsMaxThreadsPoolSize = ServletUtils.getIntParameterGreaterOrEqualToValue(configuration,
            GlobalParameters.BATCH_REQUESTS_MAX_THREADS_POOOL_SIZE,
            GlobalConfiguration.MIN_BATCH_REQUESTS_MAX_THREAD_POOL_SIZE,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_MAX_THREAD_POOL_SIZE);
    int batchRequestsThreadKeepAliveSeconds = ServletUtils.getIntParameterGreaterOrEqualToValue(configuration,
            GlobalParameters.BATCH_REQUESTS_THREAD_KEEP_ALIVE_SECONDS,
            GlobalConfiguration.MIN_BATCH_REQUESTS_THREAD_KEEP_ALIVE_SECONDS,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_THREAD_KEEP_ALIVE_SECONDS);
    int batchRequestsMaxThreadsPerRequest = ServletUtils.getIntParameterGreaterOrEqualToValue(configuration,
            GlobalParameters.BATCH_REQUESTS_MAX_THREADS_PER_REQUEST,
            GlobalConfiguration.MIN_BATCH_REQUESTS_MAX_THREADS_PER_REQUEST,
            GlobalConfiguration.DEFAULT_BATCH_REQUESTS_MAX_THREADS_PER_REQUEST);
    String contextPath = configuration.getInitParameter(GlobalParameters.CONTEXT_PATH);

    if (batchRequestsMinThreadsPoolSize > batchRequestsMaxThreadsPoolSize) {
        ServletConfigurationException ex = ServletConfigurationException
                .forMaxThreadPoolSizeMustBeEqualOrGreaterThanMinThreadPoolSize(batchRequestsMinThreadsPoolSize,
                        batchRequestsMaxThreadsPoolSize);
        logger.fatal(ex.getMessage(), ex);
        throw ex;
    }

    if (logger.isInfoEnabled()) {
        String contextPathInfo = contextPath;
        if (contextPathInfo == null) {
            contextPathInfo = "--not specified: calculated via Javascript--";
        }
        logger.info("Servlet GLOBAL configuration: " + GlobalParameters.DEBUG + "=" + isDebug + ", "
                + GlobalParameters.PROVIDERS_URL + "=" + providersUrl + ", " + GlobalParameters.MINIFY + "="
                + minifyEnabled + ", " + GlobalParameters.BATCH_REQUESTS_MULTITHREADING_ENABLED + "="
                + isBatchRequestsMultithreadingEnabled + ", "
                + GlobalParameters.BATCH_REQUESTS_MIN_THREADS_POOOL_SIZE + "=" + batchRequestsMinThreadsPoolSize
                + ", " + GlobalParameters.BATCH_REQUESTS_MAX_THREADS_POOOL_SIZE + "="
                + batchRequestsMaxThreadsPoolSize + ", "
                + GlobalParameters.BATCH_REQUESTS_MAX_THREADS_PER_REQUEST + "="
                + batchRequestsMaxThreadsPerRequest + ", "
                + GlobalParameters.BATCH_REQUESTS_THREAD_KEEP_ALIVE_SECONDS + "="
                + batchRequestsThreadKeepAliveSeconds + ", " + GlobalParameters.GSON_BUILDER_CONFIGURATOR_CLASS
                + "=" + gsonConfiguratorClassName + ", " + GlobalParameters.DISPATCHER_CLASS + "="
                + dispatcherClassName + ", " + GlobalParameters.JSON_REQUEST_PROCESSOR_THREAD_CLASS + "="
                + jsonRequestProcessorThreadClassName + ", " + GlobalParameters.CONTEXT_PATH + "="
                + contextPathInfo);
    }

    Class<? extends GsonBuilderConfigurator> gsonConfiguratorClass = getGsonBuilderConfiguratorClass(
            gsonConfiguratorClassName);
    Class<? extends Dispatcher> dispatcherClass = getDispatcherClass(dispatcherClassName);
    Class<? extends JsonRequestProcessorThread> jsonRequestProcessorClass = getJsonRequestProcessorThreadClass(
            jsonRequestProcessorThreadClassName);

    GlobalConfiguration result = new GlobalConfiguration(contextPath, providersUrl, isDebug,
            gsonConfiguratorClass, jsonRequestProcessorClass, dispatcherClass, minifyEnabled,
            isBatchRequestsMultithreadingEnabled, batchRequestsMinThreadsPoolSize,
            batchRequestsMaxThreadsPoolSize, batchRequestsThreadKeepAliveSeconds,
            batchRequestsMaxThreadsPerRequest);
    return result;
}

From source file:com.portfolio.rest.RestServicePortfolio.java

public RestServicePortfolio(@Context ServletConfig sc, @Context ServletContext context) {
    try {/*  w  w  w  .  ja  v a2  s .co  m*/
        // Initialize data provider and cas
        try {
            casUrlValidation = context.getInitParameter("casUrlValidation");
        } catch (Exception ex) {
            casUrlValidation = null;
        }
        ;

        try {
            elggDefaultApiUrl = context.getInitParameter("elggDefaultApiUrl");
        } catch (Exception ex) {
            elggDefaultApiUrl = null;
        }
        ;

        try {
            elggDefaultSiteUrl = context.getInitParameter("elggDefaultSiteUrl");
        } catch (Exception ex) {
            elggDefaultSiteUrl = null;
        }
        ;

        try {
            elggApiKey = context.getInitParameter("elggApiKey");
        } catch (Exception ex) {
            elggApiKey = null;
        }
        ;

        try {
            elggDefaultUserPassword = context.getInitParameter("elggDefaultUserPassword");
        } catch (Exception ex) {
            elggDefaultUserPassword = null;
        }
        ;

        servContext = context;
        String dataProviderName = sc.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        // Try to initialize Datasource
        InitialContext cxt = new InitialContext();
        if (cxt == null) {
            throw new Exception("no context found!");
        }

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        logger.error("CAN'T INIT PROVIDER: " + e.toString());
        e.printStackTrace();
    }
}

From source file:org.apache.cocoon.servlet.CocoonServlet.java

/**
 * Initialize this <code>CocoonServlet</code> instance.  You will
 * notice that I have broken the init into sub methods to make it
 * easier to maintain (BL).  The context is passed to a couple of
 * the subroutines.  This is also because it is better to explicitly
 * pass variables than implicitely.  It is both more maintainable,
 * and more elegant./*from  w ww. ja v a2 s.co m*/
 *
 * @param conf The ServletConfig object from the servlet engine.
 *
 * @throws ServletException
 */
public void init(ServletConfig conf) throws ServletException {

    super.init(conf);

    // Check the init-classloader parameter only if it's not already true.
    // This is useful for subclasses of this servlet that override the value
    // initially set by this class (i.e. false).
    if (!this.initClassLoader) {
        this.initClassLoader = getInitParameterAsBoolean("init-classloader", false);
    }

    if (this.initClassLoader) {
        // Force context classloader so that JAXP can work correctly
        // (see javax.xml.parsers.FactoryFinder.findClassLoader())
        try {
            Thread.currentThread().setContextClassLoader(this.classLoader);
        } catch (Exception e) {
            // ignore this
        }
    }

    try {
        // FIXME (VG): We shouldn't have to specify these. Need to override
        // jaxp implementation of weblogic before initializing logger.
        // This piece of code is also required in the Cocoon class.
        String value = System.getProperty("javax.xml.parsers.SAXParserFactory");
        if (value != null && value.startsWith("weblogic")) {
            System.setProperty("javax.xml.parsers.SAXParserFactory",
                    "org.apache.xerces.jaxp.SAXParserFactoryImpl");
            System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                    "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
        }
    } catch (Exception e) {
        // Ignore security exception
        System.out.println("CocoonServlet: Could not check system properties, got: " + e);
    }

    this.servletContext = conf.getServletContext();
    this.appContext.put(Constants.CONTEXT_ENVIRONMENT_CONTEXT, new HttpContext(this.servletContext));
    this.servletContextPath = this.servletContext.getRealPath("/");

    // first init the work-directory for the logger.
    // this is required if we are running inside a war file!
    final String workDirParam = getInitParameter("work-directory");
    if (workDirParam != null) {
        if (this.servletContextPath == null) {
            // No context path : consider work-directory as absolute
            this.workDir = new File(workDirParam);
        } else {
            // Context path exists : is work-directory absolute ?
            File workDirParamFile = new File(workDirParam);
            if (workDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.workDir = workDirParamFile;
            } else {
                // No : consider it relative to context path
                this.workDir = new File(servletContextPath, workDirParam);
            }
        }
    } else {
        this.workDir = (File) this.servletContext.getAttribute("javax.servlet.context.tempdir");
        this.workDir = new File(workDir, "cocoon-files");
    }
    this.workDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_WORK_DIR, workDir);

    String path = this.servletContextPath;
    // these two variables are just for debugging. We can't log at this point
    // as the logger isn't initialized yet.
    String debugPathOne = null, debugPathTwo = null;
    if (path == null) {
        // Try to figure out the path of the root from that of WEB-INF
        try {
            path = this.servletContext.getResource("/WEB-INF").toString();
        } catch (MalformedURLException me) {
            throw new ServletException("Unable to get resource 'WEB-INF'.", me);
        }
        debugPathOne = path;
        path = path.substring(0, path.length() - "WEB-INF".length());
        debugPathTwo = path;
    }
    try {
        if (path.indexOf(':') > 1) {
            this.servletContextURL = path;
        } else {
            this.servletContextURL = new File(path).toURL().toExternalForm();
        }
    } catch (MalformedURLException me) {
        // VG: Novell has absolute file names starting with the
        // volume name which is easily more then one letter.
        // Examples: sys:/apache/cocoon or sys:\apache\cocoon
        try {
            this.servletContextURL = new File(path).toURL().toExternalForm();
        } catch (MalformedURLException ignored) {
            throw new ServletException("Unable to determine servlet context URL.", me);
        }
    }
    try {
        this.appContext.put("context-root", new URL(this.servletContextURL));
    } catch (MalformedURLException ignore) {
        // we simply ignore this
    }

    // Init logger
    initLogger();

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("getRealPath for /: " + this.servletContextPath);
        if (this.servletContextPath == null) {
            getLogger().debug("getResource for /WEB-INF: " + debugPathOne);
            getLogger().debug("Path for Root: " + debugPathTwo);
        }
    }

    this.forceLoadParameter = getInitParameter("load-class", null);
    this.forceSystemProperty = getInitParameter("force-property", null);

    // Output some debug info
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Servlet Context URL: " + this.servletContextURL);
        if (workDirParam != null) {
            getLogger().debug("Using work-directory " + this.workDir);
        } else {
            getLogger().debug("Using default work-directory " + this.workDir);
        }
    }

    final String uploadDirParam = conf.getInitParameter("upload-directory");
    if (uploadDirParam != null) {
        if (this.servletContextPath == null) {
            this.uploadDir = new File(uploadDirParam);
        } else {
            // Context path exists : is upload-directory absolute ?
            File uploadDirParamFile = new File(uploadDirParam);
            if (uploadDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.uploadDir = uploadDirParamFile;
            } else {
                // No : consider it relative to context path
                this.uploadDir = new File(servletContextPath, uploadDirParam);
            }
        }
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using upload-directory " + this.uploadDir);
        }
    } else {
        this.uploadDir = new File(workDir, "upload-dir" + File.separator);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using default upload-directory " + this.uploadDir);
        }
    }
    this.uploadDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_UPLOAD_DIR, this.uploadDir);

    this.enableUploads = getInitParameterAsBoolean("enable-uploads", ENABLE_UPLOADS);

    this.autoSaveUploads = getInitParameterAsBoolean("autosave-uploads", SAVE_UPLOADS_TO_DISK);

    String overwriteParam = getInitParameter("overwrite-uploads", "rename");
    // accepted values are deny|allow|rename - rename is default.
    if ("deny".equalsIgnoreCase(overwriteParam)) {
        this.allowOverwrite = false;
        this.silentlyRename = false;
    } else if ("allow".equalsIgnoreCase(overwriteParam)) {
        this.allowOverwrite = true;
        this.silentlyRename = false; // ignored in this case
    } else {
        // either rename is specified or unsupported value - default to rename.
        this.allowOverwrite = false;
        this.silentlyRename = true;
    }

    this.maxUploadSize = getInitParameterAsInteger("upload-max-size", MAX_UPLOAD_SIZE);

    String cacheDirParam = conf.getInitParameter("cache-directory");
    if (cacheDirParam != null) {
        if (this.servletContextPath == null) {
            this.cacheDir = new File(cacheDirParam);
        } else {
            // Context path exists : is cache-directory absolute ?
            File cacheDirParamFile = new File(cacheDirParam);
            if (cacheDirParamFile.isAbsolute()) {
                // Yes : keep it as is
                this.cacheDir = cacheDirParamFile;
            } else {
                // No : consider it relative to context path
                this.cacheDir = new File(servletContextPath, cacheDirParam);
            }
        }
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Using cache-directory " + this.cacheDir);
        }
    } else {
        this.cacheDir = IOUtils.createFile(workDir, "cache-dir" + File.separator);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("cache-directory was not set - defaulting to " + this.cacheDir);
        }
    }
    this.cacheDir.mkdirs();
    this.appContext.put(Constants.CONTEXT_CACHE_DIR, this.cacheDir);

    this.appContext.put(Constants.CONTEXT_CONFIG_URL, getConfigFile(conf.getInitParameter("configurations")));
    if (conf.getInitParameter("configurations") == null) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("configurations was not set - defaulting to... ?");
        }
    }

    // get allow reload parameter, default is true
    this.allowReload = getInitParameterAsBoolean("allow-reload", ALLOW_RELOAD);

    String value = conf.getInitParameter("show-time");
    this.showTime = BooleanUtils.toBoolean(value) || (this.hiddenShowTime = "hide".equals(value));
    if (value == null) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("show-time was not set - defaulting to false");
        }
    }

    this.showCocoonVersion = getInitParameterAsBoolean("show-cocoon-version", true);

    parentComponentManagerClass = getInitParameter("parent-component-manager", null);
    if (parentComponentManagerClass != null) {
        int dividerPos = parentComponentManagerClass.indexOf('/');
        if (dividerPos != -1) {
            parentComponentManagerInitParam = parentComponentManagerClass.substring(dividerPos + 1);
            parentComponentManagerClass = parentComponentManagerClass.substring(0, dividerPos);
        }
    }

    this.containerEncoding = getInitParameter("container-encoding", "ISO-8859-1");
    this.defaultFormEncoding = getInitParameter("form-encoding", "ISO-8859-1");
    this.appContext.put(Constants.CONTEXT_DEFAULT_ENCODING, this.defaultFormEncoding);

    this.manageExceptions = getInitParameterAsBoolean("manage-exceptions", true);

    this.enableInstrumentation = getInitParameterAsBoolean("enable-instrumentation", false);

    this.requestFactory = new RequestFactory(this.autoSaveUploads, this.uploadDir, this.allowOverwrite,
            this.silentlyRename, this.maxUploadSize, this.containerEncoding);
    // Add the servlet configuration
    this.appContext.put(CONTEXT_SERVLET_CONFIG, conf);
    this.createCocoon();
}