Prepare a trace header to be inserted into response
    based on original header and the request segment.
437465
def prepare_response_header(origin_header, segment):
    
    if origin_header and origin_header.sampled == '?':
        new_header = TraceHeader(root=segment.trace_id,
                                 sampled=segment.sampled)
    else:
        new_header = TraceHeader(root=segment.trace_id)

    return new_header.to_header_str()
1106053
def _initialize_context(self, trace_header):
        
        sampled = None
        if not global_sdk_config.sdk_enabled():
            # Force subsequent subsegments to be disabled and turned into DummySegments.
            sampled = False
        elif trace_header.sampled == 0:
            sampled = False
        elif trace_header.sampled == 1:
            sampled = True

        segment = FacadeSegment(
            name='facade',
            traceid=trace_header.root,
            entityid=trace_header.parent,
            sampled=sampled,
        )
        setattr(self._local, 'segment', segment)
        setattr(self._local, 'entities', [])
536001
protected function parseTracedReponseInformation()
    {
        // nothing to set if we weren't tracing
        if ( ! isset($this->clientOptions['trace']) || $this->clientOptions['trace'] !== true) {
            return;
        }

        $responseHeaderString = $this->client->__getLastResponseHeaders();

        $this->responseInformation->setStatusCode(
            $this->parseResponseHeaderForStatusCode($responseHeaderString)
        );

        $this->responseInformation->setHeaders(
            $this->parseResponseHeadersAsArray($responseHeaderString)
        );
    }
576304
def request(self, method, uri, headers=None, bodyProducer=None):
        
        if self._parent_trace is None:
            trace = Trace(method)
        else:
            trace = self._parent_trace.child(method)

        if self._endpoint is not None:
            trace.set_endpoint(self._endpoint)

        if headers is None:
            headers = Headers({})

        # These headers are based on the headers used by finagle's tracing
        # http Codec.
        #
        # https://github.com/twitter/finagle/blob/master/finagle-http/
        #
        # Currently not implemented are X-B3-Sampled and X-B3-Flags
        # Tryfer's underlying Trace implementation has no notion of a Sampled
        # trace and I haven't figured out what flags are for.
        headers.setRawHeaders('X-B3-TraceId', [hex_str(trace.trace_id)])
        headers.setRawHeaders('X-B3-SpanId', [hex_str(trace.span_id)])

        if trace.parent_span_id is not None:
            headers.setRawHeaders('X-B3-ParentSpanId',
                                  [hex_str(trace.parent_span_id)])

        # Similar to the headers above we use the annotation 'http.uri' for
        # because that is the standard set forth in the finagle http Codec.
        trace.record(Annotation.string('http.uri', uri))
        trace.record(Annotation.client_send())

        def _finished(resp):
            # TODO: It may be advantageous here to return a wrapped response
            # whose deliverBody can wrap it's protocol and record when the
            # application has finished reading the contents.
            trace.record(Annotation.string(
                'http.responsecode',
                '{0} {1}'.format(resp.code, resp.phrase)))
            trace.record(Annotation.client_recv())
            return resp

        d = self._agent.request(method, uri, headers, bodyProducer)
        d.addBoth(_finished)

        return d
308315
private void addResponseHeaderParameters(InternalRequest request, ResponseHeaderOverrides responseHeaders) {
        if (responseHeaders != null) {
            if (responseHeaders.getCacheControl() != null) {
                request.addParameter(ResponseHeaderOverrides.RESPONSE_HEADER_CACHE_CONTROL,
                        responseHeaders.getCacheControl());
            }
            if (responseHeaders.getContentDisposition() != null) {
                request.addParameter(ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_DISPOSITION,
                        responseHeaders.getContentDisposition());
            }
            if (responseHeaders.getContentEncoding() != null) {
                request.addParameter(ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_ENCODING,
                        responseHeaders.getContentEncoding());
            }
            if (responseHeaders.getContentLanguage() != null) {
                request.addParameter(ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_LANGUAGE,
                        responseHeaders.getContentLanguage());
            }
            if (responseHeaders.getContentType() != null) {
                request.addParameter(ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_TYPE,
                        responseHeaders.getContentType());
            }
            if (responseHeaders.getExpires() != null) {
                request.addParameter(ResponseHeaderOverrides.RESPONSE_HEADER_EXPIRES, responseHeaders.getExpires());
            }
        }
    }
728681
public void writeHeaders(HttpResponse response,Resource resource, long count)
        throws IOException
    {
        ResourceCache.ResourceMetaData metaData =
            (ResourceCache.ResourceMetaData)resource.getAssociate();

        response.setContentType(metaData.getMimeType());
        if (count != -1)
        {
            if (count==resource.length())
                response.setField(HttpFields.__ContentLength,metaData.getLength());
            else
                response.setContentLength((int)count);
        }

        response.setField(HttpFields.__LastModified,metaData.getLastModified());
        
        if (_acceptRanges && response.getHttpRequest().getDotVersion()>0)
            response.setField(HttpFields.__AcceptRanges,"bytes");
    }
1193354
protected void doResponseHeaders(final HttpServletResponse response, final String mimeType) {
        if (mimeType != null) {
            response.setContentType(mimeType);
        }
    }
829019
def _format_response(self, request, response):
        

        res = datamapper.format(request, response, self)
        # data is now formatted, let's check if the status_code is set
        if res.status_code is 0:
            res.status_code = 200
        # apply headers
        self._add_resposne_headers(res, response)
        return res
844399
def set_response_headers(self, request, total_count):
        '''
        
        '''
        response = request.response
        response.headerlist.append(('Access-Control-Expose-Headers', 'Content-Range, X-Content-Range'))
        response.accept_ranges = 'items'
        if total_count is None:
            raise RangeParseException('Provided length value is null')
        if total_count > 0:
            response.content_range = self.content_range(total_count)

        self.set_link_headers(request, total_count)
172503
def rebuild_method(self, prepared_request, response):
        
        method = prepared_request.method

        # http://tools.ietf.org/html/rfc7231#section-6.4.4
        if response.status_code == codes.see_other and method != 'HEAD':
            method = 'GET'

        # Do what the browsers do, despite standards...
        # First, turn 302s into GETs.
        if response.status_code == codes.found and method != 'HEAD':
            method = 'GET'

        # Second, if a POST is responded to with a 301, turn it into a GET.
        # This bizarre behaviour is explained in Issue 1704.
        if response.status_code == codes.moved and method == 'POST':
            method = 'GET'

        prepared_request.method = method
925904
def _make_req(self, method, url, methname, headers=None):
        """"""

        # Build up headers
        hset = hdrs.HeaderDict()

        # Walk through our global headers
        for hdr, value in self._headers.items():
            # If it's a callable, call it
            if callable(value):
                value = value(methname)
            else:
                # OK, just stringify it
                value = str(value)

            # If it's meaningful, attach it
            if value:
                hset[hdr] = value

        # Were headers passed in?
        if headers is not None:
            # Update from specified headers
            hset.update(headers)

        # Hook method to instantiate requests
        self._debug("Creating request %s.%s(%r, %r, headers=%r)",
                    self._req_class.__module__, self._req_class.__name__,
                    method, url, hset)
        return self._req_class(method, url, self._client, self._procstack,
                               headers=hset, debug=self._debug)
1003175
def _BuildResponse(self,
                     status,
                     rendered_data,
                     method_name=None,
                     headers=None,
                     content_length=None,
                     token=None,
                     no_audit_log=False):
    """"""

    # To avoid IE content sniffing problems, escape the tags. Otherwise somebody
    # may send a link with malicious payload that will be opened in IE (which
    # does content sniffing and doesn't respect Content-Disposition header) and
    # IE will treat the document as html and executre arbitrary JS that was
    # passed with the payload.
    str_data = json.Dump(
        rendered_data, encoder=JSONEncoderWithRDFPrimitivesSupport)
    # XSSI protection and tags escaping
    rendered_data = ")]}'\n" + str_data.replace("<", r"\u003c").replace(
        ">", r"\u003e")

    response = werkzeug_wrappers.Response(
        rendered_data,
        status=status,
        content_type="application/json; charset=utf-8")
    response.headers[
        "Content-Disposition"] = "attachment; filename=response.json"
    response.headers["X-Content-Type-Options"] = "nosniff"

    if token and token.reason:
      response.headers["X-GRR-Reason"] = utils.SmartStr(token.reason)
    if method_name:
      response.headers["X-API-Method"] = method_name
    if no_audit_log:
      response.headers["X-No-Log"] = "True"

    for key, value in iteritems(headers or {}):
      response.headers[key] = value

    if content_length is not None:
      response.content_length = content_length

    return response
31053
def prepare(self, context):
		
		
		if __debug__:
			log.debug("Preparing request context.", extra=dict(request=id(context)))
		
		# Bridge in WebOb `Request` and `Response` objects.
		# Extensions shouldn't rely on these, using `environ` where possible instead.
		context.request = Request(context.environ)
		context.response = Response(request=context.request)
		
		# Record the initial path representing the point where a front-end web server bridged to us.
		context.environ['web.base'] = context.request.script_name
		
		# Track the remaining (unprocessed) path elements.
		context.request.remainder = context.request.path_info.split('/')
		if context.request.remainder and not context.request.remainder[0]:
			del context.request.remainder[0]
		
		# Track the "breadcrumb list" of dispatch through distinct controllers.
		context.path = Bread()
237227
public static HttpCallContext set(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext)
	{
		final HttpCallContext ctx = new HttpCallContext(generateTraceId(request), request, response, servletContext);

		contexts.set(ctx);

		return ctx;
	}
820297
def prepare(self):
        
        super(RequestHandler, self).prepare()
        if self.request.headers.get('content-type', '').startswith(self.JSON):
            self.request.body = escape.json_decode(self.request.body)
1331442
def _before_request(self):
        
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
            return

        try:
            span_context = self.propagator.from_headers(flask.request.headers)

            tracer = tracer_module.Tracer(
                span_context=span_context,
                sampler=self.sampler,
                exporter=self.exporter,
                propagator=self.propagator)

            span = tracer.start_span()
            span.span_kind = span_module.SpanKind.SERVER
            # Set the span name as the name of the current module name
            span.name = '[{}]{}'.format(
                flask.request.method,
                flask.request.url)
            tracer.add_attribute_to_current_span(
                HTTP_METHOD, flask.request.method)
            tracer.add_attribute_to_current_span(
                HTTP_URL, str(flask.request.url))
            execution_context.set_opencensus_attr(
                'blacklist_hostnames',
                self.blacklist_hostnames)
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
643769
def prepare_request(self, **kwargs):
        

        if self.transport is None:
            self.setup_transport(self.transport_param)
        self.reset()
        self.request_counter = next(REQUEST_COUNTER)
        if kwargs:
            self.setup(**kwargs)
        if self.proxylist.size() and self.config['proxy_auto_change']:
            self.change_proxy()
        self.request_method = self.detect_request_method()
        self.transport.process_config(self)