Parse JWKS from the HTTP response.

        Should be overriden by subclasses for adding support of e.g. signed
        JWKS.
        :param response: HTTP response from the 'jwks_uri' endpoint
        :return: response parsed as JSON
512966
def _parse_remote_response(self, response):
        
        # Check if the content type is the right one.
        try:
            if response.headers["Content-Type"] != 'application/json':
                logger.warning('Wrong Content_type ({})'.format(
                    response.headers["Content-Type"]))
        except KeyError:
            pass

        logger.debug("Loaded JWKS: %s from %s" % (response.text, self.source))
        try:
            return json.loads(response.text)
        except ValueError:
            return None
1265798
def from_response(response):
        
        # Get the httplib.HTTPResponse object
        http_response = response.raw._original_response
        
        # HTTP status line, headers and body as strings
        status_line = "HTTP/1.1 %d %s" % (http_response.status, http_response.reason)
        headers = str(http_response.msg)
        body = http_response.read()

        # Monkey-patch the response object so that it is possible to read from it later.
        response.raw._fp = StringIO(body)

        # Build the payload to create warc file.
        payload = status_line + "\r\n" + headers + "\r\n" + body
        
        headers = {
            "WARC-Type": "response",
            "WARC-Target-URI": response.request.full_url.encode('utf-8')
        }
        return WARCRecord(payload=payload, headers=headers)
850385
def parse_json(response)
      data = JSON.parse(response)
      fail OptaSD::Error.new(data), ErrorMessage.get_message(data['errorCode'].to_i) if data['errorCode']
      data
    end
903673
def _parse_ocsp_response_from_openssl_text(
            cls,
            response_text: str,
            response_status: OcspResponseStatusEnum
    ) -> Dict[str, Any]:
        
        response_dict = {
            'responseStatus': cls._get_value_from_text_output_no_p('OCSP Response Status:', response_text),
            'version': cls._get_value_from_text_output_no_p('Version:', response_text),
            'responseType': cls._get_value_from_text_output('Response Type:', response_text),
            'responderID': cls._get_value_from_text_output('Responder Id:', response_text),
            'producedAt': cls._get_value_from_text_output('Produced At:', response_text),
            }  # type: Dict[str, Any]

        if response_status != OcspResponseStatusEnum.SUCCESSFUL:
            return response_dict

        # A successful OCSP response will contain more data - let's parse it
        # TODO(ad): This will not work correctly if there are multiple responses as it assumes just one
        response_dict['responses'] = [
            {
                'certID': {
                    'hashAlgorithm': cls._get_value_from_text_output('Hash Algorithm:', response_text),
                    'issuerNameHash': cls._get_value_from_text_output('Issuer Name Hash:', response_text),
                    'issuerKeyHash': cls._get_value_from_text_output('Issuer Key Hash:', response_text),
                    'serialNumber': cls._get_value_from_text_output('Serial Number:', response_text)
                },
                'certStatus': cls._get_value_from_text_output('Cert Status:', response_text),
                'thisUpdate': cls._get_value_from_text_output('This Update:', response_text),
                'nextUpdate': cls._get_value_from_text_output('Next Update:', response_text),
            }
        ]
        if cls._get_scts_from_text_output(response_text):
            # SCT extension present
            response_dict['responses'][0]['singleExtensions'] = {
                'ctCertificateScts': cls._get_scts_from_text_output(response_text)
            }
        return response_dict
1144170
def _parse_response_for_dict(response):
    ''' '''

    if response is None:
        return None
    http_headers = ['server', 'date', 'location', 'host',
                    'via', 'proxy-connection', 'connection']
    return_dict = _HeaderDict()
    if response.headers:
        for name, value in response.headers:
            if not name.lower() in http_headers:
                return_dict[name] = value

    return return_dict
1264309
def parse_response(self, connection, command_name, **options):
        ""
        try:
            response = connection.read_response()
        except ResponseError:
            if EMPTY_RESPONSE in options:
                return options[EMPTY_RESPONSE]
            raise
        if command_name in self.response_callbacks:
            return self.response_callbacks[command_name](response, **options)
        return response
738995
def parse_response(resp):
        
        if resp.status_code in [200, 201, 202]:
            return resp.json()
        elif resp.status_code == 204:
            return None
        elif resp.status_code == 400:
            raise error.BadRequestError(resp.text)
        elif resp.status_code == 401:
            raise error.UnauthorizedError(resp.text)
        elif resp.status_code == 403:
            raise error.ForbiddenError(resp.text)
        elif resp.status_code == 404:
            raise error.NotFoundError(resp.text)
        elif resp.status_code == 429:
            raise error.TooManyRequestsError(resp.text)
        elif resp.status_code == 503:
            raise error.ServiceUnavailableError(resp.text)
        else:
            raise error.OptimizelyError(resp.text)
426165
def parse_image_response(self, response):
        
        if 'xml' in response.headers.get('Content-Type'):
            # Got an XML response, likely an error code.
            xml = xmltodict.parse(response.text)
            self.analyze_reply_code(xml_response_dict=xml)

        multi_parts = self._get_multiparts(response)
        parsed = []
        # go through each part of the multipart message
        for part in multi_parts:
            clean_part = part.strip('\r\n\r\n')
            if '\r\n\r\n' in clean_part:
                header, body = clean_part.split('\r\n\r\n', 1)
            else:
                header = clean_part
                body = None
            part_header_dict = {k.strip(): v.strip() for k, v in (h.split(':', 1) for h in header.split('\r\n'))}

            # Some multipart requests respond with a text/XML part stating an error
            if 'xml' in part_header_dict.get('Content-Type'):
                # Got an XML response, likely an error code.
                # Some rets servers give characters after the closing brace.
                body = body[:body.index('/>') + 2]  if '/>' in body else body
                xml = xmltodict.parse(body)
                try:
                    self.analyze_reply_code(xml_response_dict=xml)
                except RETSException as e:
                    if e.reply_code == '20403':
                        # The requested object_id was not found.
                        continue
                    raise e

            if body:
                obj = self._response_object_from_header(
                    obj_head_dict=part_header_dict,
                    content=body.encode('latin-1') if six.PY3 else body)
            else:
                obj = self._response_object_from_header(obj_head_dict=part_header_dict)
            parsed.append(obj)
        return parsed
10340
def parse_requests_response(response, **kwargs):
    

    return parse_headers(
        response.headers.get('content-disposition'), response.url, **kwargs)
1011772
def parse_response(response)
      if response.headers['Content-Type'] == "application/json"
        JSON.parse(response.body) rescue nil
      else
        response.body
      end
    end
797343
def _parse_authorization(cls, response, uri=None):
        
        links = _parse_header_links(response)
        try:
            new_cert_uri = links[u'next'][u'url']
        except KeyError:
            raise errors.ClientError('"next" link missing')
        return (
            response.json()
            .addCallback(
                lambda body: messages.AuthorizationResource(
                    body=messages.Authorization.from_json(body),
                    uri=cls._maybe_location(response, uri=uri),
                    new_cert_uri=new_cert_uri))
            )
465069
def parse(response):
        """"""
        if response.status_code == 400:
            try:
                msg = json.loads(response.content)['message']
            except (KeyError, ValueError):
                msg = ''
            raise ApiError(msg)
        return response
811802
def _parse_response(self, response):
        

        response_dict = {}
        for line in response.splitlines():
            key, value = response.split("=", 1)
            response_dict[key] = value
        return response_dict
159651
def handle_response (response):
    
    
    response = json.loads(response.read())
    
    # Was the expression valid?
    if 'error' in response:
        raise ValueError(response['error'])
    else:
        # Some of the strings returned can be parsed to integers or floats
        try:
            return json.loads(response['result'])
        except (TypeError, json.decoder.JSONDecodeError):
            # If the result is NaN, return the actual NaN float
            if response['result'] == 'NaN':
                return float('nan')
            else:
                return response['result']
884840
def get_response(self, **kwargs):
        
        return Response(
            json.dumps({"error": self.message}),  # pylint: disable=exception-message-attribute
            status_code=self.status_code,
            content_type="application/json",
            charset="utf-8",
            **kwargs
        )
1000617
def parse_response!
      response.body = case @response_format
        when :xml then Hash.from_xml response.body
        when :json then JSON response.body
      end if response.body
    end
86310
async def parse_result(response, response_type=None, *, encoding="utf-8"):
    
    if response_type is None:
        ct = response.headers.get("content-type")
        if ct is None:
            cl = response.headers.get("content-length")
            if cl is None or cl == "0":
                return ""
            raise TypeError(
                "Cannot auto-detect response type "
                "due to missing Content-Type header."
            )
        main_type, sub_type, extras = parse_content_type(ct)
        if sub_type == "json":
            response_type = "json"
        elif sub_type == "x-tar":
            response_type = "tar"
        elif (main_type, sub_type) == ("text", "plain"):
            response_type = "text"
            encoding = extras.get("charset", encoding)
        else:
            raise TypeError("Unrecognized response type: {ct}".format(ct=ct))
    if "tar" == response_type:
        what = await response.read()
        return tarfile.open(mode="r", fileobj=BytesIO(what))
    if "json" == response_type:
        data = await response.json(encoding=encoding)
    elif "text" == response_type:
        data = await response.text(encoding=encoding)
    else:
        data = await response.read()
    return data