Example usage for javax.servlet FilterConfig getInitParameter

List of usage examples for javax.servlet FilterConfig getInitParameter

Introduction

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

Prototype

public String getInitParameter(String name);

Source Link

Document

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

Usage

From source file:gov.nih.nci.cabig.caaers.web.filters.BadInputFilter.java

/**
 * {@inheritDoc}//from w  w w  .j a va 2s  .c  o  m
 */
public void init(FilterConfig filterConfig) throws ServletException {

    servletContext = filterConfig.getServletContext();

    // Parse the Filter's init parameters.
    String allowString = filterConfig.getInitParameter("allowURIs");
    if (!StringUtils.isBlank(allowString)) {
        this.allowURIs = Arrays.asList(allowString.split(",\\s*"));
    }
    String allowParams = filterConfig.getInitParameter("allowParams");
    if (!StringUtils.isBlank(allowParams)) {
        this.allowParams = Arrays.asList(allowParams.split(",\\s*"));
    }
    setAllow(filterConfig.getInitParameter("allow"));
    setDeny(filterConfig.getInitParameter("deny"));
    String initParam = filterConfig.getInitParameter("escapeQuotes");
    if (initParam != null) {
        boolean flag = Boolean.parseBoolean(initParam);
        setEscapeQuotes(flag);
    }
    initParam = filterConfig.getInitParameter("escapeAngleBrackets");
    if (initParam != null) {
        boolean flag = Boolean.parseBoolean(initParam);
        setEscapeAngleBrackets(flag);
    }
    initParam = filterConfig.getInitParameter("escapeHtmlFormTags");
    if (initParam != null) {
        boolean flag = Boolean.parseBoolean(initParam);
        setEscapeHtmlFormTags(flag);
    }
    initParam = filterConfig.getInitParameter("escapeNewlines");
    if (initParam != null) {
        boolean flag = Boolean.parseBoolean(initParam);
        setEscapeNewlines(flag);
    }

    initParam = filterConfig.getInitParameter("escapeJavaScript");
    if (initParam != null) {
        boolean flag = Boolean.parseBoolean(initParam);
        setEscapeJavaScript(flag);
    }

    //        logger.debug(toString() + " initialized.");
    logger.debug(toString() + " initialized.");

}

From source file:com.onehippo.gogreen.login.HstConcurrentLoginFilter.java

@SuppressWarnings("unchecked")
public void init(FilterConfig filterConfig) throws ServletException {
    ServletContext servletContext = filterConfig.getServletContext();
    usernameHttpSessionWrapperMap = (Map<String, HttpSessionWrapper>) servletContext
            .getAttribute(USERNAME_SESSIONID_MAP_ATTR);

    if (usernameHttpSessionWrapperMap == null) {
        usernameHttpSessionWrapperMap = Collections.synchronizedMap(new HashMap<String, HttpSessionWrapper>());
        servletContext.setAttribute(USERNAME_SESSIONID_MAP_ATTR, usernameHttpSessionWrapperMap);
    }/* w  ww.java 2  s  .co  m*/

    String[] disallowConcurrentLoginUsernamesArray = StringUtils
            .split(filterConfig.getInitParameter("disallowConcurrentLoginUsernames"), " ,\t\r\n");

    if (disallowConcurrentLoginUsernamesArray != null && disallowConcurrentLoginUsernamesArray.length > 0) {
        disallowConcurrentLoginUsernames = new HashSet<String>(
                Arrays.asList(disallowConcurrentLoginUsernamesArray));
    }

    log.info(
            "HstConcurrentLoginFilter's disallowConcurrentLoginUsernames: " + disallowConcurrentLoginUsernames);

    String[] allowConcurrentLoginUsernamesArray = StringUtils
            .split(filterConfig.getInitParameter("allowConcurrentLoginUsernames"), " ,\t\r\n");

    if (allowConcurrentLoginUsernamesArray != null && allowConcurrentLoginUsernamesArray.length > 0) {
        allowConcurrentLoginUsernames = new HashSet<String>(Arrays.asList(allowConcurrentLoginUsernamesArray));
    }

    earlySessionInvalidation = BooleanUtils
            .toBoolean(filterConfig.getInitParameter("earlySessionInvalidation"));

    log.info("HstConcurrentLoginFilter's allowConcurrentLoginUsernames: " + allowConcurrentLoginUsernames);
}

From source file:org.josso.servlet.agent.JossoFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    // Validate and update our current component state
    ctx = filterConfig.getServletContext();
    String nom = filterConfig.getInitParameter("leNom");
    logg("Initialisation du filtre pour=" + nom + " contextName=" + ctx.getContextPath());
    ctx.setAttribute(KEY_SESSION_MAP, new HashMap());
    if (_agent == null) {

        try {//from   w  w  w .j  ava2  s.  c o  m

            Lookup lookup = Lookup.getInstance();
            lookup.init("josso-agent2-config.xml", ctx.getContextPath()); // For spring compatibility ...

            // We need at least an abstract SSO Agent
            _agent = (FacesSSOAgent) lookup.lookupSSOAgent();
            if (debug == 1)
                _agent.setDebug(1);
            _agent.start();
        } catch (Exception e) {
            throw new ServletException("Error starting SSO Agent : " + e.getMessage(), e);
        }

    }

}

From source file:org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticationFilter.java

/**
 * Returns the proxyuser configuration. All returned properties must start
 * with <code>proxyuser.</code>'
 * <p/>/* ww  w  . jav  a 2s .  c  o  m*/
 * Subclasses may override this method if the proxyuser configuration is 
 * read from other place than the filter init parameters.
 *
 * @param filterConfig filter configuration object
 * @return the proxyuser configuration properties.
 * @throws ServletException thrown if the configuration could not be created.
 */
protected Configuration getProxyuserConfiguration(FilterConfig filterConfig) throws ServletException {
    // this filter class gets the configuration from the filter configs, we are
    // creating an empty configuration and injecting the proxyuser settings in
    // it. In the initialization of the filter, the returned configuration is
    // passed to the ProxyUsers which only looks for 'proxyusers.' properties.
    Configuration conf = new Configuration(false);
    Enumeration<?> names = filterConfig.getInitParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        if (name.startsWith(PROXYUSER_PREFIX + ".")) {
            String value = filterConfig.getInitParameter(name);
            conf.set(name, value);
        }
    }
    return conf;
}

From source file:org.surfnet.oaaas.auth.AuthorizationServerFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    /*//w  w w .  j av  a  2  s .  co  m
     * First check on the presence of a init-param where to look for the properties to support
     * multiple resource servers in the same war. Then look for second best apis-resource-server.properties file, then
     * try to use the filter config if parameters are present. If this also
     * fails trust on the setters (e.g. probably in test modus), but apply
     * fail-fast strategy
     */
    ClassPathResource res = null;
    String propertiesFile = filterConfig.getInitParameter("apis-resource-server.properties.file");
    if (StringUtils.isNotEmpty(propertiesFile)) {
        res = new ClassPathResource(propertiesFile);
    }
    if (res == null || !res.exists()) {
        res = new ClassPathResource("apis-resource-server.properties");
    }
    if (res != null && res.exists()) {
        Properties prop = new Properties();
        try {
            prop.load(res.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException("Error in reading the apis-resource-server.properties file", e);
        }
        resourceServerKey = prop.getProperty("adminService.resourceServerKey");
        resourceServerSecret = prop.getProperty("adminService.resourceServerSecret");
        authorizationServerUrl = prop.getProperty("adminService.tokenVerificationUrl");
        cacheEnabled = Boolean.valueOf(prop.getProperty("adminService.cacheEnabled"));
        String allowCorsRequestsProperty = prop.getProperty("adminService.allowCorsRequests");
        if (StringUtils.isNotEmpty(allowCorsRequestsProperty)) {
            allowCorsRequests = Boolean.valueOf(allowCorsRequestsProperty);
        }
        String typeInformationIsIncludedProperty = prop.getProperty("adminService.jsonTypeInfoIncluded");
        if (StringUtils.isNotEmpty(typeInformationIsIncludedProperty)) {
            typeInformationIsIncluded = Boolean.valueOf(typeInformationIsIncludedProperty);
        }
    } else if (filterConfig.getInitParameter("resource-server-key") != null) {
        resourceServerKey = filterConfig.getInitParameter("resource-server-key");
        resourceServerSecret = filterConfig.getInitParameter("resource-server-secret");
        authorizationServerUrl = filterConfig.getInitParameter("authorization-server-url");
        typeInformationIsIncluded = Boolean
                .valueOf(filterConfig.getInitParameter("type-information-is-included"));
    }
    Assert.hasText(resourceServerKey, "Must provide a resource server key");
    Assert.hasText(resourceServerSecret, "Must provide a resource server secret");
    Assert.hasText(authorizationServerUrl, "Must provide a authorization server url");

    this.authorizationValue = new String(
            Base64.encodeBase64(resourceServerKey.concat(":").concat(resourceServerSecret).getBytes()));
    if (cacheAccessTokens()) {
        this.cache = buildCache();
        Assert.notNull(this.cache);
    }

    this.client = createClient();

    this.objectMapper = createObjectMapper(typeInformationIsIncluded);
}

From source file:org.owasp.esapi.waf.ESAPIWebApplicationFirewallFilter.java

/**
 * /*from  w w w.  j av a2s .c  o m*/
 * This function is invoked at application startup and when the
 * configuration file polling period has elapsed and a change in the
 * configuration file has been detected.
 * 
 * It's main purpose is to read the configuration file and establish the
 * configuration object model for use at runtime during the
 * <code>doFilter()</code> method.
 */
public void init(FilterConfig fc) throws ServletException {

    /*
     * This variable is saved so that we can retrieve it later to re-invoke
     * this function.
     */
    this.fc = fc;

    logger.debug(Logger.EVENT_SUCCESS, ">> Initializing WAF");
    /*
     * Pull logging file.
     */

    // Demoted scope to a local since this is the only place it is
    // referenced
    String logSettingsFilename = fc.getInitParameter(LOGGING_FILE_PARAM);

    String realLogSettingsFilename = fc.getServletContext().getRealPath(logSettingsFilename);

    if (realLogSettingsFilename == null || (!new File(realLogSettingsFilename).exists())) {
        throw new ServletException(
                "[ESAPI WAF] Could not find log file at resolved path: " + realLogSettingsFilename);
    }

    /*
     * Pull main configuration file.
     */

    configurationFilename = fc.getInitParameter(CONFIGURATION_FILE_PARAM);

    configurationFilename = fc.getServletContext().getRealPath(configurationFilename);

    if (configurationFilename == null || !new File(configurationFilename).exists()) {
        throw new ServletException(
                "[ESAPI WAF] Could not find configuration file at resolved path: " + configurationFilename);
    }

    /*
     * Find out polling time from a parameter. If none is provided, use the
     * default (10 seconds).
     */

    String sPollingTime = fc.getInitParameter(POLLING_TIME_PARAM);

    if (sPollingTime != null) {
        pollingTime = Long.parseLong(sPollingTime);
    } else {
        pollingTime = DEFAULT_POLLING_TIME;
    }

    /*
     * Open up configuration file and populate the AppGuardian configuration
     * object.
     */

    FileInputStream inputStream = null;

    try {
        String webRootDir = fc.getServletContext().getRealPath("/");
        inputStream = new FileInputStream(configurationFilename);
        appGuardConfig = ConfigurationParser.readConfigurationFile(inputStream, webRootDir);
        DOMConfigurator.configure(realLogSettingsFilename);
        lastConfigReadTime = System.currentTimeMillis();
    } catch (FileNotFoundException e) {
        throw new ServletException(e);
    } catch (ConfigurationException e) {
        throw new ServletException(e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.ambraproject.struts2.AmbraStruts2Dispatcher.java

@Override
public void init(FilterConfig filterConfig) {
    // Copied the init function of the StrutsPrepareAndExecuteFilter class
    // and modified how the Dispatcher object is getting created by passing our own configuration values.

    // There should be a better way to do this than what we are doing here.

    InitOperations init = new InitOperations();
    Dispatcher dispatcher = null;//  w w  w.  j a  v  a  2s.  c o  m
    try {
        FilterHostConfig config = new FilterHostConfig(filterConfig);
        init.initLogging(config);

        // initDispatcher is the function we really want to override
        // dispatcher = init.initDispatcher(config);

        Map<String, String> params = new HashMap<String, String>();
        for (Iterator e = config.getInitParameterNames(); e.hasNext();) {
            String name = (String) e.next();
            String value = filterConfig.getInitParameter(name);

            params.put(name, value);
        }

        // adding our own configuration values
        Configuration conf = ConfigurationStore.getInstance().getConfiguration();
        for (String name : keys) {
            String val = conf.getString(name);

            if (val != null) {
                log.info("Setting struts constant: " + name + "=" + val);
                params.put(name, val);
            }
        }

        dispatcher = new Dispatcher(config.getServletContext(), params);
        dispatcher.init();

        init.initStaticContentLoader(config, dispatcher);

        prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
        execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
        this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

        postInit(dispatcher, filterConfig);
    } finally {
        if (dispatcher != null) {
            dispatcher.cleanUpAfterInit();
        }
        init.cleanup();
    }
}

From source file:org.apache.myfaces.webapp.filter.ExtensionsFilter.java

/**
 * Init method for this filter.//from   w  w  w .  j a  v a  2  s .  c  om
 * <p>
 * The following filter init parameters can be configured in the web.xml file
 * for this filter:
 * <ul>
 * <li>uploadMaxFileSize</li>
 * <li>uploadThresholdSize</li>
 * <li>uploadRepositoryPath</li>
 * <li>uploadMaxSize</li>
 * <li>cacheFileSizeErrors</li>
 * </ul>
 * </p>
 * <p>
 * All size parameters may have the suffix "g" (gigabytes), "m" (megabytes) or "k" (kilobytes).
 * </p>
 * 
 * <h2>uploadMaxFileSize</h2>
 * 
 * Sets the maximum allowable size for uploaded files.
 * <p>
 * If the user attempts to upload a file which is larger than this, then the data <i>is</i>
 * transmitted from the browser to the server (this cannot be prevented with standard HTML
 * functionality). However the file will not be saved in memory or on disk. An error message
 * will be added to the standard JSF error messages, and the page re-rendered (as for a
 * validation failure).
 * </p>
 * <p>
 * The default value is 100 Megabytes.
 * </p>
 * 
 * <h2>uploadThresholdSize</h2>
 * 
 * Sets the size threshold beyond which files are written directly to disk. Files which are
 * smaller than this are simply held in memory. The default is 1 Megabyte.
 * 
 * <h2>uploadRepositoryPath</h2>
 * 
 * Sets the directory in which temporary files (ie caches for those uploaded files that
 * are larger than uploadThresholdSize) are to be stored.
 * 
 * <h2>uploadMaxSize</h2>
 * 
 * Sets the maximum allowable size for the current request. If not set, its value is the 
 * value set on uploadMaxFileSize param. 
 * 
 * <h2>cacheFileSizeErrors</h2>
 * 
 * Catch and swallow FileSizeLimitExceededExceptions in order to return as
 * many usable items as possible.
 * 
 */
public void init(FilterConfig filterConfig) {
    // Note that the code here to extract FileUpload configuration params is not actually used.
    // The handling of multipart requests was moved from this Filter into a custom FacesContext
    // (TomahawkFacesContextWrapper) so that Portlets could be supported (Portlets cannot use
    // servlet filters).
    //
    // For backwards compatibility, the TomahawkFacesContextWrapper class *parses* the
    // web.xml to retrieve these same filter config params. That is IMO seriously ugly
    // and hopefully will be fixed.

    String param = filterConfig.getInitParameter("uploadMaxFileSize");

    _uploadMaxFileSize = resolveSize(param, _uploadMaxFileSize);

    param = filterConfig.getInitParameter("uploadMaxSize");

    if (param != null) {
        _uploadMaxSize = resolveSize(param, _uploadMaxSize);
    } else {
        //If not set, default to uploadMaxFileSize
        _uploadMaxSize = resolveSize(param, _uploadMaxFileSize);
    }

    param = filterConfig.getInitParameter("uploadThresholdSize");

    _uploadThresholdSize = resolveSize(param, _uploadThresholdSize);

    _uploadRepositoryPath = filterConfig.getInitParameter("uploadRepositoryPath");

    _cacheFileSizeErrors = getBooleanValue(filterConfig.getInitParameter("cacheFileSizeErrors"), false);

    _servletContext = filterConfig.getServletContext();

    filterConfig.getServletContext().setAttribute(EXTENSIONS_FILTER_INITIALIZED, true);
}

From source file:org.craftercms.cstudio.share.servlet.ShareAuthenticationFilter.java

public void init(FilterConfig filterConfig) {

    this.servletContext = filterConfig.getServletContext();
    ApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.servletContext);
    /* retrieve the connector service */
    this.connectorService = (ConnectorService) context.getBean("connector.service");
    /* retrieve the cookie manager */
    this.cookieManager = (CookieManager) context.getBean("rlCookieManager");
    /* retrieve the user preference manager */
    this.userPreferenceManager = (UserPreferenceManager) context.getBean("rlUserPreferenceManager");
    this.enableRememberLastPage = new Boolean(filterConfig.getInitParameter("enableRememberLastPage"));
    this.defaultLastPage = filterConfig.getInitParameter("defaultRememberLastPage");

}

From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    otapStage = AppConstants.getInstance().getResolvedProperty("otap.stage");
    instanceName = AppConstants.getInstance().getResolvedProperty("instance.name");

    String ldapAuthMode = AppConstants.getInstance().getString("ldap.auth.mode", LDAP_AUTH_MODE_NONE_STR);
    ldapAuthModeNum = getLdapAuthModeNum(ldapAuthMode);
    if (ldapAuthModeNum < 0) {
        log.warn("Unknown ldapAuthMode [" + ldapAuthMode + "], will use [" + LDAP_AUTH_MODE_NONE_STR + "]");
        ldapAuthModeNum = 0;/*from w  w w .  jav  a2 s  . c  o  m*/
    }

    if (ldapAuthModeNum >= LDAP_AUTH_MODE_SIMPLE) {
        String allowedExtentionsString = filterConfig.getInitParameter("allowedExtentions");
        if (allowedExtentionsString != null) {
            allowedExtentions.addAll(Arrays.asList(allowedExtentionsString.split("\\s+")));
        }

        String allowedObserverPathsString = filterConfig.getInitParameter("allowedObserverPaths");
        if (allowedObserverPathsString != null) {
            allowedObserverPaths.addAll(Arrays.asList(allowedObserverPathsString.split("\\s+")));
        }

        String allowedDataAdminPathsString = filterConfig.getInitParameter("allowedDataAdminPaths");
        if (allowedDataAdminPathsString != null) {
            allowedDataAdminPaths.addAll(Arrays.asList(allowedDataAdminPathsString.split("\\s+")));
        }

        String allowedTesterPathsString = filterConfig.getInitParameter("allowedTesterPaths");
        if (allowedTesterPathsString != null) {
            allowedTesterPaths.addAll(Arrays.asList(allowedTesterPathsString.split("\\s+")));
        }

        if (ldapAuthModeNum >= LDAP_AUTH_MODE_BASIC) {
            ldapAuthUrl = AppConstants.getInstance().getResolvedProperty("ldap.auth.url");
            if (ldapAuthUrl == null) {
                String ldapAuthUrlProp = "ldap.auth." + otapStage.toLowerCase() + ".url";
                ldapAuthUrl = AppConstants.getInstance().getResolvedProperty(ldapAuthUrlProp);
            }

            ldapAuthUserBase = AppConstants.getInstance().getResolvedProperty("ldap.auth.user.base");
            if (ldapAuthModeNum >= LDAP_AUTH_MODE_FULL) {
                ldapAuthObserverBase = AppConstants.getInstance()
                        .getResolvedProperty("ldap.auth.observer.base");
                if (ldapAuthObserverBase == null) {
                    throw new ServletException("property [ldap.auth.observer.base] should be set");
                }
                ldapAuthDataAdminBase = AppConstants.getInstance()
                        .getResolvedProperty("ldap.auth.dataadmin.base");
                if (ldapAuthDataAdminBase == null) {
                    throw new ServletException("property [ldap.auth.dataadmin.base] should be set");
                }
                ldapAuthTesterBase = AppConstants.getInstance().getResolvedProperty("ldap.auth.tester.base");
                if (ldapAuthTesterBase == null) {
                    throw new ServletException("property [ldap.auth.tester.base] should be set");
                }
            }
        }
    }
}