Intercept the outgoing response to perform auditing of the request data if the bundle contains auditable
resources.
161810
@Override
	public boolean outgoingResponse(RequestDetails theRequestDetails, Bundle theResponseObject, HttpServletRequest theServletRequest, HttpServletResponse theServletResponse) throws AuthenticationException {
		if (myClientParamsOptional && myDataStore == null) {
			// auditing is not required or configured, so do nothing here
			log.debug("No auditing configured.");
			return true;
		}
		if (theResponseObject == null || theResponseObject.isEmpty()) {
			log.debug("No bundle to audit");
			return true;
		}
		try {
			log.info("Auditing bundle: " + theResponseObject + " from request " + theRequestDetails);
			SecurityEvent auditEvent = new SecurityEvent();
			auditEvent.setEvent(getEventInfo(theRequestDetails));
			// get user info from request if available
			Participant participant = getParticipant(theServletRequest);
			if (participant == null) {
				log.debug("No participant to audit");
				return true; // no user to audit - throws exception if client params are required
			}
			List<Participant> participants = new ArrayList<SecurityEvent.Participant>(1);
			participants.add(participant);
			auditEvent.setParticipant(participants);

			SecurityEventObjectLifecycleEnum lifecycle = mapResourceTypeToSecurityLifecycle(theRequestDetails.getRestOperationType());
			byte[] query = getQueryFromRequestDetails(theRequestDetails);
			List<ObjectElement> auditableObjects = new ArrayList<SecurityEvent.ObjectElement>();
			for (BundleEntry entry : theResponseObject.getEntries()) {
				IResource resource = entry.getResource();
				ObjectElement auditableObject = getObjectElement(resource, lifecycle, query);
				if (auditableObject != null)
					auditableObjects.add(auditableObject);
			}
			if (auditableObjects.isEmpty()) {
				log.debug("No auditable resources to audit.");
				return true; // no PHI to audit
			} else {
				log.debug("Auditing " + auditableObjects.size() + " resources.");
			}
			auditEvent.setObject(auditableObjects);
			auditEvent.setSource(getSourceElement(theServletRequest));
			store(auditEvent);
			return true; // success
		} catch (Exception e) {
			log.error("Unable to audit resource: " + theResponseObject + " from request: " + theRequestDetails, e);
			throw new InternalErrorException("Auditing failed, unable to complete request", e);
		}
	}
364198
@Override
	public ClientHttpResponse intercept(HttpRequest request, byte[] body,
										ClientHttpRequestExecution execution) throws IOException {
		HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);

		HttpHeaders headers = requestWrapper.getHeaders();
		headers.setBearerAuth(getAccessToken().getTokenValue());

		return execution.execute(requestWrapper, body);
	}
723436
def _check_response_for_request_warnings(self):
        

        if self.response.HighestSeverity in ("NOTE", "WARNING"):
            for notification in self.response.Notifications:
                if notification.Severity in ("NOTE", "WARNING"):
                    self.logger.warning(FedexFailure(notification.Code,
                                                     notification.Message))
1304623
private Process launchBundleAudit(File folder) throws AnalysisException {
        if (!folder.isDirectory()) {
            throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath()));
        }
        final List<String> args = new ArrayList<>();
        final String bundleAuditPath = getSettings().getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH);
        File bundleAudit = null;
        if (bundleAuditPath != null) {
            bundleAudit = new File(bundleAuditPath);
            if (!bundleAudit.isFile()) {
                LOGGER.warn("Supplied `bundleAudit` path is incorrect: {}", bundleAuditPath);
                bundleAudit = null;
            }
        }
        args.add(bundleAudit != null && bundleAudit.isFile() ? bundleAudit.getAbsolutePath() : "bundle-audit");
        args.add("check");
        args.add("--verbose");
        final ProcessBuilder builder = new ProcessBuilder(args);
        builder.directory(folder);
        try {
            LOGGER.info("Launching: {} from {}", args, folder);
            return builder.start();
        } catch (IOException ioe) {
            throw new AnalysisException("bundle-audit initialization failure; this error can be ignored if you are not analyzing Ruby. "
                    + "Otherwise ensure that bundle-audit is installed and the path to bundle audit is correctly specified", ioe);
        }
    }
277509
def handleResponseEnd(self):
        
        try:
            if not self._finished:
                reactor.callInThread(
                    self.resource.cacheContent,
                    self.father,
                    self._response,
                    self.buffer
                )
            proxy.ProxyClient.handleResponseEnd(self)
        except RuntimeError:
            # because we don't care if the user hits
            # refresh before the request is done
            pass
1160947
@Override
    public boolean enableImmediateResponseRead() {
        if (headersSent()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Request hdrs already sent, too late for immediate read");
            }
            return false;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Immediate response read requested: " + getVC());
        }
        this.bImmediateRead = true;
        return true;
    }
871691
protected function _ensureRespondentData()
    {
        if (! isset($this->_respTrackData['grs_id_user'], $this->_respTrackData['gr2o_id_user'], $this->_respTrackData['gco_code'])) {
            $sql = "SELECT *
                FROM gems__respondents INNER JOIN
                    gems__respondent2org ON grs_id_user = gr2o_id_user INNER JOIN
                    gems__consents ON gr2o_consent = gco_description
                WHERE gr2o_id_user = ? AND gr2o_id_organization = ? LIMIT 1";

            $respId = $this->_respTrackData['gr2t_id_user'];
            $orgId  = $this->_respTrackData['gr2t_id_organization'];

            if ($row = $this->db->fetchRow($sql, array($respId, $orgId))) {
                $this->_respTrackData = $this->_respTrackData + $row;
            } else {
                $trackId = $this->_respTrackId;
                throw new \Gems_Exception("Respondent data missing for track $trackId.");
            }
        }
    }
426061
@Override public Response intercept(Chain chain) throws IOException {
    final Request request = chain.request();

    return chain.proceed(request.newBuilder()
        .addHeader(name, value)
        .build());
  }
745718
@SuppressWarnings("unchecked")
	public Response createResponse(ServerTransaction origServerTransaction, Response receivedResponse) throws SipException {

		final SleeSipProviderImpl provider = ra.getProviderWrapper();
		
		Response forgedResponse = null;
		
		try {
			forgedResponse = provider.getMessageFactory().createResponse(receivedResponse.getStatusCode(), origServerTransaction.getRequest());
		} catch (ParseException e) {
			throw new SipException("Failed to forge message", e);
		}
		
		final DialogState dialogState = getState();
		final String localTag = getLocalTag();
		if ((dialogState == null || dialogState == DialogState.EARLY) && localTag != null && isServer()) {
			// no tag set in the response, since the dialog creating transaction didn't had it
			try {
				((ToHeader)forgedResponse.getHeader(ToHeader.NAME)).setTag(localTag);
			} catch (ParseException e) {
				throw new SipException("Failed to set local tag", e);
			}
		}
		
		// copy headers 
		ListIterator<String> lit = receivedResponse.getHeaderNames();
		String headerName = null;
		ListIterator<Header> headersIterator = null;
		while (lit.hasNext()) {
			headerName = lit.next();
			if (Utils.getHeadersToOmmitOnResponseCopy().contains(headerName)) {
				continue;
			} else {
				forgedResponse.removeHeader(headerName);
				headersIterator = receivedResponse.getHeaders(headerName);
				while (headersIterator.hasNext()) {
					forgedResponse.addLast((Header)headersIterator.next().clone());
				}
			}
		}
		
		// Copy content
		final byte[] rawOriginal = receivedResponse.getRawContent();
		if (rawOriginal != null && rawOriginal.length != 0) {
			final byte[] copy = new byte[rawOriginal.length];
			System.arraycopy(rawOriginal, 0, copy, 0, copy.length);
			try {
				forgedResponse.setContent(copy, (ContentTypeHeader) forgedResponse
						.getHeader(ContentTypeHeader.NAME));
			} catch (ParseException e) {
				tracer.severe("Failed to set content on forged response. To copy value [" + new String(copy) + "] Type ["
						+ receivedResponse.getHeader(ContentTypeHeader.NAME) + "]\n", e);
			}
		}
		
		// set contact if the received response had it
		if (receivedResponse.getHeader(ContactHeader.NAME) != null) {
			final String transport = ((ViaHeader) forgedResponse.getHeader(ViaHeader.NAME)).getTransport();
			forgedResponse.setHeader(((ListeningPointImpl)provider.getListeningPoint(transport)).createContactHeader());
		}
		
		return forgedResponse;
		
	}
561019
def process_response(self, request, response, resource, req_succeeded):
        """"""
        self.logger.info(self._generate_combined_log(request, response))
952204
public static void audit(TraceComponent tc, String msgKey, Object objs) {
     SibTr.audit(tc, msgKey, objs);
  }
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);
        }
    }
814032
private void checkResponse(ResponseDTO response) throws Throwable {
        if (response == null) {
            throw new RpcException("Response should not be null");
        }

        if (response.getError() != null) {
            throw response.getError().getCause();
        }
    }
897747
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest xRequest;
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            if (!request.isSecure() && matchesOne(request.getRemoteAddr(), securedRemoteAddresses)) {
                xRequest = new HttpServletRequestWrapper((HttpServletRequest) request) {
                    @Override
                    public boolean isSecure() {
                        return true;
                    }
                };
            } else {
                xRequest = request;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Incoming request uri=" + ((HttpServletRequest) request).getRequestURI() + " with originalSecure='"
                        + request.isSecure() + "', remoteAddr='" + request.getRemoteAddr() + "' will be seen with newSecure='"
                        + xRequest.isSecure() + "'");
            }
        } else {
            xRequest = request;
        }

        chain.doFilter(xRequest, response);
    }
490862
def check_response(self, resp):
        """"""
        if resp.status_code == 400:
            raise ApiException(json.loads(resp.content).get('message'))
        return resp
488315
@Override
    public void onFailure(Response response, Throwable t, JSONObject extendedInfo) {
        if (isAuthorizationRequired(response)) {
            processResponseWrapper(response, true);
        } else {
            listener.onFailure(response, t, extendedInfo);
        }
    }
249061
private void processResponseWrapper(Response response, boolean isFailure) {
        try {
            ResponseImpl responseImpl = (ResponseImpl)response;
            if (isFailure || !responseImpl.isRedirect()) {
                processResponse(response);
            } else {
                processRedirectResponse(response);
            }
        } catch (Throwable t) {
            logger.error("processResponseWrapper caught exception: " + t.getLocalizedMessage());
            listener.onFailure(response, t, null);
        }
    }