Wrap response, deal with headers and cookies
544572
private RawResponse getResponse(URL url, HttpURLConnection conn, CookieJar cookieJar, String method)
            throws IOException {
        // read result
        int status = conn.getResponseCode();
        String host = url.getHost().toLowerCase();

        String statusLine = null;
        // headers and cookies
        List<Header> headerList = new ArrayList<>();
        List<Cookie> cookies = new ArrayList<>();
        int index = 0;
        while (true) {
            String key = conn.getHeaderFieldKey(index);
            String value = conn.getHeaderField(index);
            if (value == null) {
                break;
            }
            index++;
            //status line
            if (key == null) {
                statusLine = value;
                continue;
            }
            headerList.add(new Header(key, value));
            if (key.equalsIgnoreCase(NAME_SET_COOKIE)) {
                Cookie c = Cookies.parseCookie(value, host, Cookies.calculatePath(url.getPath()));
                if (c != null) {
                    cookies.add(c);
                }
            }
        }
        Headers headers = new Headers(headerList);

        InputStream input;
        try {
            input = conn.getInputStream();
        } catch (IOException e) {
            input = conn.getErrorStream();
        }
        if (input == null) {
            input = InputStreams.empty();
        }

        // update session
        cookieJar.storeCookies(cookies);
        return new RawResponse(method, url.toExternalForm(), status, statusLine == null ? "" : statusLine,
                cookies, headers, input, conn);
    }
116978
def wrapper(self, updateParams=None):
		
		def decorator(f):
			_headers = self._getHeaders(updateParams)
			""" flask decorator to include headers """
			@wraps(f)
			def decorated_function(*args, **kwargs):
				resp = make_response(f(*args, **kwargs))
				self._setRespHeader(resp, _headers)
				resp.has_secure_headers = True
				return resp
			return decorated_function
		return decorator
202665
function parseResponseHeaders (headers) {
  var parsed = {};

  if (headers) {
    headers.split('\n').forEach(function (line) {
      var separatorIndex = line.indexOf(':');
      var key = line.substr(0, separatorIndex).trim().toLowerCase();
      var value = line.substr(separatorIndex + 1).trim().toLowerCase();

      if (key) {
        parsed[key] = value;
      }
    });
  }

  return parsed;
}
709066
def _wrap_result(self, response):
        
        if isinstance(response, int):
            response = self._wrap_response(response)

        return HandlerResult(
            status=HandlerStatus.RETURN,
            message_out=self._response_proto(**response),
            message_type=self._response_type)
447148
function fullResponse() {
    function restifyResponseHeaders(req, res, next) {
        res.once('header', function () {

            // Restify 1.0 compatibility
            if (res.defaultResponseFormatters) {
                res.defaultResponseFormatters(res._data);
            }

            res.emit('beforeSend', res._data, res._body);

            // end backwards-compatibility
            return (setHeaders(req, res));
        });

        return (next());
    }

    return (restifyResponseHeaders);
}
930612
function mockResponseHeaders (req, res, next) {
  if (res.swagger) {
    util.debug("Setting %d response headers...", _.keys(res.swagger.headers).length);

    if (res.swagger.headers) {
      _.forEach(res.swagger.headers, (header, name) => {
        // Set all HTTP headers that are defined in the Swagger API.
        // If a default value is specified in the Swagger API, then use it; otherwise generate a value.
        if (res.get(name) !== undefined) {
          util.debug("    %s: %s (already set)", name, res.get(name));
        }
        else if (header.default !== undefined) {
          res.set(name, header.default);
          util.debug("    %s: %s (default)", name, header.default);
        }
        else {
          switch (name.toLowerCase()) {
            case "location":
              res.location(req.baseUrl + (res.swagger.location || req.path));
              break;
            case "last-modified":
              res.set(name, util.rfc1123(res.swagger.lastModified));
              break;
            case "content-disposition":
              res.set(name, 'attachment; filename="' + path.basename(res.swagger.location || req.path) + '"');
              break;
            case "set-cookie":
              // Generate a random "swagger" cookie, or re-use it if it already exists
              if (req.cookies.swagger === undefined) {
                res.cookie("swagger", _.uniqueId("random") + _.random(99999999999.9999));
              }
              else {
                res.cookie("swagger", req.cookies.swagger);
              }
              break;
            default:
              // Generate a sample value from the schema
              let sample = new JsonSchema(header).sample();
              if (_.isDate(sample)) {
                res.set(name, util.rfc1123(sample));
              }
              else {
                res.set(name, _(sample).toString());
              }
          }
          util.debug("    %s: %s", name, res.get(name));
        }
      });
    }
  }

  next();
}
497534
def respond(response, headers_or_body = {}, body = nil)
      raise StateError, "not in header state" if @response_state != :headers

      if headers_or_body.is_a? Hash
        headers = headers_or_body
      else
        headers = {}
        body = headers_or_body
      end

      if @keepalive
        headers[CONNECTION] = KEEP_ALIVE
      else
        headers[CONNECTION] = CLOSE
      end

      case response
      when Symbol, Fixnum, Integer
        response = Response.new(response, headers, body)
      when Response
      else raise TypeError, "invalid response: #{response.inspect}"
      end

      if current_request
        current_request.handle_response(response)
      else
        raise RequestError
      end

      # Enable streaming mode
      if response.chunked? and response.body.nil?
        @response_state = :chunked_body
      elsif @keepalive
        reset_request
      else
        @current_request = nil
        @parser.reset
        @request_fsm.transition :closed
      end
    rescue IOError, SystemCallError, RequestError
      # The client disconnected early, or there is no request
      @keepalive = false
      @request_fsm.transition :closed
      @parser.reset
      @current_request = nil
    end
59887
function onResponse(httpCode, headers, body, callback) {
  var resp = {
    _HTTP: {
      status: httpCode
    },
    headers: headers
  };
  var i;
  var pieces;

  if(typeof body === 'string') {
    try {
      //JSON decode
      resp.body = (body.length > 0 && decodeJSON) ? JSON.parse(body) : body;
    }
    catch(e) {
      //failed to decode - likely not JSON
      resp.body = body;
    }
  }

  //will likely only happen in node due to httpOnly cookies
  if(headers['set-cookie']) {
    resp.cookies = {};

    for(i in headers['set-cookie']) {
      if(headers['set-cookie'].hasOwnProperty(i)) {
        pieces = headers['set-cookie'][i].split(';')[0].split('=');
        resp.cookies[pieces[0]] = pieces[1];
        pieces = null;
      }
    }
  }

  if(resp._HTTP.status >= 400) {
    observers._notify('error', resp);
  }

  if(typeof callback === 'function') {
    callback(resp, (resp._HTTP.status < 400));
  }
}
877349
function parseCookies(req, res, next) {
		var self = this;
		var cookieHeader = req.headers.cookie;

		if (cookieHeader) {
			req.cookies = cookie.parse(cookieHeader);
		} else {
			req.cookies = {};
		}

		/**
		 * Add a cookie to our response.  Uses a Set-Cookie header
		 * per cookie added.
		 * 
		 * @param {String} key  - Cookie name
		 * @param {String} val  - Cookie value
		 * @param {[type]} opts - Options object can contain path, secure, 
		 *     expires, domain, http
		 */
		res.setCookie = function setCookie(key, val, opts) {
			var HEADER = "Set-Cookie";

			if (res.header(HEADER)) {
				var curCookies = res.header(HEADER);

				if (!(curCookies instanceof Array)) {
					curCookies = [curCookies];
				}

				curCookies.push(cookie.serialize(key, val, opts));

				res.setHeader(HEADER, curCookies);

			} else {

				res.setHeader(HEADER, cookie.serialize(key, val, opts));

			}
		};

		res.clearCookie = function clearCookie (key, opts) {
			var options = merge({
				expires: new Date(1)
			}, opts);

			res.setCookie(key, '', options)
		}

		next();

	}
546248
def allow_cors(func):
    """"""
    def wrapper(*args, **kwargs):
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = \
            'PUT, GET, POST, DELETE, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = \
            'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
        return func(*args, **kwargs)
    return wrapper
1162597
def _parse_regr_response(self, response, uri=None, new_authzr_uri=None,
                             terms_of_service=None):
        
        links = _parse_header_links(response)
        if u'terms-of-service' in links:
            terms_of_service = links[u'terms-of-service'][u'url']
        if u'next' in links:
            new_authzr_uri = links[u'next'][u'url']
        if new_authzr_uri is None:
            raise errors.ClientError('"next" link missing')
        return (
            response.json()
            .addCallback(
                lambda body:
                messages.RegistrationResource(
                    body=messages.Registration.from_json(body),
                    uri=self._maybe_location(response, uri=uri),
                    new_authzr_uri=new_authzr_uri,
                    terms_of_service=terms_of_service))
            )
1144322
def process_response(self, request, response):
        
        if getattr(settings, 'FORCE_VARY_ON_HOST', True):
            patch_vary_headers(response, ('Host',))

        return response
590201
def wrap_json_response(func=None, *, encoder=json.JSONEncoder):
    

    if func is None:
        return functools.partial(wrap_json_response, encoder=encoder)

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        response = func(request, *args, **kwargs)

        if "Content-Type" in response.headers and response.headers['Content-Type'] is not None:
            ctype, pdict = parse_header(response.headers.get('Content-Type', ''))
            if ctype == "application/json" and (isinstance(response.body, dict) or isinstance(response.body, list)):
                response.body = json.dumps(response.body, cls=encoder)
        return response

    return wrapper
411348
def parse_response(self, response):
        """"""
        try:
            for header in response.msg.get_all("Set-Cookie"):
                cookie = header.split(";", 1)[0]
                cookieKey, cookieValue = cookie.split("=", 1)
                self._cookies[cookieKey] = cookieValue
        finally:
            return Transport.parse_response(self, response)
1061001
def _parse_request(header_data, ignore_bad_cookies=False):
    
    cookies_dict = {}
    for line in Definitions.EOL.split(header_data.strip()):
        matches = Definitions.COOKIE_RE.finditer(line)
        matches = [item for item in matches]
        for match in matches:
            invalid = match.group('invalid')
            if invalid:
                if not ignore_bad_cookies:
                    raise InvalidCookieError(data=invalid)
                _report_invalid_cookie(invalid)
                continue
            name = match.group('name')
            values = cookies_dict.get(name)
            value = match.group('value').strip('"')
            if values:
                values.append(value)
            else:
                cookies_dict[name] = [value]
        if not matches:
            if not ignore_bad_cookies:
                raise InvalidCookieError(data=line)
            _report_invalid_cookie(line)
    return cookies_dict
959926
def from_request(cls, header_data, ignore_bad_cookies=False):
        ""
        cookies = cls()
        cookies.parse_request(
            header_data, ignore_bad_cookies=ignore_bad_cookies)
        return cookies
245886
def convert_response(response)
      HttpResponse.new(response.status, response.headers, response.body)
    end