适配服务端filter

@param requestContext ContainerRequestContext
510602
public static void serverFilter(ContainerRequestContext requestContext) {
        try {
            SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
            SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();
            if (serverSpan != null) {
                RpcInternalContext context = RpcInternalContext.getContext();

                context.setAttachment(RpcConstants.INTERNAL_KEY_SERVER_RECEIVE_TIME, RpcRuntimeContext.now());

                SofaResourceMethodInvoker resourceMethodInvoker = (SofaResourceMethodInvoker)
                        ((PostMatchContainerRequestContext) requestContext)
                            .getResourceMethod();

                SofaResourceFactory factory = resourceMethodInvoker.getResource();
                String serviceName = factory.getServiceName();
                String appName = factory.getAppName();

                if (serviceName == null) {
                    serviceName = resourceMethodInvoker.getResourceClass().getName();
                }
                serverSpan.setTag(RpcSpanTags.SERVICE, serviceName);
                if (resourceMethodInvoker.getMethod() != null) {
                    serverSpan.setTag(RpcSpanTags.METHOD, resourceMethodInvoker.getMethod().getName());
                    //serverSend需要
                    context.setAttachment(METHOD_TYPE_STRING, resourceMethodInvoker.getMethod());
                }

                serverSpan.setTag(RpcSpanTags.REMOTE_IP, context.getRemoteHostName()); // 客户端地址

                String remoteAppName = requestContext.getHeaderString(RemotingConstants.HEAD_APP_NAME);
                if (StringUtils.isNotBlank(remoteAppName)) {
                    serverSpan.setTag(RpcSpanTags.REMOTE_APP, remoteAppName);
                }
                serverSpan.setTag(RpcSpanTags.PROTOCOL, RpcConstants.PROTOCOL_TYPE_REST);
                serverSpan.setTag(RpcSpanTags.INVOKE_TYPE, RpcConstants.INVOKER_TYPE_SYNC);
                if (appName == null) {
                    appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME);
                }
                serverSpan.setTag(RpcSpanTags.LOCAL_APP, appName);
            }
        } catch (Throwable t) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("the process of rest tracer server filter occur error ", t);
            }
        }
    }
1092521
@InternalApi
  public ReadRowsRequest toProto(RequestContext requestContext) {
    String tableName =
        NameUtil.formatTableName(
            requestContext.getProjectId(), requestContext.getInstanceId(), tableId);

    return builder
        .setTableName(tableName)
        .setAppProfileId(requestContext.getAppProfileId())
        .build();
  }
710261
protected String determineConsentEvent(final RequestContext requestContext) {
        val webService = WebUtils.getService(requestContext);
        val service = this.authenticationRequestServiceSelectionStrategies.resolveService(webService);
        if (service == null) {
            return null;
        }

        val registeredService = getRegisteredServiceForConsent(requestContext, service);

        val authentication = WebUtils.getAuthentication(requestContext);
        if (authentication == null) {
            return null;
        }

        return isConsentRequired(service, registeredService, authentication, requestContext);
    }
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);
		}
	}
874964
@Override
	public void filter(final ClientRequestContext requestContext) {
		if (!backend.isEmpty() && backend.getConfiguration().shouldProcessContext(OutgoingRequest)) {
			final Map<String, String> filtered = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), OutgoingRequest);
			requestContext.getHeaders().putSingle(TraceeConstants.TPIC_HEADER, transportSerialization.render(filtered));
		}
	}
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);
    }
1281324
@Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        RequestContext context = createRequestContext(req, resp);
        String threadName = Thread.currentThread().getName();

        logger.debug(LOG_KEY_BINGING_CONTEXT, req.getRequestURI(), threadName);

        RequestContext.setCurrent(context);

        try {
            chain.doFilter(request, response);
        } finally {
            logger.debug(LOG_KEY_UNBINDING_CONTEXT, req.getRequestURI(), threadName);

            RequestContext.clear();
        }
    }
819171
@Override
    public void visitClassContext(ClassContext classContext) {
        try {
            bloatableCandidates = new HashMap<>();
            bloatableFields = new HashMap<>();
            threadLocalNonStaticFields = new HashSet<>();
            userValues = new HashMap<>();
            jaxbContextRegs = new HashMap<>();
            parseFields(classContext);

            stack = new OpcodeStack();
            super.visitClassContext(classContext);

            reportMemoryBloatBugs();
            reportThreadLocalBugs();

        } finally {
            stack = null;
            bloatableCandidates = null;
            bloatableFields = null;
            userValues = null;
            threadLocalNonStaticFields = null;
            jaxbContextRegs = null;
        }
    }
24744
private function fillGeneralRequestSettings(RequestContext $requestContext): RequestContext
    {
        $requestContext
            ->setContentType(RequestContext::CONTENT_TYPE_FORM_URLENCODED)
            ->setResponseContextClass(JsonResponseContext::class);

        return $requestContext;
    }
646462
@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
                    ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        for (String path : mediaTypes.keySet()) {
            if (matches(httpServletRequest, path)) {
                response.setContentType(mediaTypes.get(path));
                break;
            }
        }
        chain.doFilter(request, response);
    }
1251672
public void createContainerContext(@Observes EventContext<ContainerControlEvent> context) {
        ContainerContext containerContext = this.containerContext.get();
        ContainerControlEvent event = context.getEvent();

        try {
            containerContext.activate(event.getContainerName());
            context.proceed();
        } finally {
            containerContext.deactivate();
        }
    }
36728
public String render(String content, RenderContext context) {
    init();
    FilterContext filterContext = new BaseFilterContext();
    filterContext.setRenderContext(context);
    return fp.filter(content, filterContext);
  }
78388
public static HttpServletRequest getHttpServletRequestFromExternalWebflowContext(final RequestContext context) {
        Assert.isInstanceOf(ServletExternalContext.class, context.getExternalContext(),
            "Cannot obtain HttpServletRequest from event of type: "
                + context.getExternalContext().getClass().getName());

        return (HttpServletRequest) context.getExternalContext().getNativeRequest();
    }
1038104
public static void processAllExitProbeExtensions(Event event, RequestContext requestContext) {

		List<ProbeExtension> probeExtnList = RequestProbeService.getProbeExtensions();
		for (int i = 0; i < probeExtnList.size(); i ++) {
			ProbeExtension probeExtension = probeExtnList.get(i);
			try{
				// Exit enabled??
				if (probeExtension.invokeForEventExit()) {
					// To be sampled ??
					if (requestContext.getRequestId().getSequenceNumber() % probeExtension.getRequestSampleRate() == 0) {
						if (event == requestContext.getRootEvent() && probeExtension.invokeForRootEventsOnly() == true
								&& (probeExtension.invokeForEventTypes() == null || probeExtension.invokeForEventTypes().contains(event.getType()))) {
							probeExtension.processExitEvent(event, requestContext);
						}
						if (probeExtension.invokeForRootEventsOnly() == false
								&& (probeExtension.invokeForEventTypes() == null || probeExtension.invokeForEventTypes().contains(event.getType()))) {
							probeExtension.processExitEvent(event, requestContext);
						}
					}
				}
			}catch(Exception e){
				if(TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()){
					Tr.debug(tc, "----------------Probe extension invocation failure---------------");
					Tr.debug(tc, probeExtension.getClass().getName() + ".processExitEvent failed because of the following reason:" );
					Tr.debug(tc, e.getMessage());
				}
				FFDCFilter.processException(e, RequestProbeService.class.getName() + ".processAllExitProbeExtensions", "185");
			}
		}
		if (event == requestContext.getRootEvent()) {
			// Remove the request from active request list
			try{
				RequestContext storedRequestContext = activeRequests.get(requestContext.getRequestContextIndex());
				// 1) Check to handle stale requests.
				// A long running stale request from the last time the feature was enabled could potentially 
				// end up evicting a valid request that is occupying the same slot in the list.
				// 2) Also check if the returned request context is null, this can happen when we remove the feature while
				// a request is executing as we clean up the active requests list and the slot no longer holds a request context.
				if(storedRequestContext != null && (storedRequestContext.getRequestId() == requestContext.getRequestId()))
					activeRequests.remove(requestContext.getRequestContextIndex());
			}catch(ArrayIndexOutOfBoundsException e){
				//Do nothing as this can fail for an in-flight request when the feature is disabled
				//Rational being, the active request list gets reset and this index can no longer be valid.
			}
		}
	}
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);
        }

    }
741400
@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        // set cache directives
        httpServletResponse.setHeader(HTTPCacheHeader.CACHE_CONTROL.getName(), "no-cache, no-store");
        httpServletResponse.setDateHeader(HTTPCacheHeader.EXPIRES.getName(), 0L);

        filterChain.doFilter(servletRequest, servletResponse);
    }
87724
protected RegisteredService resolveRegisteredServiceInRequestContext(final RequestContext requestContext) {
        val resolvedService = resolveServiceFromAuthenticationRequest(requestContext);
        if (resolvedService != null) {
            val service = getWebflowEventResolutionConfigurationContext().getServicesManager().findServiceBy(resolvedService);
            RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(resolvedService, service);
            return service;
        }
        LOGGER.debug("Authentication request is not accompanied by a service given none is specified");
        return null;
    }