Convert an HTTP response to the expected message type.
330284
def ProcessHttpResponse(self, method_config, http_response, request=None):
        """"""
        return self.__client.ProcessResponse(
            method_config,
            self.__ProcessHttpResponse(method_config, http_response, request))
161994
def message(message_type, payload, payload_length):
    
    return packet.build(
        Container(
            type=message_type,
            id=1,
            refer=0,
            sent=Container(
                secs=0,
                usecs=0
            ),
            recv=Container(
                secs=0,
                usecs=0
            ),
            payload_length=payload_length,
            payload=payload
        )
    )
1138378
def convert_response_to_text(response):
    """"""
    # Responses are sent as html. Split on the newlines and give us
    # the <p> text back.
    errorlines = response.text.encode("utf-8").split("\n")
    error = []
    pattern = re.compile(r"<p.*>(.*)</p>")
    for line in errorlines:
        content_line = re.search(pattern, line)
        if content_line:
            error.append(content_line.group(1))

    return ". ".join(error)
1294694
def __ProcessHttpResponse(self, method_config, http_response, request):
        """"""
        if http_response.status_code not in (http_client.OK,
                                             http_client.CREATED,
                                             http_client.NO_CONTENT):
            raise exceptions.HttpError.FromResponse(
                http_response, method_config=method_config, request=request)
        if http_response.status_code == http_client.NO_CONTENT:
            # TODO(craigcitro): Find out why _replace doesn't seem to work
            # here.
            http_response = http_wrapper.Response(
                info=http_response.info, content='{}',
                request_url=http_response.request_url)

        content = http_response.content
        if self._client.response_encoding and isinstance(content, bytes):
            content = content.decode(self._client.response_encoding)

        if self.__client.response_type_model == 'json':
            return content
        response_type = _LoadClass(method_config.response_type_name,
                                   self.__client.MESSAGES_MODULE)
        return self.__client.DeserializeMessage(response_type, content)
1216215
def parse_response(response):
    
    if response.headers.get('Content-Type', JSON_TYPE).startswith(JSON_TYPE):
        return ResponseObject(json.loads(response.body))
    else:
        return response.body
285858
def decode_response(client_message, to_object=None):
    
    parameters = dict(response=None)
    parameters['response'] = client_message.read_long()
    return parameters
1055773
def _map_response(response, decode=False):
    """"""
    # This causes weird deepcopy errors, so it's commented out for now.
    # item._urllib3_response = response
    item = httplib2.Response(response.getheaders())
    item.status = response.status
    item['status'] = str(item.status)
    item.reason = response.reason
    item.version = response.version

    # httplib2 expects the content-encoding header to be stripped and the
    # content length to be the length of the uncompressed content.
    # This does not occur for 'HEAD' requests.
    if decode and item.get('content-encoding') in ['gzip', 'deflate']:
        item['content-length'] = str(len(response.data))
        item['-content-encoding'] = item.pop('content-encoding')

    return item
732756
def raw(request):
    """"""
    foos = foobar_models.Foo.objects.all()
    return HttpResponse(tree.xml(foos), mimetype='text/xml')
903605
private byte[] encode(Message msg, String apiVersion, String kind) {
    // It is unfortunate that we have to include apiVersion and kind,
    // since we should be able to extract it from the Message, but
    // for now at least, those fields are missing from the proto-buffer.
    Unknown u =
        Unknown.newBuilder()
            .setTypeMeta(TypeMeta.newBuilder().setApiVersion(apiVersion).setKind(kind))
            .setRaw(msg.toByteString())
            .build();
    return Bytes.concat(MAGIC, u.toByteArray());
  }
1123053
def prepare_message(self, message_data, delivery_mode,
                        content_type, content_encoding, **kwargs):
        """"""
        return (message_data, content_type, content_encoding)
517748
def _message_to_payload(cls, message):
        ''''''
        try:
            return json.loads(message.decode())
        except UnicodeDecodeError:
            message = 'messages must be encoded in UTF-8'
        except json.JSONDecodeError:
            message = 'invalid JSON'
        raise cls._error(cls.PARSE_ERROR, message, True, None)
676854
def string_to_response(content_type):
    
    def outer_wrapper(req_function):
        @wraps(req_function)
        def newreq(request, *args, **kwargs):
            try:
                outp = req_function(request, *args, **kwargs)
                if issubclass(outp.__class__, HttpResponse):
                    response = outp
                else:
                    response = HttpResponse()
                    response.write(outp)
                    response['Content-Length'] = str(len(response.content))

                response['Content-Type'] = content_type

            except HttpBadRequestException as bad_request:
                response = HttpResponseBadRequest(bad_request.message)

            return response
        return newreq
    return outer_wrapper
249827
def raw(body, status=200, headers=None,
        content_type='application/octet-stream'):
    '''
    
    '''
    return HTTPResponse(body_bytes=body, status=status, headers=headers,
                        content_type=content_type)
1335192
def encode_request(name, expected, updated):
    
    client_message = ClientMessage(payload_size=calculate_size(name, expected, updated))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_long(expected)
    client_message.append_long(updated)
    client_message.update_frame_length()
    return client_message
797320
private static String getResponseMimeType(final HttpResponse httpHeadResponse) {
        Header contentTypeHeader = httpHeadResponse.getFirstHeader("Content-Type");
        if (contentTypeHeader != null) {
            String contentType = contentTypeHeader.getValue();
            if (contentType != null) {
                try {
                    return ContentType.parse(contentType).getMimeType();
                } catch (ParseException | UnsupportedCharsetException exception) {
                    return contentType.split(";")[0].trim();
                }
            }
        }

        return ContentType.DEFAULT_TEXT.getMimeType();
    }
583393
def _parse_response(response, post_request=False):
        
        try:
            data = response.json()
        except:
            msg = 'Unhandled HTTP %s response, shown truncated below:\n%s...' % (
                response.status_code, response.text[:50]
            )
            raise ValueError(msg)

        if not response.ok:
            utils.error_message_and_exit(None, data)

        if post_request and not data['success']:
            raise Exception('Asmaster Api Error: [%s]' % data['error'])

        return data
369485
def create_response(self, request, content, content_type):
        """"""

        return HttpResponse(content=content, content_type=content_type)