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.ResponseHeaderManagerFilter.java

public void init(FilterConfig filterConfig) throws ServletException, RuntimeException {
    filterConfigObj = filterConfig;/* w  w w. ja  va 2  s . c  om*/

    //if specified in web.xml, take that value as the config file

    String fullConfigFilePath;

    // only expand the path with the realpath if not defined
    if (StringUtils.isNotEmpty(filterConfig.getInitParameter("configFile"))) {
        fullConfigFilePath = filterConfig.getInitParameter("configFile");
    } else {
        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 ResponseHeaderManagerFilter, 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, Rule> allRules = configProcessor.getRuleMap();
    urlPatterns.addAll(allRules.keySet());
    rules.putAll(allRules);
}

From source file:com.jsmartframework.web.manager.FilterControl.java

private void initHeaders(FilterConfig config) {
    String assetsUrl = CONFIG.getContent().getAssetsUrl();
    String contextPath = config.getServletContext().getContextPath();

    String headerPath = "/";
    if (StringUtils.isNotBlank(assetsUrl)) {
        headerPath = assetsUrl + (assetsUrl.endsWith("/") ? "" : "/");
    } else if (StringUtils.isNotBlank(contextPath)) {
        headerPath = contextPath + "/";
    }//from   w w w .j a va  2  s  . co  m

    Headers jsonHeaders = EXPRESSIONS.GSON.fromJson(convertResourceToString(FILTER_HEADERS), Headers.class);
    for (String style : jsonHeaders.getStyles()) {
        headerStyles.append(String.format(style, headerPath));
    }
    for (String script : jsonHeaders.getScripts()) {
        headerScripts.append(String.format(script, headerPath));
    }
}

From source file:de.innovationgate.wgpublisher.filter.WGAFilter.java

public void init(FilterConfig arg0) throws ServletException {
    _servletContext = arg0.getServletContext();
    _core = WGACore.retrieve(_servletContext);
    if (_core != null) {
        _core.setFilter(this);
    }/*from  w w w  .  ja  va2s  .  c o m*/
    setupFilterChain();
}

From source file:com.jsmartframework.web.manager.FilterControl.java

private String getAutomaticResourceVersion(FilterConfig config) {
    try {/*from   w w w .j  av  a  2  s  .c  o m*/
        Properties manifestProperties = new Properties();
        manifestProperties.load(config.getServletContext().getResourceAsStream(MANIFEST));
        return manifestProperties.getProperty(IMPLEMENTATION_VERSION);
    } catch (Exception e) {
        LOGGER.warning("Failed to retrieve [MANIFEST.MF] information for automatic versioning");
        return null;
    }
}

From source file:org.echocat.jemoni.jmx.support.ServletHealth.java

@Override
public void init(@Nonnull FilterConfig filterConfig) throws ServletException {
    final String mapping = filterConfig.getInitParameter(MAPPING_INIT_ATTRIBUTE);
    if (mapping != null) {
        setMapping(mapping);/*w ww  .  j a  v  a  2 s.c o m*/
    }
    final String registryRef = filterConfig.getInitParameter(REGISTRY_REF_INIT_ATTRIBUTE);
    if (!isEmpty(registryRef)) {
        setRegistry(getBeanFor(filterConfig.getServletContext(), registryRef, JmxRegistry.class));
    }
    final String interceptor = filterConfig.getInitParameter(INTERCEPTOR_INIT_ATTRIBUTE);
    if (!isEmpty(interceptor)) {
        setInterceptor(loadInterceptor(interceptor));
    }
    final String interceptorRef = filterConfig.getInitParameter(INTERCEPTOR_REF_INIT_ATTRIBUTE);
    if (!isEmpty(interceptorRef)) {
        setInterceptor(
                getBeanFor(filterConfig.getServletContext(), interceptorRef, ServletHealthInterceptor.class));
    }
    handleHostIncludeExcludesIfNeeded(filterConfig);
    init();
}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.java

public void init(FilterConfig filterConfig) {
    super.init(filterConfig);
    this.filterConfig = filterConfig;
    this.containerTweaks = new ContainerTweaks();
    Config config = new Config(filterConfig);
    DefaultFactory defaultFactory = new DefaultFactory(config);
    config.getServletContext().setAttribute("sitemesh.factory", defaultFactory);
    defaultFactory.refresh();/* w  w w . ja  v  a2s.  c o  m*/
    FactoryHolder.setFactory(defaultFactory);

    this.applicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(filterConfig.getServletContext());
    Map interceptors = applicationContext.getBeansOfType(PersistenceContextInterceptor.class);
    if (!interceptors.isEmpty()) {
        persistenceInterceptor = (PersistenceContextInterceptor) interceptors.values().iterator().next();
    }
}

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  .  ja v a 2  s  .com

            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:com.netspective.sparx.fileupload.FileUploadFilter.java

/**
 * This method is called by the server before the filter goes into service,
 * and here it determines the file upload directory.
 *
 * @param <b>config</b> The filter config passed by the servlet engine
 *//*from w  w w.j a v a2s.  com*/
public void init(FilterConfig config) throws ServletException {
    String tryDirectoryNames = config.getInitParameter(FILTERPARAM_UPLOAD_DIRS); // comma-separated list of directories to try
    if (tryDirectoryNames != null) {
        // find the first available directory either as a resource or a physical directory
        String[] tryDirectories = TextUtils.getInstance().split(tryDirectoryNames, ",", true);
        for (int i = 0; i < tryDirectories.length; i++) {
            String tryDirectory = tryDirectories[i];
            try {
                // first try the directory as a servlet resource
                java.net.URL uploadDirURL = config.getServletContext().getResource(tryDirectory);
                if (uploadDirURL != null && uploadDirURL.getFile() != null) {
                    uploadDir = uploadDirURL.getFile();
                    break;
                }

                File f = new File(tryDirectory);
                if (f.exists()) {
                    uploadDir = f.getAbsolutePath();
                    break;
                }

            } catch (java.net.MalformedURLException ex) {
                throw new ServletException(ex.getMessage());
            }
        }
    }

    // If upload directory parameter is null, assign a temp directory
    if (uploadDir == null) {
        File tempdir = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir");
        if (tempdir != null) {
            uploadDir = tempdir.toString();
        } else {
            throw new ServletException("Error in FileUploadFilter : No upload "
                    + "directory found: set an uploadDir init " + "parameter or ensure the "
                    + "javax.servlet.context.tempdir directory " + "is valid");
        }
    }

    uploadPrefix = config.getInitParameter(FILTERPARAM_UPLOADED_FILES_PREFIX);
    if (uploadPrefix == null)
        uploadPrefix = FILTERPARAMVALUE_DEFAULT_UPLOADED_FILES_PREFIX;
    log.info("uploadPrefix is: " + uploadPrefix);

    uploadFileArg = config.getInitParameter(FILTERPARAM_UPLOADED_FILES_REQUEST_ATTR_NAME);
    if (uploadFileArg == null)
        uploadFileArg = FILTERPARAMVALUE_DEFAULT_UPLOADED_FILES_REQUEST_ATTR_NAME;
    log.info("uploadFileArg is: " + uploadFileArg);

}

From source file:net.sf.j2ep.ProxyFilter.java

/**
 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
 * //  www . ja  v a 2s .  c  o  m
 * Called upon initialization, Will create the ConfigParser and get the
 * RuleChain back. Will also configure the httpclient.
 */
public void init(FilterConfig filterConfig) throws ServletException {
    log = LogFactory.getLog(ProxyFilter.class);
    AllowedMethodHandler.setAllowedMethods("OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE");

    httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    httpClient.getParams().setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, false);
    httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);

    String data = filterConfig.getInitParameter("dataUrl");
    if (data == null) {
        serverChain = null;
    } else {
        try {
            File dataFile = new File(filterConfig.getServletContext().getRealPath(data));
            ConfigParser parser = new ConfigParser(dataFile);
            serverChain = parser.getServerChain();
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}

From source file:org.ajax4jsf.webapp.BaseXMLFilter.java

public void init(FilterConfig config) throws ServletException {
    if (log.isDebugEnabled()) {
        log.debug("init XML filter service with class " + this.getClass().getName());
    }/*from  w  w  w .java2  s. com*/
    String forceXmlParameter = config.getInitParameter(FORCEXML_PARAMETER);
    if (forceXmlParameter == null) {
        forceXmlParameter = config.getServletContext()
                .getInitParameter(INIT_PARAMETER_PREFIX + FORCEXML_PARAMETER);
    }
    setupForceXml(forceXmlParameter);

    String forceNotRfParameter = config.getInitParameter(FORCENOTRF_PARAMETER);
    if (forceNotRfParameter == null) {
        forceNotRfParameter = config.getServletContext()
                .getInitParameter(INIT_PARAMETER_PREFIX + FORCENOTRF_PARAMETER);
    }
    setupForcenotrf(forceNotRfParameter);

    setMimetype((String) nz(config.getInitParameter(MIME_TYPE_PARAMETER), "text/xml"));
    setPublicid((String) nz(config.getInitParameter(PUBLICID_PARAMETER), getPublicid()));
    setSystemid((String) nz(config.getInitParameter(SYSTEMID_PARAMETER), getSystemid()));
    setNamespace((String) nz(config.getInitParameter(NAMESPACE_PARAMETER), getNamespace()));
    handleViewExpiredOnClient = Boolean.parseBoolean(
            config.getServletContext().getInitParameter(ContextInitParameters.HANDLE_VIEW_EXPIRED_ON_CLIENT));

}