Example usage for javax.servlet FilterConfig getServletContext

List of usage examples for javax.servlet FilterConfig getServletContext

Introduction

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

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns a reference to the ServletContext in which the caller is executing.

Usage

From source file:com.avlesh.web.filter.responseheaderfilter.ResponseHeaderFilter.java

public void init(FilterConfig filterConfig) throws ServletException, RuntimeException {
    //if specified in web.xml, take that value as the config file
    if (StringUtils.isNotEmpty(filterConfig.getInitParameter("configFile"))) {
        configFileName = filterConfig.getInitParameter("configFile");
    }//  w  w w .  j a v  a 2 s  .  c o  m

    String fullConfigFilePath = filterConfig.getServletContext().getRealPath(configFileName);
    configFile = new File(fullConfigFilePath);
    if (!configFile.exists() || !configFile.canRead()) {
        //not expecting this, the config file should exist and be readable
        throw new RuntimeException("Cannot initialize ResponseHeaderFilter, error reading " + configFileName);
    }

    //object to hold preferences related to conf reloading
    confReloadInfo = new ConfReloadInfo();
    String reloadCheckIntervalStr = filterConfig.getInitParameter("reloadCheckInterval");
    //if web.xml filter definition has no "reloadCheckInterval" applied, default values in ConfReloadInfo are used  
    if (StringUtils.isNotEmpty(reloadCheckIntervalStr)) {
        Integer reloadCheckInterval = Integer.valueOf(reloadCheckIntervalStr);
        if (reloadCheckInterval > 0) {
            confReloadInfo.reloadEnabled = true;
            confReloadInfo.reloadCheckInterval = reloadCheckInterval;
        } else {
            //zero or negative values means don't ever reload
            confReloadInfo.reloadEnabled = false;
            confReloadInfo.reloadCheckInterval = 0;
        }
    }

    //parse all the mappings into Rules
    ConfigProcessor configProcessor = new ConfigProcessor(configFile);
    Map<Pattern, Mapping> allRules = configProcessor.getRuleMap();
    urlPatterns.addAll(allRules.keySet());
    rules.putAll(allRules);
}

From source file:com.matthewcasperson.validation.filter.ParameterValidationFilter.java

/**
 * Attempts to parse the XML config file. The config file is a JaxB serialisation of a
 * ParameterValidationDefinitionsImpl object. 
 *//*from  w w w .ja  v  a  2s.  co m*/
@Override
public void init(final FilterConfig config) throws ServletException {
    try {
        final String configFile = config.getInitParameter(CONFIG_PARAMETER_NAME);
        if (configFile != null) {
            LOGGER.log(Level.FINE, "Attempting to unmarshall " + configFile);
            final String configXml = IOUtils
                    .toString(config.getServletContext().getResourceAsStream(configFile));
            LOGGER.log(Level.FINE, "configXml is \n" + configXml);
            parameterValidationDefinitions = SERIALISATION_UTILS.readFromXML(configXml,
                    ParameterValidationDefinitionsImpl.class);
        }
    } catch (final Exception ex) {
        /*
         * This will happen if the supplied XML is invalid. Log the error
         */
        LOGGER.log(Level.SEVERE, ExceptionUtils.getFullStackTrace(ex));

        /*
         * Rethrow as we don't want to proceed with invalid configuration
         */
        throw new ServletException(ex);
    }

}

From source file:org.apache.ranger.security.web.filter.RangerKrbFilter.java

protected void initializeSecretProvider(FilterConfig filterConfig) throws ServletException {
    secretProvider = (SignerSecretProvider) filterConfig.getServletContext()
            .getAttribute(SIGNER_SECRET_PROVIDER_ATTRIBUTE);
    if (secretProvider == null) {
        // As tomcat cannot specify the provider object in the configuration.
        // It'll go into this path
        try {/*w  ww . j a va  2 s.  c  o m*/
            secretProvider = constructSecretProvider(filterConfig.getServletContext(), config, false);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    }
    signer = new Signer(secretProvider);
}

From source file:org.jasig.cas.client.authentication.AuthenticationFilter.java

protected void initInternal(final FilterConfig filterConfig) throws ServletException {
    logger.trace(this.getClass() + ".initInternal() BEGIN");

    if (!isIgnoreInitConfiguration()) {
        super.initInternal(filterConfig);

        // TODO ?    
        ServletContext context = filterConfig.getServletContext();
        String casServerName = context.getInitParameter(CAS_SERVER_NAME_CONTEXT_PARAMETER);
        CommonUtils.assertNotNull(casServerName, "casServerContextName cannot be null.");

        String casServerLoginPath = casServerName + "/login";

        String casServerAddress = getCasServerAddress();
        setCasServerLoginUrl(casServerAddress + "/" + casServerLoginPath);

        logger.trace("CasServerLoginUrl: " + this.casServerLoginUrl);

        setRenew(parseBoolean(getPropertyFromInitParams(filterConfig, "renew", "false")));
        logger.trace("Loaded renew parameter: " + this.renew);
        setGateway(parseBoolean(getPropertyFromInitParams(filterConfig, "gateway", "false")));
        logger.trace("Loaded gateway parameter: " + this.gateway);

        final String gatewayStorageClass = getPropertyFromInitParams(filterConfig, "gatewayStorageClass", null);

        if (gatewayStorageClass != null) {
            try {
                this.gatewayStorage = (GatewayResolver) Class.forName(gatewayStorageClass).newInstance();
            } catch (final Exception e) {
                logger.error(e, e);//ww  w.  ja va  2  s .co  m
                throw new ServletException(e);
            }
        }
    }

    logger.trace(this.getClass() + ".initInternal() END");
}

From source file:com.flexive.war.filter.FxFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    this.config = filterConfig;
    // Get the war deployment directory root on the server file system
    // Eg. "/opt/jboss-4.0.3RC1/server/default/./tmp/deploy/tmp52986Demo.ear-contents/web.war/"
    this.FILESYSTEM_WAR_ROOT = filterConfig.getServletContext().getRealPath("/");

    final String excluded = config.getInitParameter(PARAM_EXCLUDED_PATHS);
    if (StringUtils.isNotBlank(excluded)) {
        this.excludedPaths = Sets.newHashSet(StringUtils.split(excluded, ";'"));
        LOG.info("Excluded paths from FxFilter: " + this.excludedPaths);
    } else {/*from w ww . j a va2 s.  c o m*/
        this.excludedPaths = Collections.emptySet();
    }
}

From source file:com.octo.captcha.j2ee.servlet.ImageCaptchaFilter.java

/**
 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
 * @TODO : verify that URL begins with a "\" (or add it and trace
 * a warning) ?//from  w  w  w.  ja  v  a  2  s  . c o m
 */
public void init(final FilterConfig theFilterConfig) throws ServletException {

    // get associated servlet context
    this.servletContext = theFilterConfig.getServletContext();

    // get rendering URL from web.xml
    this.captchaRenderingURL = FilterConfigUtils.getStringInitParameter(theFilterConfig,
            CAPTCHA_RENDERING_URL_PARAMETER, true);

    // get verification URLs from web.xml (CSV list of URLs)
    String captchaVerificationURLs = FilterConfigUtils.getStringInitParameter(theFilterConfig,
            CAPTCHA_VERIFICATION_URLS_PARAMETER, true);

    // get forward error URLs from web.xml (CSV list of URLs)
    String captchaForwardErrorURLs = FilterConfigUtils.getStringInitParameter(theFilterConfig,
            CAPTCHA_ERROR_URLS_PARAMETER, true);

    // initialize the verificationForwards hashtable
    StringTokenizer verificationURLs = new StringTokenizer(captchaVerificationURLs, CSV_DELIMITER, false);
    StringTokenizer forwardErrorURLs = new StringTokenizer(captchaForwardErrorURLs, CSV_DELIMITER, false);
    if (verificationURLs.countTokens() != forwardErrorURLs.countTokens()) {
        // The URL lists are not consistant (there should be a forward and
        // a success for each verification URL)
        throw new ServletException(CAPTCHA_VERIFICATION_URLS_PARAMETER + " and " + CAPTCHA_ERROR_URLS_PARAMETER
                + " values are not consistant in web.xml : there should be"
                + " exactly one forward error for each verification URL !");
    }
    while (verificationURLs.hasMoreTokens()) {
        // Create a ForwardInfo for each verification URL and store it in
        // the verificationForward hashtable
        this.verificationForwards.put(verificationURLs.nextToken(), forwardErrorURLs.nextToken());
    }

    // get captcha ID parameter name from web.xml
    this.captchaIDParameterName = FilterConfigUtils.getStringInitParameter(theFilterConfig,
            CAPTCHA_ID_PARAMETER_NAME_PARAMETER, true);

    // get challenge response parameter name from web.xml
    this.captchaChallengeResponseParameterName = FilterConfigUtils.getStringInitParameter(theFilterConfig,
            CAPTCHA_RESPONSE_PARAMETER_NAME_PARAMETER, true);

    // get from web.xml the indicator signaling if the CaptchaFilter
    // should be registered to an MBean Server
    this.captchaRegisterToMBeanServer = FilterConfigUtils.getBooleanInitParameter(theFilterConfig,
            CAPTCHA_REGISTER_TO_MBEAN_SERVER_PARAMETER, false);

    // Extract the ImageCaptchaService initialization parameters
    // from web.xml
    Properties captchaServiceInitParameters = new Properties();
    {
        // get max number of simultaneous captchas from web.xml
        String captchaInternalStoreSize = FilterConfigUtils.getStringInitParameter(theFilterConfig,
                MAX_NUMBER_OF_SIMULTANEOUS_CAPTCHAS_PROP, true);
        captchaServiceInitParameters.setProperty(ImageCaptchaService.MAX_NUMBER_OF_SIMULTANEOUS_CAPTCHAS_PROP,
                captchaInternalStoreSize);
        // get minimum guaranted storage delay in seconds from web.xml
        String captchaTimeToLive = FilterConfigUtils.getStringInitParameter(theFilterConfig,
                MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS_PROP, true);
        captchaServiceInitParameters.setProperty(
                ImageCaptchaService.MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS_PROP, captchaTimeToLive);
        // get from web.xml the ImageCaptchaEngine implementation class name
        String engineClass = FilterConfigUtils.getStringInitParameter(theFilterConfig,
                CAPTCHA_ENGINE_CLASS_PARAMETER, true);
        captchaServiceInitParameters.setProperty(ImageCaptchaService.ENGINE_CLASS_INIT_PARAMETER_PROP,
                engineClass);
    }

    // create the ImageCaptchaService
    this.captchaService = new ImageCaptchaService(captchaServiceInitParameters);

    // get captcha ID max length from web.xml and set the
    // ImageCaptchaService captcha ID max length value with it
    Integer captchaIDMaxMLengthAsInteger = FilterConfigUtils.getIntegerInitParameter(theFilterConfig,
            CAPTCHA_ID_MAX_LENGTH_PARAMETER, true, 0, Integer.MAX_VALUE);
    this.captchaService.setCaptchaIDMaxLength(captchaIDMaxMLengthAsInteger.intValue());

    // register the ImageCaptchaService to an MBean server if specified
    if (this.captchaRegisterToMBeanServer) {
        registerToMBeanServer();
    }
}

From source file:org.apache.click.extras.cayenne.DataContextFilter.java

/**
 * Initialize the shared Cayenne configuration. If the
 * <tt>use-shared-cache</tt> init parameter is defined
 *
 * @see Filter#init(FilterConfig)//from w w w. ja  v  a2  s.c  om
 *
 * @param config the filter configuration
 * @throws RuntimeException if an initialization error occurs
 */
public synchronized void init(FilterConfig config) {

    HtmlStringBuffer buffer = new HtmlStringBuffer();
    buffer.append("DataContextFilter initialized: ");

    filterConfig = config;

    ServletUtil.initializeSharedConfiguration(config.getServletContext());

    dataDomain = Configuration.getSharedConfiguration().getDomain();

    String value = null;

    value = config.getInitParameter("auto-rollback");
    if (StringUtils.isNotBlank(value)) {
        autoRollback = "true".equalsIgnoreCase(value);
    }
    buffer.append(" auto-rollback=" + autoRollback);

    value = config.getInitParameter("session-scope");
    if (StringUtils.isNotBlank(value)) {
        sessionScope = "true".equalsIgnoreCase(value);
    }
    buffer.append(", session-scope=" + sessionScope);

    value = config.getInitParameter("shared-cache");
    if (StringUtils.isNotBlank(value)) {
        sharedCache = "true".equalsIgnoreCase(value);
    }
    buffer.append(", shared-cache=");
    buffer.append((sharedCache != null) ? sharedCache : "default");

    value = config.getInitParameter("oscache-enabled");
    boolean oscacheEnabled = "true".equalsIgnoreCase(value);
    if (oscacheEnabled) {
        dataDomain.setQueryCacheFactory(new OSQueryCacheFactory());
    }
    buffer.append(", oscache-enabled=" + oscacheEnabled);

    String classname = config.getInitParameter("lifecycle-listener");

    if (StringUtils.isNotEmpty(classname)) {
        try {
            @SuppressWarnings("unchecked")
            Class listenerClass = ClickUtils.classForName(classname);

            LifecycleCallbackRegistry registry = dataDomain.getEntityResolver().getCallbackRegistry();

            LifecycleListener lifecycleListener = (LifecycleListener) listenerClass.newInstance();

            if (registry.isEmpty(LifecycleEvent.POST_LOAD)) {
                registry.addDefaultListener(lifecycleListener);
                buffer.append(", lifecycle-listener=" + classname);

            } else {
                String message = "Could not get LifecycleCallbackRegistry from domain: " + dataDomain.getName();
                throw new RuntimeException(message);
            }

        } catch (Exception e) {
            String message = "Could not configure LifecycleCallbackRegistry: " + classname;
            throw new RuntimeException(message, e);
        }
    }

    // Log init data, note LogService is not yet initialized
    getFilterConfig().getServletContext().log(buffer.toString());
}

From source file:de.itsvs.cwtrpc.controller.CacheControlFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    final WebApplicationContext applicationContext;
    final CacheControlConfig config;
    final List<CacheControlUriConfig> uriConfigs;
    String configBeanName;/*from   w  w  w  .ja v  a  2  s  . c  o m*/

    configBeanName = filterConfig.getInitParameter(CONFIG_BEAN_NAME_INIT_PARAM);
    if (configBeanName == null) {
        configBeanName = CacheControlConfig.DEFAULT_BEAN_ID;
    }

    applicationContext = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
    if (log.isDebugEnabled()) {
        log.debug("Resolving cache control config with bean name '" + configBeanName
                + "' from application context");
    }
    config = applicationContext.getBean(configBeanName, CacheControlConfig.class);

    setLowerCaseMatch(config.isLowerCaseMatch());

    uriConfigs = new ArrayList<CacheControlUriConfig>();
    if (config.isDefaultsEnabled()) {
        log.debug("Adding default URI configurations");
        uriConfigs.addAll(createDefaultUriConfigs(config));
    }
    uriConfigs.addAll(config.getUriConfigs());
    setUriConfigs(createCacheControlUriConfigBuilder().build(uriConfigs));
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

public void init(FilterConfig config) throws ServletException {

    this.log = Logger.getLogger(this.getClass());
    this.context = config.getServletContext();
    this.location = "/" + this.context.getServletContextName() + "/";

    loadConfiguration(config);/*  ww w .  ja  va 2  s .  co m*/
    loadCiphers();
    loadDatabase();
}

From source file:cc.kune.core.server.rack.RackServletFilter.java

@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    if (initialized) {
        throw new ServerException("Trying to init RackServletFilter twice");
    }//from   ww  w.  j  a  va2s  . co m
    LOG.debug("INITIALIZING RackServletFilter...");
    final RackModule module = getModule(filterConfig);
    final RackBuilder builder = new RackBuilder();
    module.configure(builder);
    rack = builder.getRack();
    injector = (Injector) filterConfig.getServletContext().getAttribute(INJECTOR_PARENT_ATTRIBUTE);

    final Module otherGuiceModule = new Module() {
        @Override
        public void configure(final Binder binder) {
            // Here, other objects that are not register in Rack
            binder.bind(SearchEngineServletFilter.class)
                    .toInstance((SearchEngineServletFilter) filterConfig.getServletContext()
                            .getAttribute(SearchEngineServletFilter.SEARCH_ENGINE_FILTER_ATTRIBUTE));
        }
    };

    final Injector kuneChildInjector = installInjector(filterConfig, rack, injector, otherGuiceModule);
    final CustomJobFactory jobFactory = kuneChildInjector.getInstance(CustomJobFactory.class);
    jobFactory.setInjector(kuneChildInjector);
    startContainerListeners(rack.getListeners(), kuneChildInjector);
    docks = rack.getDocks();
    excludes = rack.getExcludes();
    initFilters(filterConfig);
    LOG.debug("INITIALIZATION DONE!");

    // kuneChildInjector.getInstance(CustomImportServlet.class).init(
    // kuneChildInjector.getInstance(KuneProperties.class));

    LOG.debug("Register some mbeans objects");
    kuneChildInjector.getInstance(MBeanRegister.class);

    LOG.debug("Configure remote logging");
    final String dir = FileUtils.isDirExistsAndNonEmpty(SYMBOL_MAPS_ON_PRODUCTION) ? "symbolMapsWse/"
            : FileUtils.isDirExistsAndNonEmpty(SYMBOL_MAPS_ON_DEV) ? SYMBOL_MAPS_ON_DEV : null;
    if (dir != null) {
        kuneChildInjector.getInstance(RemoteLoggingServiceImpl.class).setSymbolMapsDirectory(dir);
    }

    // We need to close wave Lucene indexer properly
    String searchType = injector.getInstance(Key.get(String.class, Names.named(CoreSettings.SEARCH_TYPE)));
    if ("lucene".equals(searchType)) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                LOG.debug("Closing wave indexer");
                injector.getInstance(LucenePerUserWaveViewHandlerImpl.class).close();
            }
        });
    }

    initialized = true;

    // Uncomment to generate the graph
    // graph("docs/wave-guice-graph.dot", injector);
    // graph("docs/kune-guice-graph.dot", kuneChildInjector);
}