/* (non-Javadoc)
@see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
553500
public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		int localPort = request.getLocalPort();
		if (mode == MODE_ALLOW && !portHit(localPort) ||
				mode == MODE_DENY && portHit(localPort)){
			if (message == null){
				((HttpServletResponse) response).sendError(statusCode, ((HttpServletRequest)request).getRequestURI());
			}else if (message.length() == 0){
				((HttpServletResponse) response).sendError(statusCode);
			}else{
				((HttpServletResponse) response).sendError(statusCode, message);
			}
		}else{
			chain.doFilter(request, response);
		}
	}
902246
protected final void removeFilter(IoFilterChain filterChain, IoFilter filter) {
        if (filterChain.contains(filter)) {
            filterChain.remove(filter);
        }
    }
840526
@Override
	public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
		return chain.filter(exchange) //
				.subscriberContext(Context.of(SERVER_WEB_EXCHANGE, exchange));
	}
1227410
private void addRequestCachingFilter() {
        FilterMapping filterMapping = new FilterMapping();
        filterMapping.setFilterName("request-caching-filter");
        filterMapping.setPathSpec("/*");

        FilterHolder filterHolder = new FilterHolder(new RequestCachingServletFilter());
        filterHolder.setName("request-caching-filter");
        servletHandler.addFilter(filterHolder, filterMapping);
    }
765583
private void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

        request.setAttribute(ARQUILLIAN_MANAGER_ATTRIBUTE, manager);

        boolean isDelegated = delegator.tryDelegateRequest(request, response, filterChain);

        if (!isDelegated) {
            doFilterWarp(request, response, filterChain);
        }
    }
1229096
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			HttpServletRequest hreq = (HttpServletRequest)request;
			if(noAuthn(hreq)) {
				chain.doFilter(request, response);
			} else {
				HttpServletResponse hresp = (HttpServletResponse)response;
				TafResp tresp = httpChecker.validate(hreq, hresp);
				if(tresp.isAuthenticated()==RESP.IS_AUTHENTICATED) {
						CadiWrap cw = new CadiWrap(hreq, tresp, httpChecker.getLur(),getConverter(hreq));
						if(httpChecker.notCadi(cw, hresp)) {
							chain.doFilter(cw,response);
						}
				}						
			}
		} catch (ClassCastException e) {
			throw new ServletException("CadiFilter expects Servlet to be an HTTP Servlet",e);
		}
	}
1109821
private FilterChain getChainForName(int requestType, ServletHolder servletHolder) {
        if (servletHolder == null) {
            throw new IllegalStateException("Named dispatch must be to an explicitly named servlet");
        }
        
        if (_filterChainsCached)
        {
            synchronized(this)
            {
                if (_namedChainCache[requestType].containsKey(servletHolder.getName()))
                    return (FilterChain)_namedChainCache[requestType].get(servletHolder.getName());
            }
        }
        
        // Build list of filters
        Object filters= null;
        
        if (jsr154Filter!=null)
        {
            // Slight hack for Named servlets
            // TODO query JSR how to apply filter to all dispatches
            filters=LazyList.add(filters,jsr154FilterHolder);
        }
        
        // Servlet filters
        if (_servletFilterMap.size() > 0)
        {
            Object o= _servletFilterMap.get(servletHolder.getName());
            for (int i=0; i<LazyList.size(o);i++)
            {
                FilterMapping mapping = (FilterMapping)LazyList.get(o,i);
                if (mapping.appliesTo(null,requestType))
                    filters=LazyList.add(filters,mapping.getHolder());
            }
        }

        FilterChain chain = null;
        if (_filterChainsCached)
        {
            synchronized(this)
            {
                if (LazyList.size(filters) > 0)
                    chain= new CachedChain(filters, servletHolder);
                _namedChainCache[requestType].put(servletHolder.getName(),chain);
            }
        }
        else if (LazyList.size(filters) > 0)
            chain = new Chain(filters, servletHolder);
        
        return chain;   
    }
401219
@Override
	public boolean filter(Object entity) {
		for (Filter filter : filters) {
			if (filter.filter(entity)) {
				return true;
			}
		}

		return false;
	}
1312010
@Override
    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
        ServletRequest request = servletRequest;
        ServletResponse response = servletResponse;
        int id = 0;

        // Generate the identifier if dumping is enabled for request and/or response
        if (LOG_REQUEST.isDebugEnabled() || LOG_RESPONSE.isDebugEnabled()) {
            id = counter.incrementAndGet();
        }

        // Dumping of the request is enabled so build the RequestWrapper and dump the request
        if (LOG_REQUEST.isDebugEnabled()) {
            request = new HttpServletRequestLoggingWrapper((HttpServletRequest) servletRequest, maxDumpSizeInKB);
            dumpRequest((HttpServletRequestLoggingWrapper) request, id);
        }

        if (LOG_RESPONSE.isDebugEnabled()) { // Dumping of the response is enabled so build the wrapper, handle the chain, dump the response, and write it to the outpuStream.
            response = new HttpServletResponseLoggingWrapper((HttpServletResponse) servletResponse, maxDumpSizeInKB);
            filterChain.doFilter(request, response);
            dumpResponse((HttpServletResponseLoggingWrapper) response, id);
        } else {
            // Dumping of the response is not needed so we just handle the chain
            filterChain.doFilter(request, response);
        }
    }
1284478
public void doFilter( ServletRequest request,
                ServletResponse response,
                FilterChain chain ) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        NtlmPasswordAuthentication ntlm;

        if ((ntlm = negotiate( req, resp, false )) == null) {
            return;
        }

        chain.doFilter( new NtlmHttpServletRequest( req, ntlm ), response );
    }
688040
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        RequestContext context = RequestContext.getCurrent();
        if (context == null) {
            context = createRequestContext(request, response);
        }

        List<RequestSecurityProcessor> finalSecurityProcessors = new ArrayList<>(securityProcessors);
        finalSecurityProcessors.add(getLastProcessorInChain(chain));

        Iterator<RequestSecurityProcessor> processorIter = finalSecurityProcessors.iterator();
        RequestSecurityProcessorChain processorChain = new RequestSecurityProcessorChainImpl(processorIter);

        try {
            processorChain.processRequest(context);
        } catch (IOException | ServletException | RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new ServletException(e.getMessage(), e);
        }
    }
1030456
public void setDependencyFilter(ObjectNode filter) {
        if (filter == null) {
            return;
        }
        final JsonNode patterns = filter.get("patterns");
        if (patterns != null && patterns.isArray()) {
            List<String> ids = new ArrayList<>();
            for (JsonNode exclusion : patterns) {
                ids.add(exclusion.asText());
            }
            setDependencyFilter(new ExcludesArtifactFilter(ids));
        }
    }
461897
@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        final ServletRequest r1 = request;
        chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
            @SuppressWarnings("unchecked")
            public void setHeader(String name, String value) {
                ArrayList<String> headersToRemove = new ArrayList<String>();
                
                if (r1.getAttribute("com.groupon.odo.removeHeaders") != null)
                    headersToRemove = (ArrayList<String>) r1.getAttribute("com.groupon.odo.removeHeaders");

                boolean removeHeader = false;
                // need to loop through removeHeaders to make things case insensitive
                for (String headerToRemove : headersToRemove) {
                    if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {
                        removeHeader = true;
                        break;
                    }
                }

                if (! removeHeader) {
                    super.setHeader(name, value);
                }
            }
        });
    }
432608
public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException
    {
        HttpServletRequest  srequest  = (HttpServletRequest)request;
        HttpServletResponse sresponse = (HttpServletResponse)response;
        Request requestWrapper=null;
        Response responseWrapper=null;
        boolean root_filter=false;
        

        // Do we need a root wrapper?
        ThreadState state = state();
        if (_unwrappedDispatchSupported || LazyList.size(_requestAttributeListeners)>0 )
        {
            if (srequest instanceof ServletHttpRequest)
            {
                request=state.rootRequest=requestWrapper=new Request(srequest);
                response=state.rootResponse=responseWrapper=new Response(sresponse);
                root_filter=true;
            }
            else
            {
                requestWrapper=state.rootRequest;
                responseWrapper=state.rootResponse;
            }
        }
        
        // Is this the first time this request has been in this _context?
        boolean first_in_context=root_filter ||
        	requestWrapper!=null && 
        	requestWrapper.getRequest()!=null && requestWrapper.getRequest() instanceof Dispatcher.DispatcherRequest &&
        	((Dispatcher.DispatcherRequest)requestWrapper.getRequest()).crossContext();
        
        if (first_in_context)
        {
            requestInitialized(request);
            
            if (requestWrapper!=null && LazyList.size(_requestAttributeListeners)>0)
                requestWrapper.addContextFilter(this);
        }
        
        // setup dispatch
        boolean dispatch=false;
        if (_unwrappedDispatchSupported && state.dispatchRequest!=null)
        {
            dispatch=true;
            requestWrapper.pushWrapper(state.dispatchRequest);
            responseWrapper.pushWrapper(state.dispatchResponse);
            state.dispatchRequest=null;
            state.dispatchResponse=null;
        }
        
        try
        {
            chain.doFilter(request, response);   
        }
        finally
        {
            if (first_in_context)
            {
                requestDestroyed(request);
                if (requestWrapper!=null && LazyList.size(_requestAttributeListeners)>0)
                    requestWrapper.delContextFilter(this);
            }
            
            if (root_filter)
                state.clear();
            
            if (dispatch)
            {
                requestWrapper.popWrapper();
                responseWrapper.popWrapper();
            }
        }
    }
956969
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException
    {
        try
        {
            // invoke the wrapped filter
            if (_filterState == FILTER_STATE_AVAILABLE)
            {
            	nServicing.incrementAndGet();
            	try
            	{  
            	    if (request.isAsyncSupported()){
            	        //141092
            	        boolean isAsyncSupported = this._filterConfig.isAsyncSupported();
            	        if (!isAsyncSupported){
            	            WebContainerRequestState reqState = WebContainerRequestState.getInstance(true);
            	            if (reqState != null) {
            	                reqState.setAttribute("resourceNotSupportAsync", "filter[ "+ this._filterName +" ]");
            	            }
            	        }
            	        //141092
            	        ServletUtil.unwrapRequest(request).setAsyncSupported(isAsyncSupported);
            	    }
            	    
            	    // LIDB-3598: begin
            	    //_filterInstance.doFilter(request, response, chain);
            	    if(_eventSource != null && _eventSource.hasFilterInvocationListeners()){
            	        FilterInvocationEvent event = getFilterInvocationEvent(request);
            	        _eventSource.onFilterStartDoFilter(event);
            	        _filterInstance.doFilter(request, response, chain);
            	        _eventSource.onFilterFinishDoFilter(event);
            	    }
            	    else{
            	        _filterInstance.doFilter(request, response, chain);
            	    }
            	    // LIDB-3598: end

            	}
            	catch (ServletException se)
            	{
            		throw se;
            	}
            	catch (IOException ioe)    //174668 
                {
                    throw ioe;
                }                          //174668
            	catch (Throwable th)
            	{
            		throw th;
            	}
            	finally
            	{
            		nServicing.decrementAndGet();
            	}
            }
            else
            {
                throw new ServletException(MessageFormat.format("Filter [{0}]: filter is unavailable.", new Object[] {_filterName}));
            }
        }
        catch (ServletException se)
        {
            if(_eventSource != null && _eventSource.hasFilterErrorListeners()){
                FilterErrorEvent errorEvent = getFilterErrorEvent(se);
                _eventSource.onFilterDoFilterError(errorEvent);
            }
            //start 140014
            if(_filterState != FILTER_STATE_DESTROYING && _filterState != FILTER_STATE_DESTROYED)
                com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(se, "com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter", "144", this);
            else if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
                logger.logp(Level.FINE, CLASS_NAME, "doFilter", "Can not invoke filter because application is destroyed", se);
            //end 140014
            throw se;
        }
        catch (RuntimeException re){
            throw re;
        }
        catch (FileNotFoundException fnfe) {
            //same as throwable without traces
            if(_eventSource != null && _eventSource.hasFilterErrorListeners()){
                FilterErrorEvent errorEvent = getFilterErrorEvent(fnfe);
                _eventSource.onFilterDoFilterError(errorEvent);
            }
            throw new ServletException(fnfe);
        }
        catch (IOException ioe){                //174668            
            if((com.ibm.ws.webcontainer.osgi.WebContainer.getServletContainerSpecLevel() >= 31) 
                            && ioe.getMessage()!=null 
                            && ioe.getMessage().contains("SRVE0918E")){
                throw ioe;
            }
            if(_eventSource != null && _eventSource.hasFilterErrorListeners()){
                FilterErrorEvent errorEvent = getFilterErrorEvent(ioe);
                _eventSource.onFilterDoFilterError(errorEvent);
            }
            
            com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(ioe, "com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter", "260", this);
            
            if (com.ibm.ws.webcontainer.osgi.WebContainer.getServletContainerSpecLevel() >= 31 )
            {
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
                    logger.logp(Level.FINE, CLASS_NAME, "doFilter", "rethrow IOE", ioe);
                throw ioe;
            }
            else // to prevent regression for servlet 3.0..same as Throwable() below
            {
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
                    logger.logp(Level.FINE, CLASS_NAME, "doFilter", "wrap IOE with ServletException", ioe );
                throw new ServletException(ioe);
            }
            
        }                               //174668
        catch (Throwable th)
        {
            logger.logp(Level.SEVERE, CLASS_NAME, "service", "uncaught.filter.exception", new Object[] {_filterName, th});
            if(_eventSource != null && _eventSource.hasFilterErrorListeners()){
                FilterErrorEvent errorEvent = getFilterErrorEvent(th);
                _eventSource.onFilterDoFilterError(errorEvent);
            }
            com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(th, "com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter", "149", this);
            throw new ServletException(th);
        }

    }
719288
public void addFilter(String filterName)
    {
        _hasFilters = true;
        //PM93069 Start
        if(!WCCustomProperties.DENY_DUPLICATE_FILTER_IN_CHAIN){
            _filterNames.add(filterName); 
        }
        else { 

            if(! _filterNames.contains(filterName)){ // if unique then add in the chain
                _filterNames.add(filterName);
            }
            else{
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    logger.logp(Level.FINE, CLASS_NAME,"init", "filter already in chain ->"+ filterName);

            }
        }    //PM93069 End
    }
1025691
public void filter(ClientRequestContext request) throws IOException
    {
        if(!request.getHeaders().containsKey("X-Api-Key"))
            request.getHeaders().add("X-Api-Key", this.apikey);
    }