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:io.milton.servlet.SpringMiltonFilter.java

@SuppressWarnings("resource")
protected void initSpringApplicationContext(FilterConfig fc) {

    final WebApplicationContext rootContext = WebApplicationContextUtils
            .getWebApplicationContext(fc.getServletContext());

    StaticApplicationContext parent;//from w  ww  .  ja va 2  s  .  c o  m
    if (rootContext != null) {
        log.info("Found a root spring context, and using it");
        parent = new StaticApplicationContext(rootContext);
    } else {
        log.info("No root spring context");
        parent = new StaticApplicationContext();
    }

    final FilterConfigWrapper configWrapper = new FilterConfigWrapper(fc);
    parent.getBeanFactory().registerSingleton("config", configWrapper);
    parent.getBeanFactory().registerSingleton("servletContext", fc.getServletContext());
    File webRoot = new File(fc.getServletContext().getRealPath("/"));
    parent.getBeanFactory().registerSingleton("webRoot", webRoot);
    log.info("Registered root webapp path in: webroot=" + webRoot.getAbsolutePath());
    parent.refresh();

    final String configClass = fc.getInitParameter("contextConfigClass");
    final String sFiles = fc.getInitParameter("contextConfigLocation");

    ConfigurableApplicationContext ctx = null;
    if (StringUtils.isNotBlank(configClass)) {
        try {
            Class<?> clazz = Class.forName(configClass);
            final AnnotationConfigApplicationContext annotationCtx = new AnnotationConfigApplicationContext();
            annotationCtx.setParent(parent);
            annotationCtx.register(clazz);
            annotationCtx.refresh();
            ctx = annotationCtx;
        } catch (ClassNotFoundException e) {
            ctx = null;
            log.error("Unable to create a child context for Milton", e);
        }
    } else {
        String[] contextFiles;
        if (sFiles != null && sFiles.trim().length() > 0) {
            contextFiles = sFiles.split(" ");
        } else {
            contextFiles = new String[] { "applicationContext.xml" };
        }

        try {
            ctx = new ClassPathXmlApplicationContext(contextFiles, parent);
        } catch (BeansException e) {
            log.error("Unable to create a child context for Milton", e);
        }
    }

    if (ctx == null) {
        log.warn("No child context available, only using parent context");
        context = parent;
    } else {
        context = ctx;
    }

}

From source file:com.someco.servlets.AuthenticationFilter.java

public void init(FilterConfig config) throws ServletException {
    this.context = config.getServletContext();
    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();

    authComponent = (AuthenticationComponent) ctx.getBean("AuthenticationComponent");
    authService = (AuthenticationService) ctx.getBean("AuthenticationService");
    personService = (PersonService) ctx.getBean("personService");

    // Get a list of the available locales
    ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService");
    LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.getConfig("Languages")
            .getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID);

    m_languages = configElement.getLanguages();

    casUserSessionAttributeName = config.getInitParameter(CAS_USER_INIT_PARAM_NAME);
    if (casUserSessionAttributeName == null) {
        logger.error("CAS : Filter init-param named " + CAS_USER_INIT_PARAM_NAME + " not found in web.xml");
        Enumeration enumNames = context.getInitParameterNames();
        while (enumNames.hasMoreElements()) {
            String name = enumNames.nextElement().toString();
            logger.error("init param " + name + ": " + context.getInitParameter(name));
        }//w  w w.  jav a  2s.c o m
        // last resort - hack in the default CAS attribute name. At least it prevents 
        // NPEs later.
        casUserSessionAttributeName = "edu.yale.its.tp.cas.client.filter.user";
    }
}

From source file:org.adventure.CustomCorsFilter.java

@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    // Initialize defaults
    parseAndStore(DEFAULT_ALLOWED_ORIGINS, DEFAULT_ALLOWED_HTTP_METHODS, DEFAULT_ALLOWED_HTTP_HEADERS,
            DEFAULT_EXPOSED_HEADERS, DEFAULT_SUPPORTS_CREDENTIALS, DEFAULT_PREFLIGHT_MAXAGE,
            DEFAULT_DECORATE_REQUEST);/*from w  w  w .ja v a  2  s  .co m*/

    if (filterConfig != null) {
        String configAllowedOrigins = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_ORIGINS);
        String configAllowedHttpMethods = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_METHODS);
        String configAllowedHttpHeaders = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_HEADERS);
        String configExposedHeaders = filterConfig.getInitParameter(PARAM_CORS_EXPOSED_HEADERS);
        String configSupportsCredentials = filterConfig.getInitParameter(PARAM_CORS_SUPPORT_CREDENTIALS);
        String configPreflightMaxAge = filterConfig.getInitParameter(PARAM_CORS_PREFLIGHT_MAXAGE);
        String configDecorateRequest = filterConfig.getInitParameter(PARAM_CORS_REQUEST_DECORATE);

        parseAndStore(configAllowedOrigins, configAllowedHttpMethods, configAllowedHttpHeaders,
                configExposedHeaders, configSupportsCredentials, configPreflightMaxAge, configDecorateRequest);
    }
}

From source file:net.gplatform.sudoor.server.cors.CorsFilter.java

@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    // Initialize defaults
    parseAndStore(DEFAULT_ALLOWED_ORIGINS, DEFAULT_ALLOWED_HTTP_METHODS, DEFAULT_ALLOWED_HTTP_HEADERS,
            DEFAULT_EXPOSED_HEADERS, DEFAULT_SUPPORTS_CREDENTIALS, DEFAULT_PREFLIGHT_MAXAGE,
            DEFAULT_DECORATE_REQUEST);/*from   ww w. j  ava 2s.  c om*/

    if (filterConfig != null) {
        String configAllowedOrigins = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_ORIGINS);
        String configAllowedHttpMethods = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_METHODS);
        String configAllowedHttpHeaders = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_HEADERS);
        String configExposedHeaders = filterConfig.getInitParameter(PARAM_CORS_EXPOSED_HEADERS);
        String configSupportsCredentials = filterConfig.getInitParameter(PARAM_CORS_SUPPORT_CREDENTIALS);
        String configPreflightMaxAge = filterConfig.getInitParameter(PARAM_CORS_PREFLIGHT_MAXAGE);
        String configDecorateRequest = filterConfig.getInitParameter(PARAM_CORS_REQUEST_DECORATE);

        parseAndStore(configAllowedOrigins, configAllowedHttpMethods, configAllowedHttpHeaders,
                configExposedHeaders, configSupportsCredentials, configPreflightMaxAge, configDecorateRequest);
    }

    //Added by Shark to enable init via spring
    parseAndStore(null, null,
            "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,dataserviceversion,maxdataserviceversion",
            null, null, null, null);
}

From source file:io.druid.security.kerberos.KerberosAuthenticator.java

@Override
public Filter getFilter() {
    return new AuthenticationFilter() {
        private Signer mySigner;

        @Override/*from w w w .  j a v a 2s .c o  m*/
        public void init(FilterConfig filterConfig) throws ServletException {
            ClassLoader prevLoader = Thread.currentThread().getContextClassLoader();
            try {
                // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader.
                // In case of druid since the class is actually loaded as an extension and filter init is done in main thread.
                // We need to set the classloader explicitly to extension class loader.
                Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader());
                super.init(filterConfig);
                String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
                configPrefix = (configPrefix != null) ? configPrefix + "." : "";
                Properties config = getConfiguration(configPrefix, filterConfig);
                String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET);
                if (signatureSecret == null) {
                    signatureSecret = Long.toString(new Random().nextLong());
                    log.warn("'signature.secret' configuration not set, using a random value as secret");
                }
                final byte[] secretBytes = StringUtils.toUtf8(signatureSecret);
                SignerSecretProvider signerSecretProvider = new SignerSecretProvider() {
                    @Override
                    public void init(Properties config, ServletContext servletContext, long tokenValidity)
                            throws Exception {

                    }

                    @Override
                    public byte[] getCurrentSecret() {
                        return secretBytes;
                    }

                    @Override
                    public byte[][] getAllSecrets() {
                        return new byte[][] { secretBytes };
                    }
                };
                mySigner = new Signer(signerSecretProvider);
            } finally {
                Thread.currentThread().setContextClassLoader(prevLoader);
            }
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper
        @Override
        protected AuthenticationToken getToken(HttpServletRequest request)
                throws IOException, AuthenticationException {
            AuthenticationToken token = null;
            String tokenStr = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                        tokenStr = cookie.getValue();
                        try {
                            tokenStr = mySigner.verifyAndExtract(tokenStr);
                        } catch (SignerException ex) {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null) {
                token = AuthenticationToken.parse(tokenStr);
                if (!token.getType().equals(getAuthenticationHandler().getType())) {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.isExpired()) {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return token;
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest httpReq = (HttpServletRequest) request;

            // If there's already an auth result, then we have authenticated already, skip this.
            if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) {
                filterChain.doFilter(request, response);
                return;
            }

            if (loginContext == null) {
                initializeKerberosLogin();
            }

            String path = ((HttpServletRequest) request).getRequestURI();
            if (isExcluded(path)) {
                filterChain.doFilter(request, response);
            } else {
                String clientPrincipal = null;
                try {
                    Cookie[] cookies = httpReq.getCookies();
                    if (cookies == null) {
                        clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request);
                    } else {
                        clientPrincipal = null;
                        for (Cookie cookie : cookies) {
                            if ("hadoop.auth".equals(cookie.getName())) {
                                Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue());
                                if (matcher.matches()) {
                                    clientPrincipal = matcher.group(1);
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    clientPrincipal = null;
                }

                if (clientPrincipal != null) {
                    request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                            new AuthenticationResult(clientPrincipal, authorizerName, null));
                }
            }

            doFilterSuper(request, response, filterChain);
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling
        private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            boolean unauthorizedResponse = true;
            int errCode = HttpServletResponse.SC_UNAUTHORIZED;
            AuthenticationException authenticationEx = null;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            boolean isHttps = "https".equals(httpRequest.getScheme());
            try {
                boolean newToken = false;
                AuthenticationToken token;
                try {
                    token = getToken(httpRequest);
                } catch (AuthenticationException ex) {
                    log.warn("AuthenticationToken ignored: " + ex.getMessage());
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token = null;
                }
                if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) {
                    if (token == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest));
                        }
                        token = getAuthenticationHandler().authenticate(httpRequest, httpResponse);
                        if (token != null && token.getExpires() != 0
                                && token != AuthenticationToken.ANONYMOUS) {
                            token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null) {
                        unauthorizedResponse = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest),
                                    token.getUserName());
                        }
                        final AuthenticationToken authToken = token;
                        httpRequest = new HttpServletRequestWrapper(httpRequest) {

                            @Override
                            public String getAuthType() {
                                return authToken.getType();
                            }

                            @Override
                            public String getRemoteUser() {
                                return authToken.getUserName();
                            }

                            @Override
                            public Principal getUserPrincipal() {
                                return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                            }
                        };
                        if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                            String signedToken = mySigner.sign(token.toString());
                            createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), isHttps);
                        }
                        doFilter(filterChain, httpRequest, httpResponse);
                    }
                } else {
                    unauthorizedResponse = false;
                }
            } catch (AuthenticationException ex) {
                // exception from the filter itself is fatal
                errCode = HttpServletResponse.SC_FORBIDDEN;
                authenticationEx = ex;
                if (log.isDebugEnabled()) {
                    log.debug("Authentication exception: " + ex.getMessage(), ex);
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(
                            org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) {
                        errCode = HttpServletResponse.SC_FORBIDDEN;
                    }
                    if (authenticationEx == null) {
                        // Don't send an error response here, unlike the base AuthenticationFilter implementation.
                        // This request did not use Kerberos auth.
                        // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow
                        // other Authenticator implementations to check the request.
                        filterChain.doFilter(request, response);
                    } else {
                        // Do send an error response here, we attempted Kerberos authentication and failed.
                        httpResponse.sendError(errCode, authenticationEx.getMessage());
                    }
                }
            }
        }
    };
}

From source file:org.apache.druid.security.kerberos.KerberosAuthenticator.java

@Override
public Filter getFilter() {
    return new AuthenticationFilter() {
        private Signer mySigner;

        @Override//from w  w w.ja  va 2s  . com
        public void init(FilterConfig filterConfig) throws ServletException {
            ClassLoader prevLoader = Thread.currentThread().getContextClassLoader();
            try {
                // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader.
                // In case of druid since the class is actually loaded as an extension and filter init is done in main thread.
                // We need to set the classloader explicitly to extension class loader.
                Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader());
                super.init(filterConfig);
                String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
                configPrefix = (configPrefix != null) ? configPrefix + "." : "";
                Properties config = getConfiguration(configPrefix, filterConfig);
                String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET);
                if (signatureSecret == null) {
                    signatureSecret = Long.toString(ThreadLocalRandom.current().nextLong());
                    log.warn("'signature.secret' configuration not set, using a random value as secret");
                }
                final byte[] secretBytes = StringUtils.toUtf8(signatureSecret);
                SignerSecretProvider signerSecretProvider = new SignerSecretProvider() {
                    @Override
                    public void init(Properties config, ServletContext servletContext, long tokenValidity) {

                    }

                    @Override
                    public byte[] getCurrentSecret() {
                        return secretBytes;
                    }

                    @Override
                    public byte[][] getAllSecrets() {
                        return new byte[][] { secretBytes };
                    }
                };
                mySigner = new Signer(signerSecretProvider);
            } finally {
                Thread.currentThread().setContextClassLoader(prevLoader);
            }
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper
        @Override
        protected AuthenticationToken getToken(HttpServletRequest request) throws AuthenticationException {
            AuthenticationToken token = null;
            String tokenStr = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                        tokenStr = cookie.getValue();
                        try {
                            tokenStr = mySigner.verifyAndExtract(tokenStr);
                        } catch (SignerException ex) {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null) {
                token = AuthenticationToken.parse(tokenStr);
                if (!token.getType().equals(getAuthenticationHandler().getType())) {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.isExpired()) {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return token;
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest httpReq = (HttpServletRequest) request;

            // If there's already an auth result, then we have authenticated already, skip this.
            if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) {
                filterChain.doFilter(request, response);
                return;
            }

            if (loginContext == null) {
                initializeKerberosLogin();
            }

            String path = ((HttpServletRequest) request).getRequestURI();
            if (isExcluded(path)) {
                filterChain.doFilter(request, response);
            } else {
                String clientPrincipal = null;
                try {
                    Cookie[] cookies = httpReq.getCookies();
                    if (cookies == null) {
                        clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request);
                    } else {
                        clientPrincipal = null;
                        for (Cookie cookie : cookies) {
                            if ("hadoop.auth".equals(cookie.getName())) {
                                Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue());
                                if (matcher.matches()) {
                                    clientPrincipal = matcher.group(1);
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    clientPrincipal = null;
                }

                if (clientPrincipal != null) {
                    request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                            new AuthenticationResult(clientPrincipal, authorizerName, name, null));
                }
            }

            doFilterSuper(request, response, filterChain);
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling
        private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            boolean unauthorizedResponse = true;
            int errCode = HttpServletResponse.SC_UNAUTHORIZED;
            AuthenticationException authenticationEx = null;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            boolean isHttps = "https".equals(httpRequest.getScheme());
            try {
                boolean newToken = false;
                AuthenticationToken token;
                try {
                    token = getToken(httpRequest);
                } catch (AuthenticationException ex) {
                    log.warn("AuthenticationToken ignored: " + ex.getMessage());
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token = null;
                }
                if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) {
                    if (token == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest));
                        }
                        token = getAuthenticationHandler().authenticate(httpRequest, httpResponse);
                        if (token != null && token.getExpires() != 0
                                && token != AuthenticationToken.ANONYMOUS) {
                            token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null) {
                        unauthorizedResponse = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest),
                                    token.getUserName());
                        }
                        final AuthenticationToken authToken = token;
                        httpRequest = new HttpServletRequestWrapper(httpRequest) {

                            @Override
                            public String getAuthType() {
                                return authToken.getType();
                            }

                            @Override
                            public String getRemoteUser() {
                                return authToken.getUserName();
                            }

                            @Override
                            public Principal getUserPrincipal() {
                                return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                            }
                        };
                        if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                            String signedToken = mySigner.sign(token.toString());
                            tokenToAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), !token.isExpired() && token.getExpires() > 0, isHttps);
                            request.setAttribute(SIGNED_TOKEN_ATTRIBUTE,
                                    tokenToCookieString(signedToken, getCookieDomain(), getCookiePath(),
                                            token.getExpires(), !token.isExpired() && token.getExpires() > 0,
                                            isHttps));
                        }
                        // Since this request is validated also set DRUID_AUTHENTICATION_RESULT
                        request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                                new AuthenticationResult(token.getName(), authorizerName, name, null));
                        doFilter(filterChain, httpRequest, httpResponse);
                    }
                } else {
                    unauthorizedResponse = false;
                }
            } catch (AuthenticationException ex) {
                // exception from the filter itself is fatal
                errCode = HttpServletResponse.SC_FORBIDDEN;
                authenticationEx = ex;
                if (log.isDebugEnabled()) {
                    log.debug(ex, "Authentication exception: " + ex.getMessage());
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    tokenToAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, false, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(
                            org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) {
                        errCode = HttpServletResponse.SC_FORBIDDEN;
                    }
                    if (authenticationEx == null) {
                        // Don't send an error response here, unlike the base AuthenticationFilter implementation.
                        // This request did not use Kerberos auth.
                        // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow
                        // other Authenticator implementations to check the request.
                        filterChain.doFilter(request, response);
                    } else {
                        // Do send an error response here, we attempted Kerberos authentication and failed.
                        httpResponse.sendError(errCode, authenticationEx.getMessage());
                    }
                }
            }
        }
    };
}

From source file:com.ark.website.filter.CORSFilter.java

@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    // Initialize defaults
    parseAndStore(DEFAULT_ALLOWED_ORIGINS, DEFAULT_ALLOWED_HTTP_METHODS, DEFAULT_ALLOWED_HTTP_HEADERS,
            DEFAULT_EXPOSED_HEADERS, DEFAULT_SUPPORTS_CREDENTIALS, DEFAULT_PREFLIGHT_MAXAGE,
            DEFAULT_LOGGING_ENABLED, DEFAULT_DECORATE_REQUEST);

    this.filterConfig = filterConfig;
    this.loggingEnabled = false;

    if (filterConfig != null) {
        String configAllowedOrigins = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_ORIGINS);
        String configAllowedHttpMethods = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_METHODS);
        String configAllowedHttpHeaders = filterConfig.getInitParameter(PARAM_CORS_ALLOWED_HEADERS);
        String configExposedHeaders = filterConfig.getInitParameter(PARAM_CORS_EXPOSED_HEADERS);
        String configSupportsCredentials = filterConfig.getInitParameter(PARAM_CORS_SUPPORT_CREDENTIALS);
        String configPreflightMaxAge = filterConfig.getInitParameter(PARAM_CORS_PREFLIGHT_MAXAGE);
        String configLoggingEnabled = filterConfig.getInitParameter(PARAM_CORS_LOGGING_ENABLED);
        String configDecorateRequest = filterConfig.getInitParameter(PARAM_CORS_REQUEST_DECORATE);

        parseAndStore(configAllowedOrigins, configAllowedHttpMethods, configAllowedHttpHeaders,
                configExposedHeaders, configSupportsCredentials, configPreflightMaxAge, configLoggingEnabled,
                configDecorateRequest);//from w w  w. java 2  s  .  co m
    }
}

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

/**
 * Initialisation.//from ww  w . 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.iorga.webappwatcher.RequestLogFilter.java

@SuppressWarnings("unchecked")
@Override//  w w  w  .  jav  a  2 s  . c  o m
public void init(final FilterConfig filterConfig) throws ServletException {
    // Initializing context
    final CpuCriticalUsageWatcher cpuCriticalUsageWatcher = new CpuCriticalUsageWatcher();
    parametersContext.put(CpuCriticalUsageWatcher.class, cpuCriticalUsageWatcher);
    final WriteAllRequestsWatcher writeAllRequestsWatcher = new WriteAllRequestsWatcher();
    parametersContext.put(WriteAllRequestsWatcher.class, writeAllRequestsWatcher);
    final RequestDurationWatcher requestDurationWatcher = new RequestDurationWatcher();
    parametersContext.put(RequestDurationWatcher.class, requestDurationWatcher);
    final RetentionLogWritingWatcher retentionLogWritingWatcher = createRetentionLogWritingWatcher();
    parametersContext.put(RetentionLogWritingWatcher.class, retentionLogWritingWatcher);
    final EventLogManager eventLogManager = EventLogManager.getInstance();
    parametersContext.put(EventLogManager.class, eventLogManager);
    systemEventLogger = new SystemEventLogger();
    parametersContext.put(SystemEventLogger.class, systemEventLogger);
    parametersContext.put(RequestLogFilter.class, this);
    // by default, watch the CPU peaks, the request duration & write all requests to the log
    eventLogManager.setEventLogWatchers(Sets.newHashSet(cpuCriticalUsageWatcher, requestDurationWatcher,
            writeAllRequestsWatcher, retentionLogWritingWatcher));

    // Reading web.xml filterConfig init-params
    for (final String parameterName : (List<String>) Collections.list(filterConfig.getInitParameterNames())) {
        final String value = filterConfig.getInitParameter(parameterName);
        setParameter(parameterName, value);
    }
    // Reading "webappwatcher.properties" parameters
    try {
        final Properties properties = new Properties();
        final InputStream propertiesStream = getClass().getClassLoader()
                .getResourceAsStream("webappwatcher.properties");
        if (propertiesStream != null) {
            properties.load(propertiesStream);
            for (final Entry<Object, Object> property : properties.entrySet()) {
                setParameter((String) property.getKey(), (String) property.getValue());
            }
        }
    } catch (final IOException e) {
        throw new ServletException("Problem while reading webappwatcher.properties file", e);
    }

    startServices();
}