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:hudson.security.SecurityRealm.java

/**
 * Creates {@link Filter} that all the incoming HTTP requests will go through
 * for authentication./*from   w  w  w  . ja  v a  2 s. co m*/
 *
 * <p>
 * The default implementation uses {@link #getSecurityComponents()} and builds
 * a standard filter chain from /WEB-INF/security/SecurityFilters.groovy.
 * But subclasses can override this to completely change the filter sequence.
 *
 * <p>
 * For other plugins that want to contribute {@link Filter}, see
 * {@link PluginServletFilter}.
 *
 * @since 1.271
 */
public Filter createFilter(FilterConfig filterConfig) {
    LOGGER.entering(SecurityRealm.class.getName(), "createFilter");

    Binding binding = new Binding();
    SecurityComponents sc = getSecurityComponents();
    binding.setVariable("securityComponents", sc);
    binding.setVariable("securityRealm", this);
    BeanBuilder builder = new BeanBuilder();
    builder.parse(
            filterConfig.getServletContext().getResourceAsStream("/WEB-INF/security/SecurityFilters.groovy"),
            binding);
    WebApplicationContext context = builder.createApplicationContext();
    return (Filter) context.getBean("filter");
}

From source file:wicket.protocol.http.WicketFilter.java

/**
 * //from  www .  java2 s .co m
 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
 */
public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;

    IWebApplicationFactory factory = getApplicationFactory();

    // Construct WebApplication subclass
    this.webApplication = factory.createApplication(this);

    // Set this WicketServlet as the servlet for the web application
    this.webApplication.setWicketFilter(this);

    // Store instance of this application object in servlet context to make
    // integration with outside world easier
    String contextKey = "wicket:" + filterConfig.getFilterName();
    filterConfig.getServletContext().setAttribute(contextKey, this.webApplication);

    filterPath = filterConfig.getInitParameter(FILTER_PATH_PARAM);

    try {
        Application.set(webApplication);

        // Call internal init method of web application for default
        // initialisation
        this.webApplication.internalInit();

        // Call init method of web application
        this.webApplication.init();

        // We initialize components here rather than in the constructor or
        // in the internal init, because in the init method class aliases
        // can be added, that would be used in installing resources in the
        // component.
        this.webApplication.initializeComponents();

        // Finished
        log.info("Wicket application " + this.webApplication.getName() + " started [factory="
                + factory.getClass().getName() + "]");
    } finally {
        Application.unset();
    }
}

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

/**
 * /*from  www. j  ava  2 s. co 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:com.jsmartframework.web.manager.FilterControl.java

private void initResources(FilterConfig config) {
    try {/*from   w  ww  .j  a  v  a  2s . c o  m*/
        if (CONFIG.getContent().getAssetsUrl() != null) {
            LOGGER.log(Level.INFO, "Using external assets, please provide the jsmart assets content at ["
                    + CONFIG.getContent().getAssetsUrl() + "]");
        }

        ServletContext context = config.getServletContext();
        Set<String> libs = context.getResourcePaths(LIB_FILE_PATH);

        if (libs == null || libs.isEmpty()) {
            LOGGER.log(Level.SEVERE, "Could not find the JSmart library JAR file. Empty [" + LIB_FILE_PATH
                    + "] resource folder.");
            return;
        }

        String libFilePath = null;
        for (String lib : libs) {
            Matcher matcher = JAR_FILE_PATTERN.matcher(lib);
            if (matcher.find()) {
                libFilePath = matcher.group();
                break;
            }
        }

        if (libFilePath == null) {
            LOGGER.log(Level.SEVERE,
                    "Could not find the JSmart library JAR file inside [" + LIB_FILE_PATH + "]");
            return;
        }

        Resources jsonResources = EXPRESSIONS.GSON.fromJson(convertResourceToString(FILTER_RESOURCES),
                Resources.class);

        File libFile = new File(context.getRealPath(libFilePath));
        Dir content = Vfs.fromURL(libFile.toURI().toURL());

        Iterator<Vfs.File> files = content.getFiles().iterator();
        while (files.hasNext()) {
            Vfs.File file = files.next();

            // Copy index.jsp and replace content to redirect to welcome-url case configured
            if (file.getRelativePath().startsWith(INDEX_JSP)) {
                if (CONFIG.getContent().getWelcomeUrl() != null) {
                    StringWriter writer = new StringWriter();
                    IOUtils.copy(file.openInputStream(), writer);
                    String index = writer.toString().replace("{0}", CONFIG.getContent().getWelcomeUrl());
                    copyFileResource(new ByteArrayInputStream(index.getBytes(ENCODING)), file.getRelativePath(),
                            context);
                }
            }

            // Do not copy anything if assets-url was provided
            if (CONFIG.getContent().getAssetsUrl() != null) {
                continue;
            }

            // Copy js, css and font resources to specific location
            for (String resource : jsonResources.getResources()) {
                String resourcePath = resource.replace("*", "");

                if (file.getRelativePath().startsWith(resourcePath)) {
                    initDirResources(context.getRealPath(PATH_SEPARATOR), file.getRelativePath());
                    copyFileResource(file.openInputStream(), file.getRelativePath(), context);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage());
    }
}

From source file:org.alfresco.web.site.servlet.CSRFFilter.java

/**
 * Parses the filter rule config.//  w ww.j  ava2  s .c  o m
 *
 * @param config The filter config
 * @throws ServletException if the rule filter config is invalid
 */
@Override
public void init(FilterConfig config) throws ServletException {
    servletContext = config.getServletContext();

    ApplicationContext context = getApplicationContext();

    ConfigService configService = (ConfigService) context.getBean("web.config");

    // Retrieve the remote configuration
    Config csrfConfig = (Config) configService.getConfig("CSRFPolicy");
    if (csrfConfig == null) {
        enabled = false;
        if (logger.isDebugEnabled())
            logger.debug("There is no 'CSRFPolicy' config, filter will allow all requests.");
    } else {
        // Parse properties
        ConfigElement propertiesConfig = csrfConfig.getConfigElement("properties");
        if (propertiesConfig != null) {
            List<ConfigElement> propertiesConfigList = propertiesConfig.getChildren();
            String value;
            if (propertiesConfigList != null && propertiesConfigList.size() > 0) {
                for (ConfigElement propertyConfig : propertiesConfigList) {
                    value = propertyConfig.getValue();
                    properties.put(propertyConfig.getName(), value != null ? value : "");
                }
            }
        }

        // Parse filter and its rules
        ConfigElement filterConfig = csrfConfig.getConfigElement("filter");
        if (filterConfig == null) {
            enabled = false;
            if (logger.isDebugEnabled())
                logger.debug("The 'CSRFPolicy' config had no filter, filter will allow all requests.");
        } else {
            List<ConfigElement> rulesConfigList = filterConfig.getChildren("rule");
            if (rulesConfigList == null || rulesConfigList.size() == 0) {
                enabled = false;
                if (logger.isDebugEnabled())
                    logger.debug("The 'CSRFPolicy' filter config was empty, filter will allow all requests.");
            } else {
                rules = new LinkedList<Rule>();
                for (ConfigElement ruleConfig : rulesConfigList) {
                    rules.add(createRule(ruleConfig));
                }
            }
        }
    }
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

/**
 * Initialisation.// w ww  . ja v  a 2  s . c om
 * @throws ServletException e
 */
@Before
public void setUp() throws ServletException {
    try {
        final Field field = MonitoringFilter.class.getDeclaredField("instanceCreated");
        field.setAccessible(true);
        field.set(null, false);
    } catch (final IllegalAccessException e) {
        throw new IllegalStateException(e);
    } catch (final NoSuchFieldException e) {
        throw new IllegalStateException(e);
    }
    final FilterConfig config = createNiceMock(FilterConfig.class);
    final ServletContext context = createNiceMock(ServletContext.class);
    expect(config.getServletContext()).andReturn(context).anyTimes();
    expect(config.getFilterName()).andReturn(FILTER_NAME).anyTimes();
    // anyTimes sur getInitParameter car TestJdbcDriver a pu fixer la proprit systme  false
    expect(context.getInitParameter(Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.DISABLED.getCode()))
            .andReturn(null).anyTimes();
    expect(config.getInitParameter(Parameter.DISABLED.getCode())).andReturn(null).anyTimes();
    expect(context.getMajorVersion()).andReturn(2).anyTimes();
    expect(context.getMinorVersion()).andReturn(5).anyTimes();
    expect(context.getServletContextName()).andReturn("test webapp").anyTimes();
    // mockJetty pour avoir un applicationServerIconName dans JavaInformations
    expect(context.getServerInfo()).andReturn("mockJetty").anyTimes();
    // dependencies pour avoir des dpendances dans JavaInformations
    final Set<String> dependencies = new LinkedHashSet<String>(
            Arrays.asList("/WEB-INF/lib/jrobin.jar", "/WEB-INF/lib/javamelody.jar"));
    // et flags pour considrer que les ressources pom.xml et web.xml existent
    JavaInformations.setWebXmlExistsAndPomXmlExists(true, true);
    expect(context.getResourcePaths("/WEB-INF/lib/")).andReturn(dependencies).anyTimes();
    expect(context.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    monitoringFilter = new MonitoringFilter();
    monitoringFilter.setApplicationType("Test");
    replay(config);
    replay(context);
    monitoringFilter.init(config);
    verify(config);
    verify(context);
}

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

private void versionResources(FilterConfig config) {
    try {// ww  w  .  j  a  v  a  2 s.  co  m
        if (CONFIG.getContent().getFileVersions() == null) {
            LOGGER.log(Level.INFO, "Not using files version control.");
            return;
        }

        String automaticVersion = getAutomaticResourceVersion(config);
        if (automaticVersion != null) {
            LOGGER.log(Level.INFO, "Automatic versioning detected as " + automaticVersion);
        }

        ServletContext context = config.getServletContext();
        File rootFile = new File(context.getRealPath(ROOT_PATH));
        Dir content = Vfs.fromURL(rootFile.toURI().toURL());

        Map<String, StringBuilder> patternBuilders = new HashMap<>();
        Iterator<Vfs.File> files = content.getFiles().iterator();

        while (files.hasNext()) {
            Vfs.File file = files.next();
            String relativePath = file.getRelativePath();

            FileVersion fileVersion = CONFIG.getContent().getFileVersion(relativePath);
            if (fileVersion != null && !fileVersion.isOnExcludeFolders(relativePath)) {
                if (!fileVersion.isIncludeMinified() && fileVersion.isMinifiedFile(relativePath)) {
                    continue;
                }

                String patternVersion = automaticVersion;
                if (!fileVersion.isAuto()) {
                    patternVersion = fileVersion.getVersion();
                }
                if (patternVersion == null) {
                    continue;
                }

                StringBuilder patternBuilder = patternBuilders.get(patternVersion);
                if (patternBuilder == null) {
                    patternBuilder = new StringBuilder("(");
                    patternBuilders.put(patternVersion, patternBuilder);
                }
                if (patternBuilder.length() > 1) {
                    patternBuilder.append("|");
                }
                patternBuilder.append(relativePath.replace(".", "\\."));
            }
        }

        for (String version : patternBuilders.keySet()) {
            StringBuilder patternBuilder = patternBuilders.get(version).append(")");
            versionFilePatterns.put(version, Pattern.compile(patternBuilder.toString(), Pattern.DOTALL));
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage());
    }
}

From source file:uk.ac.cam.ucs.webauth.RavenFilter.java

@Override
public void init(FilterConfig config) throws ServletException {
    // check if a different authenticate page is configured.
    // eg https://demo.raven.cam.ac.uk/auth/authenticate.html
    String authenticatePage = config.getInitParameter(INIT_PARAM_AUTHENTICATE_URL);
    if (authenticatePage != null)
        sRavenAuthenticatePage = authenticatePage;

    // get the path to the raven certificate or use a default
    String sCertContextPath = config.getInitParameter(INIT_PARAM_CERTIFICATE_PATH);
    if (sCertContextPath == null)
        sCertContextPath = DEFAULT_CERTIFICATE_PATH;
    // calculate real path from web app relative version
    sCertRealPath = config.getServletContext().getRealPath(sCertContextPath);
    log.debug("Certificate will be loaded from: " + sCertRealPath);

    // ensure KeyStore is initialised.
    keyStore = getKeyStore();//w  ww  . j a  v a 2  s .  co m

    // ensure WebauthValidator is initialised.
    webauthValidator = getWebauthValidator();

    String sTestingMode = config.getServletContext().getInitParameter(CONTEXT_PARAM_TESTING_MODE);
    log.debug("Testing mode: " + sTestingMode);
    testingMode = "true".equals(sTestingMode);

    serverURLPrefix = config.getServletContext().getInitParameter(CONTEXT_PARAM_URL_PREFIX);
    log.debug("Server url prefix: " + serverURLPrefix);

    String sAllowedPrincipals = config.getInitParameter(INIT_PARAM_ALLOWED_PRINCIPALS);
    if (sAllowedPrincipals != null) {
        allowedPrincipals = new HashSet<String>(Arrays.asList(sAllowedPrincipals.split(",")));
        log.debug("Restricting access to " + sAllowedPrincipals);
    } else {
        log.debug("Granting access to all principals");
    }

}

From source file:com.sfwl.framework.web.casclient.AuthenticationFilter.java

protected void initInternal(final FilterConfig filterConfig) throws ServletException {
    if (!isIgnoreInitConfiguration()) {
        super.initInternal(filterConfig);
        setCasServerLoginUrl(getPropertyFromInitParams(filterConfig, "casServerLoginUrl", null));
        logger.trace("Loaded CasServerLoginUrl parameter: {}", 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 ignorePattern = getPropertyFromInitParams(filterConfig, "ignorePattern", null);
        logger.trace("Loaded ignorePattern parameter: {}", ignorePattern);

        final String ignoreUrlPatternType = getPropertyFromInitParams(filterConfig, "ignoreUrlPatternType",
                "REGEX");
        logger.trace("Loaded ignoreUrlPatternType parameter: {}", ignoreUrlPatternType);

        // URL//from www .  j a v  a2 s  .  c  o  m
        String casExcepUrlRegex = filterConfig.getServletContext().getInitParameter("casExcepUrlRegex");
        if (StringUtils.isNotBlank(casExcepUrlRegex)) {
            excepUrlPattern = Pattern.compile(casExcepUrlRegex);
        }

        if (ignorePattern != null) {
            final Class<? extends UrlPatternMatcherStrategy> ignoreUrlMatcherClass = PATTERN_MATCHER_TYPES
                    .get(ignoreUrlPatternType);
            if (ignoreUrlMatcherClass != null) {
                this.ignoreUrlPatternMatcherStrategyClass = ReflectUtils
                        .newInstance(ignoreUrlMatcherClass.getName());
            } else {
                try {
                    logger.trace("Assuming {} is a qualified class name...", ignoreUrlPatternType);
                    this.ignoreUrlPatternMatcherStrategyClass = ReflectUtils.newInstance(ignoreUrlPatternType);
                } catch (final IllegalArgumentException e) {
                    logger.error("Could not instantiate class [{}]", ignoreUrlPatternType, e);
                }
            }
            if (this.ignoreUrlPatternMatcherStrategyClass != null) {
                this.ignoreUrlPatternMatcherStrategyClass.setPattern(ignorePattern);
            }
        }

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

        if (gatewayStorageClass != null) {
            this.gatewayStorage = ReflectUtils.newInstance(gatewayStorageClass);
        }

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

        if (authenticationRedirectStrategyClass != null) {
            this.authenticationRedirectStrategy = ReflectUtils.newInstance(authenticationRedirectStrategyClass);
        }
    }
}

From source file:com.corejsf.UploadFilter.java

public void init(FilterConfig config) throws ServletException {
    repositoryPath = ServerConfigurationService.getString("samigo.answerUploadRepositoryPath",
            "${sakai.home}/samigo/answerUploadRepositoryPath/");

    try {//from w  w w . j a v a  2 s.com
        String paramValue = ServerConfigurationService.getString("samigo.sizeThreshold", "1024");
        if (paramValue != null)
            sizeThreshold = Integer.parseInt(paramValue);

        paramValue = ServerConfigurationService.getString("samigo.sizeMax", "40960");
        if (paramValue != null)
            sizeMax = Long.parseLong(paramValue);

        paramValue = ServerConfigurationService.getString("samigo.saveMediaToDb", "true");
        if (paramValue != null)
            saveMediaToDb = paramValue;

        //System.out.println("**** repositoryPath="+repositoryPath);
        //System.out.println("**** sabeMediaToDb="+saveMediaToDb);
        //System.out.println("**** sizeThreshold="+sizeThreshold);
        //System.out.println("**** sizeMax="+sizeMax);
    } catch (NumberFormatException ex) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw servletEx;
    }
    ServletContext context = config.getServletContext();
    context.setAttribute("FILEUPLOAD_REPOSITORY_PATH", repositoryPath);
    context.setAttribute("FILEUPLOAD_SIZE_THRESHOLD", Integer.valueOf(sizeThreshold));
    context.setAttribute("FILEUPLOAD_SIZE_MAX", Long.valueOf(sizeMax));
    context.setAttribute("FILEUPLOAD_SAVE_MEDIA_TO_DB", saveMediaToDb);
}