Decode a push notification with the given body XML.

    Returns a dictionary containing the constituent objects of the push
    notification. The kind of push notification is given in the ``"type"``
    member of the returned dictionary.
183404
def objects_for_push_notification(notification):
    
    notification_el = ElementTree.fromstring(notification)
    objects = {'type': notification_el.tag}
    for child_el in notification_el:
        tag = child_el.tag
        res = Resource.value_for_element(child_el)
        objects[tag] = res
    return objects
968097
def body_as_str(self, encoding='UTF-8'):
        
        data = self.body
        try:
            return "".join(b.decode(encoding) for b in data)
        except TypeError:
            return six.text_type(data)
        except:  # pylint: disable=bare-except
            pass
        try:
            return data.decode(encoding)
        except Exception as e:
            raise TypeError("Message data is not compatible with string type: {}".format(e))
537623
def message_to_objects(
        message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None,
) -> List:
    
    # We only really expect one element here for ActivityPub.
    return element_to_objects(message)
27198
def _maybe_deserialize_body(self):
        
        if not self.content_type:
            return self._message_body
        ct = headers.parse_content_type(self.content_type)
        key = '{}/{}'.format(ct.content_type, ct.content_subtype)
        if key not in self._SERIALIZATION_MAP:
            if key not in self._IGNORE_TYPES:
                self.logger.debug('Unsupported content-type: %s',
                                  self.content_type)
            return self._message_body
        elif not self._SERIALIZATION_MAP[key].get('enabled', True):
            self.logger.debug('%s is not enabled in the serialization map',
                              key)
            return self._message_body
        value = self._message_body
        if not self._SERIALIZATION_MAP[key].get('binary'):
            value = self._maybe_decode(
                self._message_body, ct.parameters.get('charset', 'utf-8'))
        return self._maybe_invoke_serialization(value, 'load', key)
1152288
def normalize_body(self, b):
        
        if b is None: return ''

        if self.is_json():
            # TODO ???
            # I don't like this, if we have a content type but it isn't one
            # of the supported ones we were returning the exception, which threw
            # Jarid off, but now it just returns a string, which is not best either
            # my thought is we could have a body_type_subtype method that would 
            # make it possible to easily handle custom types
            # eg, "application/json" would become: self.body_application_json(b, is_error)
            b = json.dumps(b, cls=ResponseBody)

        else:
            # just return a string representation of body if no content type
            b = String(b, self.encoding)

        return b
834277
def deserialize_from_http_generics(cls, body_bytes, headers):
        # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any
        
        # Try to use content-type from headers if available
        content_type = None
        if 'content-type' in headers:
            content_type = headers['content-type'].split(";")[0].strip().lower()
        # Ouch, this server did not declare what it sent...
        # Let's guess it's JSON...
        # Also, since Autorest was considering that an empty body was a valid JSON,
        # need that test as well....
        else:
            content_type = "application/json"

        if body_bytes:
            return cls.deserialize_from_text(body_bytes, content_type)
        return None
879149
def json(self):
        '''  '''
        ctype = self.environ.get('CONTENT_TYPE', '').lower().split(';')[0]
        if ctype == 'application/json':
            b = self._get_body_string()
            if not b:
                return None
            return json_loads(b)
        return None
221831
public String extractPayloadJsonAsString(String body) {
        if (body == null) {
            return null;
        }
        String[] pairs = body.split("\\&");
        for (String pair : pairs) {
            String[] elements = pair.split("=");
            if (elements.length == 2 && elements[0].equals("payload")) {
                try {
                    return URLDecoder.decode(elements[1], "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    return elements[1];
                }
            }
        }
        return null;
    }
507971
def body(self):
        """"""

        if self._decoded_body == None:
            # Try to decode the JSON body. But raise an error if the
            # content-type is unexpected, or the JSON is invalid.

            raw_content_type = self.request.headers.get("content-type") or ""
            content_type = raw_content_type.split(";")[0].strip().lower()

            if content_type == "application/json":
                try:
                    self._decoded_body = escape.json_decode(self.request.body)
                except:
                    raise oz.json_api.ApiError("Bad JSON body")
            else:
                raise oz.json_api.ApiError("JSON body expected")

        return self._decoded_body
690786
def get_request_body(self):
        
        if self._request_body is None:
            content_type_str = self.request.headers.get(
                'Content-Type', 'application/octet-stream')
            LOGGER.debug('decoding request body of type %s', content_type_str)
            content_type = headers.parse_content_type(content_type_str)
            try:
                selected, requested = algorithms.select_content_type(
                    [content_type], _content_types.values())
            except errors.NoMatch:
                raise web.HTTPError(
                    415, 'cannot decoded content type %s', content_type_str,
                    reason='Unexpected content type')
            handler = _content_handlers[str(selected)]
            try:
                self._request_body = handler.unpack_bytes(
                    self.request.body,
                    encoding=content_type.parameters.get('charset'),
                )
            except ValueError as error:
                raise web.HTTPError(
                    400, 'failed to decode content body - %r', error,
                    reason='Content body decode failure')
        return self._request_body
851421
def body(self):
        
        if not self._auto_decode:
            return self._body
        if 'body' in self._decode_cache:
            return self._decode_cache['body']
        body = try_utf8_decode(self._body)
        self._decode_cache['body'] = body
        return body
317621
private static JsJmsMessage decodeTextBody(String body) throws MessageDecodeFailedException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "decodeTextBody");
        JsJmsTextMessage result = new JsJmsTextMessageImpl(MfpConstants.CONSTRUCTOR_NO_OP);
        if (body != null) {
            result.setText(URLDecode(body));
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "decodeTextBody");
        return result;
    }
483095
def parse_soap_enveloped_saml(text, body_class, header_class=None):
    
    envelope = defusedxml.ElementTree.fromstring(text)
    assert envelope.tag == '{%s}Envelope' % NAMESPACE

    # print(len(envelope))
    body = None
    header = {}
    for part in envelope:
        # print(">",part.tag)
        if part.tag == '{%s}Body' % NAMESPACE:
            for sub in part:
                try:
                    body = saml2.create_class_from_element_tree(
                            body_class, sub)
                except Exception:
                    raise Exception(
                        "Wrong body type (%s) in SOAP envelope" % sub.tag)
        elif part.tag == '{%s}Header' % NAMESPACE:
            if not header_class:
                raise Exception("Header where I didn't expect one")
            # print("--- HEADER ---")
            for sub in part:
                # print(">>",sub.tag)
                for klass in header_class:
                    # print("?{%s}%s" % (klass.c_namespace,klass.c_tag))
                    if sub.tag == "{%s}%s" % (klass.c_namespace, klass.c_tag):
                        header[sub.tag] = \
                            saml2.create_class_from_element_tree(klass, sub)
                        break

    return body, header
193930
def _get_message(self, get_frame, auto_decode):
        
        message_uuid = self._channel.rpc.register_request(
            get_frame.valid_responses + ['ContentHeader', 'ContentBody']
        )
        try:
            self._channel.write_frame(get_frame)
            get_ok_frame = self._channel.rpc.get_request(message_uuid,
                                                         raw=True,
                                                         multiple=True)
            if isinstance(get_ok_frame, specification.Basic.GetEmpty):
                return None
            content_header = self._channel.rpc.get_request(message_uuid,
                                                           raw=True,
                                                           multiple=True)
            body = self._get_content_body(message_uuid,
                                          content_header.body_size)
        finally:
            self._channel.rpc.remove(message_uuid)
        return Message(channel=self._channel,
                       body=body,
                       method=dict(get_ok_frame),
                       properties=dict(content_header.properties),
                       auto_decode=auto_decode)
614919
def decode_body(headers: MutableMapping, body: bytes) -> dict:
    

    type_, encoding = parse_content_type(headers)
    decoded_body = body.decode(encoding)

    # There is one api that just returns `ok` instead of json. In order to have a consistent API we decided to modify the returned payload into a dict.
    if type_ == "application/json":
        payload = json.loads(decoded_body)
    else:
        if decoded_body == "ok":
            payload = {"ok": True}
        else:
            payload = {"ok": False, "data": decoded_body}

    return payload
1032534
def payload(self):
        
        _msg = as_unicode(self.part[1])

        # If not JSON web token assume JSON
        if "cty" in self.headers and self.headers["cty"].lower() != "jwt":
            pass
        else:
            try:
                _msg = json.loads(_msg)
            except ValueError:
                pass

        return _msg
1071208
def _as_decode(self, msg):
        """"""
        return {'armed_statuses': [x for x in msg[4:12]],
                'arm_up_states': [x for x in msg[12:20]],
                'alarm_states': [x for x in msg[20:28]]}