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:com.sun.faban.harness.webclient.XFormServlet.java

/**
 * Initializes the servlet.//  ww w. j  av  a 2 s  .  com
 *
 * @throws javax.servlet.ServletException
 */
public void init() throws ServletException {

    ctx = getServletContext();
    ctxRoot = ctx.getRealPath("");
    if (ctxRoot == null)
        ctxRoot = ctx.getRealPath(".");

    ServletConfig cfg = getServletConfig();

    // Location of the config file.
    String path = cfg.getInitParameter("configFile");
    if (path != null)
        configFile = ctx.getRealPath(path);

    // Directory to store uploaded files, default to java.io.tmpDir
    uploadDir = cfg.getInitParameter("uploadDir");
    if (uploadDir == null)
        uploadDir = System.getProperty("java.io.tmpdir");

    // Make sure nobody uploads to WEB-INF - security breach!
    if (uploadDir != null && uploadDir.equalsIgnoreCase("WEB-INF")) {
        throw new ServletException("Cannot write directory " + uploadDir);
    }
    // Directory containing xslt stylesheets
    path = cfg.getInitParameter("xsltDir");
    if (path != null)
        xsltDir = ctx.getRealPath(path);

    errPage = cfg.getInitParameter("errorPage");
}

From source file:org.xmlactions.web.conceal.HttpPager.java

/**
 * @see Servlet#init(ServletConfig)//from ww w  . ja va  2  s  .c o m
 */
public void init(ServletConfig config) throws ServletException {

    String value;

    value = config.getServletContext().getRealPath("");
    if (StringUtils.isNotEmpty(value)) {
        realPath = value;
    }

    value = config.getInitParameter("pager.namespace");
    if (StringUtils.isNotEmpty(value)) {
        nameSpace = value;
    }

    value = config.getInitParameter("pager.wrapperPage");
    if (StringUtils.isNotEmpty(value)) {
        wrapperPage = value;
    }

    value = config.getInitParameter("pager.pre.page");
    if (StringUtils.isNotEmpty(value)) {
        prePage = value;
    }

    value = config.getInitParameter("pager.post.page");
    if (StringUtils.isNotEmpty(value)) {
        postPage = value;
    }

    // applicationContext =
    // WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
}

From source file:org.ireland.jnetty.jsp.JspServletComposite.java

@Override
public void init(ServletConfig config) throws ServletException {

    super.init(config);
    this.config = config;
    this.context = config.getServletContext();

    //JSPServletContext
    Thread.currentThread().setContextClassLoader(context.getClassLoader());

    // Initialize the JSP Runtime Context
    // Check for a custom Options implementation
    String engineOptionsName = config.getInitParameter("engineOptionsClass"); //
    if (engineOptionsName != null) {
        // Instantiate the indicated Options implementation
        try {/*from   w w  w.  java 2  s  .c  o  m*/
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> engineOptionsClass = loader.loadClass(engineOptionsName);
            Class<?>[] ctorSig = { ServletConfig.class, ServletContext.class };
            Constructor<?> ctor = engineOptionsClass.getConstructor(ctorSig);
            Object[] args = { config, context };
            options = (Options) ctor.newInstance(args);
        } catch (Throwable e) {
            e = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(e);
            // Need to localize this.
            log.warn("Failed to load engineOptionsClass", e);
            // Use the default Options implementation
            options = new EmbeddedServletOptions(config, context);
        }
    } else {
        // Use the default Options implementation
        options = new EmbeddedServletOptions(config, context);
    }

    rctxt = new JspRuntimeContext(context, options);

    if (debug) {
        log.debug(Localizer.getMessage("jsp.message.scratch.dir.is", options.getScratchDir().toString()));
        log.debug(Localizer.getMessage("jsp.message.dont.modify.servlets"));
    }
}

From source file:org.wso2.carbon.identity.application.authenticator.iwa.ntlm.servlet.IWAServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    Map<String, String> implParameters = new HashMap<String, String>();
    String authProvider = null;/*from  ww  w.  j  a v  a 2 s.co m*/
    String[] providerNames = null;
    if (config != null) {
        Enumeration parameterNames = config.getInitParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = (String) parameterNames.nextElement();
            String parameterValue = config

                    .getInitParameter(parameterName);
            if (parameterName.equals(IWAConstants.PRINCIPAL_FORMAT)) {
                IWAServiceDataHolder.getInstance().setPrincipalFormat(PrincipalFormat.valueOf(parameterValue));
            } else if (parameterName.equals(IWAConstants.ROLE_FORMAT)) {
                IWAServiceDataHolder.getInstance().setRoleFormat(PrincipalFormat.valueOf(parameterValue));
            } else if (parameterName.equals(IWAConstants.ALLOW_GUEST_LOGIN)) {
                IWAServiceDataHolder.getInstance().setAllowGuestLogin(Boolean.parseBoolean(parameterValue));
            } else if (parameterName.equals(IWAConstants.IMPERSONATE)) {
                IWAServiceDataHolder.getInstance().setImpersonate(Boolean.parseBoolean(parameterValue));
            } else if (parameterName.equals(IWAConstants.SECURITY_FILTER_PROVIDERS)) {
                providerNames = parameterValue.split("\\s+");
            } else if (parameterName.equals(IWAConstants.AUTH_PROVIDER)) {
                authProvider = parameterValue;
            } else {
                implParameters.put(parameterName, parameterValue);
            }
        }
    }

    if (authProvider != null) {
        try {
            IWAServiceDataHolder.getInstance()
                    .setAuth((IWindowsAuthProvider) Class.forName(authProvider).getConstructor().newInstance());
        } catch (Exception e) {
            throw new ServletException("Error loading '" + authProvider, e);
        }
    }

    if (IWAServiceDataHolder.getInstance().getAuth() == null) {
        IWAServiceDataHolder.getInstance().setAuth(new WindowsAuthProviderImpl());
    }

    if (providerNames != null) {
        IWAServiceDataHolder.getInstance().setProviders(new SecurityFilterProviderCollection(providerNames,
                IWAServiceDataHolder.getInstance().getAuth()));
    }

    // create default providers if none specified
    if (IWAServiceDataHolder.getInstance().getProviders() == null) {
        if (log.isDebugEnabled()) {
            log.debug("initializing default security filter providers");
        }
        IWAServiceDataHolder.getInstance().setProviders(
                new SecurityFilterProviderCollection(IWAServiceDataHolder.getInstance().getAuth()));
    }

    // apply provider implementation parameters
    for (Map.Entry<String, String> implParameter : implParameters.entrySet()) {
        String[] classAndParameter = implParameter.getKey().split("/", 2);
        if (classAndParameter.length == 2) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Setting " + classAndParameter[0] + ", " + classAndParameter[1] + "="
                            + implParameter.getValue());
                }
                SecurityFilterProvider provider = IWAServiceDataHolder.getInstance().getProviders()
                        .getByClassName(classAndParameter[0]);
                provider.initParameter(classAndParameter[1], implParameter.getValue());
            } catch (ClassNotFoundException e) {
                throw new ServletException(
                        "Invalid class: " + classAndParameter[0] + " in " + implParameter.getKey(), e);
            }
        } else {
            throw new ServletException("Invalid parameter: " + implParameter.getKey());
        }
    }
}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    if (repo != null) {
        return;//from   w w w  .ja va  2s . c om
    }

    try {
        // load properties file
        ServletContext context = config.getServletContext();
        String propsDir = context.getRealPath("/WEB-INF");
        String propsFileName = config.getInitParameter(SAIL_PROPERTIES);
        File propsFile = new File(propsDir, propsFileName);
        Properties sailProps = new Properties();
        sailProps.load(new FileInputStream(propsFile));
        BigdataSail sail = new BigdataSail(sailProps);
        repo = new BigdataSailRepository(sail);
        repo.initialize();
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new ServletException(ex);
    }

}

From source file:com.liferay.portal.servlet.MainServlet.java

public void init(ServletConfig config) throws ServletException {
    synchronized (MainServlet.class) {
        super.init(config);
        Config.initializeConfig();//from   ww  w.  j  a  va2s. c  o m
        com.dotmarketing.util.Config.setMyApp(config.getServletContext());
        // Need the plugin root dir before Hibernate comes up
        try {
            APILocator.getPluginAPI()
                    .setPluginJarDir(new File(config.getServletContext().getRealPath("WEB-INF/lib")));
        } catch (IOException e1) {
            Logger.debug(InitServlet.class, "IOException: " + e1.getMessage(), e1);
        }

        // Checking for execute upgrades
        try {
            StartupTasksExecutor.getInstance().executeUpgrades(config.getServletContext().getRealPath("."));
        } catch (DotRuntimeException e1) {
            throw new ServletException(e1);
        } catch (DotDataException e1) {
            throw new ServletException(e1);
        }

        // Starting the reindexation threads
        ClusterThreadProxy.createThread();
        if (Config.getBooleanProperty("DIST_INDEXATION_ENABLED")) {
            ClusterThreadProxy.startThread(Config.getIntProperty("DIST_INDEXATION_SLEEP", 500),
                    Config.getIntProperty("DIST_INDEXATION_INIT_DELAY", 5000));
        }

        ReindexThread.startThread(Config.getIntProperty("REINDEX_THREAD_SLEEP", 500),
                Config.getIntProperty("REINDEX_THREAD_INIT_DELAY", 5000));

        try {
            EventsProcessor.process(new String[] { StartupAction.class.getName() }, true);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Context path

        ServletConfig sc = getServletConfig();
        ServletContext ctx = getServletContext();

        String ctxPath = GetterUtil.get(sc.getInitParameter("ctx_path"), "/");

        ctx.setAttribute(WebKeys.CTX_PATH, StringUtil.replace(ctxPath + "/c", "//", "/"));

        ctx.setAttribute(WebKeys.CAPTCHA_PATH, StringUtil.replace(ctxPath + "/captcha", "//", "/"));

        ctx.setAttribute(WebKeys.IMAGE_PATH, StringUtil.replace(ctxPath + "/image", "//", "/"));

        // Company id

        _companyId = ctx.getInitParameter("company_id");

        ctx.setAttribute(WebKeys.COMPANY_ID, _companyId);

        // Initialize portlets

        try {
            String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")),
                    Http.URLtoString(ctx.getResource("/WEB-INF/portlet-ext.xml")),
                    Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")),
                    Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet-ext.xml")) };

            PortletManagerUtil.initEAR(xmls);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Initialize portlets display

        try {
            String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml"));

            Map oldCategories = (Map) WebAppPool.get(_companyId, WebKeys.PORTLET_DISPLAY);

            Map newCategories = PortletManagerUtil.getEARDisplay(xml);

            Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories);

            WebAppPool.put(_companyId, WebKeys.PORTLET_DISPLAY, mergedCategories);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Initialize skins
        //
        //         try {
        //            String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/liferay-skin.xml")),
        //                  Http.URLtoString(ctx.getResource("/WEB-INF/liferay-skin-ext.xml")) };
        //
        //            SkinManagerUtil.init(xmls);
        //         } catch (Exception e) {
        //            Logger.error(this, e.getMessage(), e);
        //         }

        // Check company

        try {
            CompanyLocalManagerUtil.checkCompany(_companyId);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Check web settings

        try {
            String xml = Http.URLtoString(ctx.getResource("/WEB-INF/web.xml"));

            _checkWebSettings(xml);
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        // Scheduler

        // try {
        // Iterator itr =
        // PortletManagerUtil.getPortlets(_companyId).iterator();
        //
        // while (itr.hasNext()) {
        // Portlet portlet = (Portlet)itr.next();
        //
        // String className = portlet.getSchedulerClass();
        //
        // if (portlet.isActive() && className != null) {
        // Scheduler scheduler =
        // (Scheduler)InstancePool.get(className);
        //
        // scheduler.schedule();
        // }
        // }
        // }
        // catch (ObjectAlreadyExistsException oaee) {
        // }
        // catch (Exception e) {
        // Logger.error(this,e.getMessage(),e);
        // }

        // Message Resources

        MultiMessageResources messageResources = (MultiMessageResources) ctx.getAttribute(Globals.MESSAGES_KEY);

        messageResources.setServletContext(ctx);

        WebAppPool.put(_companyId, Globals.MESSAGES_KEY, messageResources);

        // Current users

        WebAppPool.put(_companyId, WebKeys.CURRENT_USERS, new TreeMap());

        // HttpBridge

        TaskController.bridgeUserServicePath = "/httpbridge/home";
        TaskController.bridgeHttpServicePath = "/httpbridge/http";
        TaskController.bridgeGotoTag = "(goto)";
        TaskController.bridgeThenTag = "(then)";
        TaskController.bridgePostTag = "(post)";

        // Process startup events

        try {
            EventsProcessor.process(PropsUtil.getArray(PropsUtil.GLOBAL_STARTUP_EVENTS), true);

            EventsProcessor.process(PropsUtil.getArray(PropsUtil.APPLICATION_STARTUP_EVENTS),
                    new String[] { _companyId });
        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }

        PortalInstances.init(_companyId);
    }
}

From source file:fedora.localservices.saxon.SaxonServlet.java

/**
 * Initialize the servlet by setting up the stylesheet cache, the http
 * connection manager, and configuring credentials for the http client.
 *///  w w w  . j ava2s .  c om
@Override
public void init(ServletConfig config) throws ServletException {
    m_cache = new HashMap<String, Templates>();
    m_creds = new HashMap<String, UsernamePasswordCredentials>();
    m_cManager = new MultiThreadedHttpConnectionManager();
    m_cManager.getParams().setConnectionTimeout(TIMEOUT_SECONDS * 1000);

    Enumeration<?> enm = config.getInitParameterNames();
    while (enm.hasMoreElements()) {
        String name = (String) enm.nextElement();
        if (name.startsWith(CRED_PARAM_START)) {
            String value = config.getInitParameter(name);
            if (value.indexOf(":") == -1) {
                throw new ServletException(
                        "Malformed credentials for " + name + " -- expected ':' user/pass delimiter");
            }
            String[] parts = value.split(":");
            String user = parts[0];
            StringBuffer pass = new StringBuffer();
            for (int i = 1; i < parts.length; i++) {
                if (i > 1) {
                    pass.append(':');
                }
                pass.append(parts[i]);
            }
            m_creds.put(name.substring(CRED_PARAM_START.length()),
                    new UsernamePasswordCredentials(user, pass.toString()));
        }
    }
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    // get init param
    servletConfig = config;// www  . j a  va 2 s . c o m
    parameterName = config.getInitParameter("parameterName");
    forwardPathUpload = config.getInitParameter("forwardPathUpload");
    forwardPathDownload = config.getInitParameter("forwardPathDownload");
    forwardPathList = config.getInitParameter("forwardPathList");
    forwardPathRead = config.getInitParameter("forwardPathRead");
    forwardPathDelete = config.getInitParameter("forwardPathDelete");

    // set service
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(config.getServletContext());

    PropertiesService propertiesService = (PropertiesService) ctx.getBean("propertiesService");

    // overwrite configuration
    characterEncoding = propertiesService.getString("file.default.character.encoding", characterEncoding);
    sizeThreshold = propertiesService.getInt("file.default.file.size.threshold", sizeThreshold);
    fileSizeMax = propertiesService.getLong("file.default.file.size.max", fileSizeMax);
    requestSizeMax = propertiesService.getLong("file.default.request.size.max", requestSizeMax);
    realRepositoryPath = propertiesService.getString("file.default.real.repository.path", realRepositoryPath);
    tempRepositoryPath = propertiesService.getString("file.default.temp.repository.path", tempRepositoryPath);
    repositoryType = RepositoryType.valueOf(
            propertiesService.getString("file.default.real.repository.type", repositoryType.toString()));
    // mkdirs
    File file = new File(realRepositoryPath);
    if (!file.exists()) {
        try {
            FileUtils.forceMkdir(file);
        } catch (IOException e) {
            StringBuilder sb = new StringBuilder();
            sb.append("Cannot make directory: ");
            sb.append(file.toString());
            logger.error(sb.toString());
            throw new ServletException(sb.toString());
        }
    }
    file = new File(tempRepositoryPath);
    if (!file.exists()) {
        try {
            FileUtils.forceMkdir(file);
        } catch (IOException e) {
            StringBuilder sb = new StringBuilder();
            sb.append("Cannot make directory: ");
            sb.append(file.toString());
            logger.error(sb.toString());
            throw new ServletException(sb.toString());
        }
    }

}

From source file:org.wings.session.WingServlet.java

/**
 * The following init parameters are known by wings.
 * <p/>/*from  w  w  w .j av a  2  s  .  c  o  m*/
 * <dl compact>
 * <dt>externalizer.timeout</dt><dd> - The time, externalized objects
 * are kept, before they are removed</dd>
 * <p/>
 * <dt>content.maxlength</dt><dd> - Maximum content lengt for form posts.
 * Remember to increase this, if you make use of the SFileChooser
 * component</dd>
 * <p/>
 * <dt>filechooser.uploaddir</dt><dd> - The directory, where uploaded
 * files ar stored temporarily</dd>
 * </dl>
 * <p/>
 * <dt>wings.servlet.lookupname</dt><dd> - The name the wings sessions of
 * this servlet instance are stored in the servlet session hashtable</dd>
 * </dl>
 *
 * @throws ServletException
 */
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    servletConfig = config;

    if (log.isInfoEnabled()) {
        log.info("Initializing wingS global servlet with configuration:");
        for (Enumeration en = config.getInitParameterNames(); en.hasMoreElements();) {
            String param = (String) en.nextElement();
            log.info("    " + param + " = " + config.getInitParameter(param));
        }
    }

    initLookupName(config);
}

From source file:org.iff.infra.util.servlet.ProxyServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    {//add by tylerchen
        Enumeration<String> names = servletConfig.getInitParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = servletConfig.getInitParameter(name);
            initParameterMap.put(name, StringHelper.replaceBlock(value,
                    MapHelper.toMap("CPATH", servletConfig.getServletContext().getContextPath()), null));
        }//from w w  w .ja v  a2  s . c  om
    }

    String doLogStr = servletConfig.getInitParameter(P_LOG);
    if (doLogStr != null) {
        this.doLog = Boolean.parseBoolean(doLogStr);
    }

    String doForwardIPString = servletConfig.getInitParameter(P_FORWARDEDFOR);
    if (doForwardIPString != null) {
        this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
    }

    try {// get target url
        String paramName = initParameterMap.get("paramName");
        if (paramName != null) {
            String targetUri = null;//TODO ResourceKit.getValue(paramName);
            if (targetUri == null || targetUri.length() < 1) {
                targetUri = servletConfig.getInitParameter(P_TARGET_URI);
            }
            targetUriObj = new URI(targetUri);
        }
    } catch (Exception e) {
        throw new RuntimeException("Trying to process targetUri init parameter: " + e, e);
    }
    targetUri = targetUriObj.toString();

    HttpParams hcParams = new BasicHttpParams();
    readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class);
    proxyClient = createHttpClient(hcParams);
}