Apply the policy to the response.
@param response
@param context
@param config
@param chain
486752
protected void doApply(ApiResponse response, IPolicyContext context, C config, IPolicyChain<ApiResponse> chain) {
        chain.doApply(response);
    }
1158282
protected void sendSofaResponse(SofaResponse response, SofaRpcException sofaException) {
        try {
            if (RpcInvokeContext.isBaggageEnable()) {
                BaggageResolver.carryWithResponse(RpcInvokeContext.peekContext(), response);
            }
            asyncContext.sendResponse(response);
        } finally {
            if (EventBus.isEnable(ServerSendEvent.class)) {
                EventBus.post(new ServerSendEvent(request, response, sofaException));
            }
            if (EventBus.isEnable(ServerEndHandleEvent.class)) {
                EventBus.post(new ServerEndHandleEvent());
            }
        }
    }
960144
public synchronized void setResponse(HttpServletResponse response) {

        if (perThreadResponse == null) {
            perThreadResponse = new ThreadLocal<HttpServletResponse>();
        }
        perThreadResponse.set(response);
    }
1258933
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletResponse res = (HttpServletResponse)response;
		HttpServletRequest req = (HttpServletRequest)request;
		
		String et = req.getParameter("e");
		String h = req.getParameter("h");
		
		if(null == et || null == h) {
			badRequest(res);
			LOG.warn("et & h attributes are null; Bad request from IP: " + req.getRemoteAddr());
			return;
		}
			
		String baseUrl = req.getRequestURI();
		String passKey = secureUriMapper.getPassKey(baseUrl);		
		
		String salt = passKey + baseUrl + "?e=" + et;
		String hash = SpringExtensionsUtil.getMD5(salt);		
		if(!hash.trim().equals(h)) {
			badRequest(res);
			LOG.warn("Hash Value doesn't match; Bad request from IP: " + req.getRemoteAddr());
			return;
		}
		
		long expiryTime = Long.parseLong(et);		
		if(expiryTime > 0 && !(new Date().getTime() <= expiryTime)) {
			badRequest(res);
			LOG.warn("Secure Link expried, link accessed from IP: " + req.getRemoteAddr());
			return;
		}		
		
		/** making chain call for following filters*/
		chain.doFilter(request, response);
	}
341942
public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
	throws IOException, ServletException
    {
        String path=((HttpServletRequest)request).getServletPath();
        if (welcome!=null && path.endsWith("/"))
            request.getRequestDispatcher(path+welcome).forward(request,response);
        else
            chain.doFilter(request, response);
    }
115735
@Override
    public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain chain) throws IOException, ServletException {
        if (ProcessingPosition.PRE == this.processingPosition || ProcessingPosition.BOTH == this.processingPosition) {
            this.doProcessing(servletRequest);
        }

        chain.doFilter(servletRequest, servletResponse);

        if (ProcessingPosition.POST == this.processingPosition || ProcessingPosition.BOTH == this.processingPosition) {
            this.doProcessing(servletRequest);
        }
    }
408546
protected void sendAuthFailure(IPolicyContext context, IPolicyChain<?> chain, BasicAuthenticationConfig config, int reason) {
        IPolicyFailureFactoryComponent pff = context.getComponent(IPolicyFailureFactoryComponent.class);
        PolicyFailure failure = pff.createFailure(PolicyFailureType.Authentication, reason, Messages.i18n.format("BasicAuthenticationPolicy.AuthenticationFailed")); //$NON-NLS-1$
        String realm = config.getRealm();
        if (realm == null || realm.trim().isEmpty()) {
            realm = "Apiman"; //$NON-NLS-1$
        }
        failure.getHeaders().put("WWW-Authenticate", String.format("Basic realm=\"%1$s\"", realm)); //$NON-NLS-1$ //$NON-NLS-2$
        chain.doFailure(failure);
    }
47296
public void setResponse(String response) {
		this.response = response;
		try {
			this.responseLength = response.getBytes("UTF-8").length;
		} catch (UnsupportedEncodingException e) {
			this.responseLength = response.length();
		}
	}
617212
@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String authToken = getAuthTokenFromRequest(httpRequest);
        String userName = TokenUtils.getUserNameFromToken(authToken);

        if (userName != null) {
            UserDetails userDetails = userService.loadUserByUsername(userName);

            if (TokenUtils.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        chain.doFilter(request, response);
    }
822771
@Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException,
            ServletException {
        // if a response has already been committed, bypass this filter...
        if (response.isCommitted()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Response has already been committed. Bypassing PEP.");
            }
            // continuing the chain once auth has failed causes errors. Short
            // circuiting the path here.
            // remove this if it causes problems
            // chain.doFilter(request, response);
            return;
        }

        // Need to make sure we are dealing with HttpServlets
        if (!(request instanceof HttpServletRequest)
                || !(response instanceof HttpServletResponse)) {
            logger.error("Servlets are not HttpServlets!");
            throw new ServletException("Servlets are not HttpServlets!");
        }

        ServletOutputStream out = null;
        ParameterRequestWrapper req = null;
        HttpServletResponse res = (HttpServletResponse)response;

        // the request and response context
        RequestCtx reqCtx = null;
        ResponseCtx resCtx = null;

        String uri = ((HttpServletRequest) request).getRequestURI();
        String servletPath = ((HttpServletRequest) request).getServletPath();
        if (logger.isDebugEnabled()) {
            logger.debug("Incoming URI: {}", uri);
            logger.debug("Incoming servletPath: {}", servletPath);
        }

        // Fix-up for direct web.xml servlet mappings for:
        // /objects/nextPID and /objects/nextPID.xml
        // (so servlet path will be different in these cases)
        // FIXME: we don't support .xml any more? but included as the servlet mapping is still specified
        if (uri.endsWith("/nextPID") || uri.endsWith("/nextPID.xml")) {
            servletPath = "/objects";
        }


        // get the filter (or null if no filter)
        RESTFilter filter = m_filters.get(servletPath);

        if (filter != null && logger.isDebugEnabled())
            logger.debug("obtaining filter: {}", filter.getClass().getName());

        if(ObjectsFilter.class.isInstance(filter)) { // go find the ObjectHandler
            HttpServletRequest httpRequest = (HttpServletRequest)request;
      	  filter = this.m_objectsRESTFilterMatcher.getObjectsHandler(httpRequest);
      	  if (filter == null) {
            logger.error("No FeSL REST objects handler found for \"{}\"", httpRequest.getPathInfo());
            throw new ServletException(new PEPException("No FeSL REST objects handler found for " + servletPath));
      	  }
        }
        try {
            // handle the request if we have a filter
            if (filter != null) {
                // substitute our own request object that manages parameters
                try {
                    req = new ParameterRequestWrapper((HttpServletRequest) request);
                } catch (Exception e) {
                    throw new PEPException(e);
                }

                logger.debug("Filtering URI: [{}] with: [{}]" , req.getRequestURI(), filter.getClass().getName());

                if(ResponseHandlingRESTFilter.class.isInstance(filter)) {
               	    // substitute our own response object that captures the data
               	    res = new DataResponseWrapper(((HttpServletResponse) response));
                    // get a handle for the original OutputStream
                    out = response.getOutputStream();
                    logger.debug("Filtering will include post-processing the response");
                }

                reqCtx = filter.handleRequest(req, res);
                if (reqCtx != null) {
                    resCtx = m_ctxHandler.evaluate(reqCtx);
                    enforce(resCtx);
                }

                // pass the request along to the next chain...
                chain.doFilter(req, res);
            } else {
                // there must always be a filter, even if it is a NOOP
                logger.error("No FeSL REST filter found for \"{}\"", servletPath);
                throw new PEPException("No FeSL REST filter found for " + servletPath);
            }

            if(ResponseHandlingRESTFilter.class.isInstance(filter)) {
            	// handle the response if we have a non-null response handling filter
            	reqCtx = ((ResponseHandlingRESTFilter)filter).handleResponse(req, res);
            	if (reqCtx != null) {
            		resCtx = m_ctxHandler.evaluate(reqCtx);
            		enforce(resCtx);
            	}

            	out.write(((DataResponseWrapper)res).getData());
            	out.flush();
            	out.close();
            }
        } catch (AuthzDeniedException ae) {
            if (!res.isCommitted()
                    && (req.getRemoteUser() == null || req
                            .getRemoteUser().trim().isEmpty())) {
                loginForm(res);
            } else {
                denyAccess((HttpServletResponse) response, ae.getMessage());
            }
        } catch (PEPException pe) {
            throw new ServletException("Error evaluating request", pe);
        }
    }
656759
private Chain<ApiResponse> createResponseChain(IAsyncHandler<ApiResponse> responseHandler) {
        ResponseChain chain = new ResponseChain(policyImpls, context);
        chain.headHandler(responseHandler);
        chain.policyFailureHandler(result -> {
            if (apiConnectionResponse != null) {
            apiConnectionResponse.abort();
            }
            policyFailureHandler.handle(result);
        });
        chain.policyErrorHandler(result -> {
            if (apiConnectionResponse != null) {
            apiConnectionResponse.abort();
            }
            policyErrorHandler.handle(result);
        });
        return chain;
    }
1365351
public void setChaincodeEndorsementPolicy(LifecycleChaincodeEndorsementPolicy chaincodeEndorsementPolicy) throws InvalidArgumentException {
        if (null == chaincodeEndorsementPolicy) {
            throw new InvalidArgumentException(" The parameter chaincodeEndorsementPolicy may not be null.");
        }
        validationParameter = chaincodeEndorsementPolicy.getByteString();
    }
711309
@Override public Response intercept(Chain chain) throws IOException {
    final Request request = chain.request();

    final Request.Builder builder = request.newBuilder()
        .addHeader(HEADER_NAME, contentType);

    if (request.body() != null) {
      rewriteBodyWithCustomContentType(request, builder);
    }

    final Request contentTypeRequest = builder.build();
    return chain.proceed(contentTypeRequest);
  }
1065878
protected void handleConfigureResponse(MemberState member, ConfigureRequest request, ConfigureResponse response) {
    if (response.status() == Response.Status.OK) {
      handleConfigureResponseOk(member, request, response);
    } else {
      handleConfigureResponseError(member, request, response);
    }
  }
290879
private void setCorsResponseHeaders(ServiceRequestContext ctx, HttpRequest req,
                                        HttpHeaders headers) {
        final CorsPolicy policy = setCorsOrigin(ctx, req, headers);
        if (policy != null) {
            policy.setCorsAllowCredentials(headers);
            policy.setCorsAllowHeaders(headers);
            policy.setCorsExposeHeaders(headers);
        }
    }
855345
@Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        ServletRequest req = getRequest(request);

        ServletResponse resp = getResponse(request, response);

        request.setAttribute(PROCESSED_ATTR, Boolean.TRUE);

        chain.doFilter(req, resp);

        if (resp instanceof CompressedHttpServletResponseWrapper) {

            CompressedHttpServletResponseWrapper compressedResponseWrapper = (CompressedHttpServletResponseWrapper) resp;

            try {

                compressedResponseWrapper.close();  //so that stream is finished and closed.

            } catch (IOException ex) {

                LOGGER.error("Response was already closed: ", ex.toString());

            }

            if (compressedResponseWrapper.isCompressed()) {

                req.setAttribute(COMPRESSED_ATTR, Boolean.TRUE);

            }

        }

    }
99641
private void setHeaders(HttpServletResponse response) {
        setHeader(response, "Expires", Long.valueOf(System.currentTimeMillis() + cacheTimeoutMs).toString()); 
        setHeader(response, "Cache-Control", "public, must-revalidate, max-age=" + cacheTimeout); // HTTP 1.1.
        setHeader(response, "Pragma", "public"); 
    }