def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_2_0):

if kmip_version < enums.KMIPVersion.KMIP_2_0:<EOL><INDENT>raise exceptions.VersionNotSupported(<EOL>"<STR_LIT>".format(<EOL>kmip_version.value<EOL>)<EOL>)<EOL><DEDENT>local_stream = BytearrayStream()<EOL>for attribute in self._attributes:<EOL><INDENT>tag = attribute.tag<EOL>if not enums.is_attribute(tag, kmip_version=kmip_version):<EOL><INDENT>raise exceptions.AttributeNotSupported(<EOL>"<STR_LIT>".format(<EOL>tag.name,<EOL>kmip_version.value<EOL>)<EOL>)<EOL><DEDENT>attribute.write(local_stream, kmip_version=kmip_version)<EOL><DEDENT>self.length = local_stream.length()<EOL>super(Attributes, self).write(output_stream, kmip_version=kmip_version)<EOL>output_stream.write(local_stream.buffer)<EOL>

Write the Attributes structure encoding to the data stream.

Args:
    output_stream (stream): A data stream in which to encode
        Attributes structure data, supporting a write method.
    kmip_version (enum): A KMIPVersion enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 2.0.

Raises:
    AttributeNotSupported: Raised if an unsupported attribute is
        found in the attribute list while encoding.
    VersionNotSupported: Raised when a KMIP version is provided that
        does not support the Attributes object.


def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):

super(LongInteger, self).read(istream, kmip_version=kmip_version)<EOL>if self.length is not LongInteger.LENGTH:<EOL><INDENT>raise exceptions.InvalidPrimitiveLength(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>LongInteger.LENGTH, self.length))<EOL><DEDENT>self.value = unpack('<STR_LIT>', istream.read(self.length))[<NUM_LIT:0>]<EOL>self.validate()<EOL>

Read the encoding of the LongInteger from the input stream.

Args:
    istream (stream): A buffer containing the encoded bytes of a
        LongInteger. Usually a BytearrayStream object. Required.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidPrimitiveLength: if the long integer encoding read in has
        an invalid encoded length.


def read_value(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):

try:<EOL><INDENT>value = unpack('<STR_LIT>', istream.read(self.LENGTH))[<NUM_LIT:0>]<EOL><DEDENT>except Exception:<EOL><INDENT>self.logger.error("<STR_LIT>")<EOL>raise<EOL><DEDENT>if value == <NUM_LIT:1>:<EOL><INDENT>self.value = True<EOL><DEDENT>elif value == <NUM_LIT:0>:<EOL><INDENT>self.value = False<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(value))<EOL><DEDENT>self.validate()<EOL>

Read the value of the Boolean object from the input stream.

Args:
    istream (Stream): A buffer containing the encoded bytes of the
        value of a Boolean object. Usually a BytearrayStream object.
        Required.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: if the read boolean value is not a 0 or 1.


super(Enumeration, self).read(istream, kmip_version=kmip_version)<EOL>if self.length != Enumeration.LENGTH:<EOL><INDENT>raise exceptions.InvalidPrimitiveLength(<EOL>"<STR_LIT>".format(Enumeration.LENGTH))<EOL><DEDENT>value = unpack('<STR_LIT>', istream.read(Enumeration.LENGTH))[<NUM_LIT:0>]<EOL>self.value = self.enum(value)<EOL>pad = unpack('<STR_LIT>', istream.read(Enumeration.LENGTH))[<NUM_LIT:0>]<EOL>if pad != <NUM_LIT:0>:<EOL><INDENT>raise exceptions.InvalidPaddingBytes("<STR_LIT>")<EOL><DEDENT>self.validate()<EOL>

Read the encoding of the Enumeration from the input stream.

Args:
    istream (stream): A buffer containing the encoded bytes of an
        Enumeration. Usually a BytearrayStream object. Required.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidPrimitiveLength: if the Enumeration encoding read in has an
        invalid encoded length.
    InvalidPaddingBytes: if the Enumeration encoding read in does not
        use zeroes for its padding bytes.


super(Boolean, self).read(istream, kmip_version=kmip_version)<EOL>self.read_value(istream, kmip_version=kmip_version)<EOL>

Read the encoding of the Boolean object from the input stream.

Args:
    istream (Stream): A buffer containing the encoded bytes of a
        Boolean object. Usually a BytearrayStream object. Required.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.


def __init__(self, enum, value=None, tag=enums.Tags.DEFAULT):

super(Enumeration, self).__init__(tag, enums.Types.ENUMERATION)<EOL>self.value = value<EOL>self.enum = enum<EOL>self.length = Enumeration.LENGTH<EOL>self.validate()<EOL>

Create an Enumeration.

Args:
    enum (class): The enumeration class of which value is a member
        (e.g., Tags). Required.
    value (int): The value of the Enumeration, must be an integer
        (e.g., Tags.DEFAULT). Optional, defaults to None.
    tag (Tags): An enumeration defining the tag of the Enumeration.
        Optional, defaults to Tags.DEFAULT.


if self.value is not None:<EOL><INDENT>if not isinstance(self.value, six.integer_types):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(<EOL>six.integer_types, type(self.value)))<EOL><DEDENT><DEDENT>

Verify that the value of the BigInteger is valid.

Raises:
    TypeError: if the value is not of type int or long


def __init__(self, value=None, tag=enums.Tags.DEFAULT):

if value is None:<EOL><INDENT>value = int(time.time())<EOL><DEDENT>super(DateTime, self).__init__(value, tag)<EOL>self.type = enums.Types.DATE_TIME<EOL>

Create a DateTime.

Args:
    value (int): The value of the DateTime in number of seconds since
        the Epoch. See the time package for additional information.
        Optional, defaults to the current time.
    tag (Tags): An enumeration defining the tag of the LongInteger.
        Optional, defaults to Tags.DEFAULT.


super(BigInteger, self).read(istream, kmip_version=kmip_version)<EOL>if self.length % <NUM_LIT:8>:<EOL><INDENT>raise exceptions.InvalidPrimitiveLength(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(self.length))<EOL><DEDENT>sign = <NUM_LIT:1><EOL>binary = '<STR_LIT>'<EOL>for _ in range(self.length):<EOL><INDENT>byte = struct.unpack('<STR_LIT>', istream.read(<NUM_LIT:1>))[<NUM_LIT:0>]<EOL>bits = "<STR_LIT>".format(byte)<EOL>pad = len(bits) % <NUM_LIT:8><EOL>if pad:<EOL><INDENT>bits = ('<STR_LIT:0>' * (<NUM_LIT:8> - pad)) + bits<EOL><DEDENT>binary += bits<EOL><DEDENT>if binary[<NUM_LIT:0>] == '<STR_LIT:1>':<EOL><INDENT>sign = -<NUM_LIT:1><EOL>binary = binary.replace('<STR_LIT:1>', '<STR_LIT:i>')<EOL>binary = binary.replace('<STR_LIT:0>', '<STR_LIT:1>')<EOL>binary = binary.replace('<STR_LIT:i>', '<STR_LIT:0>')<EOL>pivot = binary.rfind('<STR_LIT:0>')<EOL>binary = binary[<NUM_LIT:0>:pivot] + '<STR_LIT:1>' + ('<STR_LIT:0>' * len(binary[pivot + <NUM_LIT:1>:]))<EOL><DEDENT>self.value = int(binary, <NUM_LIT:2>) * sign<EOL>

Read the encoding of the BigInteger from the input stream.

Args:
    istream (stream): A buffer containing the encoded bytes of the
        value of a BigInteger. Usually a BytearrayStream object.
        Required.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidPrimitiveLength: if the big integer encoding read in has
        an invalid encoded length.


def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):

super(Boolean, self).write(ostream, kmip_version=kmip_version)<EOL>self.write_value(ostream, kmip_version=kmip_version)<EOL>

Write the encoding of the Boolean object to the output stream.

Args:
    ostream (Stream): A buffer to contain the encoded bytes of a
        Boolean object. Usually a BytearrayStream object. Required.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.


if not isinstance(self.enum, enumeration.EnumMeta):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'.format(<EOL>self.enum))<EOL><DEDENT>if self.value is not None:<EOL><INDENT>if not isinstance(self.value, self.enum):<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>'.format(<EOL>self.value, self.enum))<EOL><DEDENT>if type(self.value.value) not in six.integer_types:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if self.value.value > Enumeration.MAX:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT>elif self.value.value < Enumeration.MIN:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>

Verify that the value of the Enumeration is valid.

Raises:
    TypeError: if the enum is not of type Enum
    ValueError: if the value is not of the expected Enum subtype or if
        the value cannot be represented by an unsigned 32-bit integer


if not isinstance(value, Tags):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for entry in attribute_name_tag_table:<EOL><INDENT>if value == entry[<NUM_LIT:1>]:<EOL><INDENT>return entry[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>raise ValueError("<STR_LIT>".format(value))<EOL>

A utility function that converts an attribute tag into the corresponding
attribute name string.

For example: enums.Tags.STATE -> 'State'

Args:
    value (enum): The Tags enumeration value of the attribute.

Returns:
    string: The attribute name string that corresponds to the attribute
        tag.

Raises:
    ValueError: if the attribute tag is not a Tags enumeration or if it
        is unrecognized attribute tag


super(Certificate, self).__init__(Tags.CERTIFICATE)<EOL>if certificate_type is None:<EOL><INDENT>self.certificate_type = CertificateType()<EOL><DEDENT>else:<EOL><INDENT>self.certificate_type = CertificateType(certificate_type)<EOL><DEDENT>if certificate_value is None:<EOL><INDENT>self.certificate_value = CertificateValue()<EOL><DEDENT>else:<EOL><INDENT>self.certificate_value = CertificateValue(certificate_value)<EOL><DEDENT>

Construct a Certificate object.

Args:
    certificate_type (CertificateType): The type of the
        certificate. Optional, defaults to None.
    certificate_value (bytes): The bytes of the certificate. Optional,
        defaults to None.


@classmethod<EOL><INDENT>def create(cls, name_value, name_type):<DEDENT>

if isinstance(name_value, Name.NameValue):<EOL><INDENT>value = name_value<EOL><DEDENT>elif isinstance(name_value, str):<EOL><INDENT>value = cls.NameValue(name_value)<EOL><DEDENT>else:<EOL><INDENT>name = '<STR_LIT:Name>'<EOL>msg = exceptions.ErrorStrings.BAD_EXP_RECV<EOL>member = '<STR_LIT>'<EOL>raise TypeError(msg.format('<STR_LIT>'.format(name, member),<EOL>'<STR_LIT>', type(Name.NameValue),<EOL>type(name_value)))<EOL><DEDENT>if isinstance(name_type, Name.NameType):<EOL><INDENT>n_type = name_type<EOL><DEDENT>elif isinstance(name_type, Enum):<EOL><INDENT>n_type = cls.NameType(name_type)<EOL><DEDENT>else:<EOL><INDENT>name = '<STR_LIT:Name>'<EOL>msg = exceptions.ErrorStrings.BAD_EXP_RECV<EOL>member = '<STR_LIT>'<EOL>raise TypeError(msg.format('<STR_LIT>'.format(name, member),<EOL>'<STR_LIT>', type(Name.NameType),<EOL>type(name_type)))<EOL><DEDENT>return Name(name_value=value,<EOL>name_type=n_type)<EOL>

Returns a Name object, populated with the given value and type


super(Digest, self).__init__(Tags.DIGEST)<EOL>if hashing_algorithm is None:<EOL><INDENT>self.hashing_algorithm = HashingAlgorithm()<EOL><DEDENT>else:<EOL><INDENT>self.hashing_algorithm = hashing_algorithm<EOL><DEDENT>if digest_value is None:<EOL><INDENT>self.digest_value = DigestValue()<EOL><DEDENT>else:<EOL><INDENT>self.digest_value = digest_value<EOL><DEDENT>if key_format_type is None:<EOL><INDENT>self.key_format_type = KeyFormatType()<EOL><DEDENT>else:<EOL><INDENT>self.key_format_type = key_format_type<EOL><DEDENT>self.validate()<EOL>

Construct a Digest object.

Args:
    hashing_algorithm (HashingAlgorithm): The hash algorithm used to
        compute the value of the digest. Optional, defaults to None.
    digest_value (DigestValue): The byte string representing the
        value of the hash digest. Optional, defaults to None.
    key_format_type (KeyFormatType): The format type of the key the
        hash was computed for, if the object in question is a key.
        Optional, defaults to None.


Error check the attributes of the Digest object.


def __init__(self, unique_identifier=None, usage_limits_count=None):

super(GetUsageAllocationRequestPayload, self).__init__(<EOL>enums.Tags.REQUEST_PAYLOAD<EOL>)<EOL>self._unique_identifier = None<EOL>self._usage_limits_count = None<EOL>self.unique_identifier = unique_identifier<EOL>self.usage_limits_count = usage_limits_count<EOL>

Construct a GetUsageAllocation request payload struct.

Args:
    unique_identifier (string): The ID of the managed object (e.g.,
        a public key) to obtain a usage allocation for. Optional,
        defaults to None.
    usage_limits_count (int): The number of usage limits units that
        should be reserved for the object. Optional, defaults to None.


super(GetUsageAllocationResponsePayload, self).__init__(<EOL>enums.Tags.RESPONSE_PAYLOAD<EOL>)<EOL>self._unique_identifier = None<EOL>self.unique_identifier = unique_identifier<EOL>

Construct a GetUsageAllocation response payload struct.

Args:
    unique_identifier (string): The ID of the managed object (e.g.,
        a public key) that was allocated. Optional, defaults to None.


def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):

Read the data encoding the GetUsageAllocation request payload and
decode it into its constituent parts.

Args:
    input_stream (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is missing from the
        encoded payload.


super(CreateResponsePayload, self).__init__(<EOL>tag=enums.Tags.RESPONSE_PAYLOAD<EOL>)<EOL>self._object_type = None<EOL>self._unique_identifier = None<EOL>self._template_attribute = None<EOL>self.object_type = object_type<EOL>self.unique_identifier = unique_identifier<EOL>self.template_attribute = template_attribute<EOL>

Construct a Create response payload structure.

Args:
    object_type (enum): An ObjectType enumeration specifying the type
        of object created. Optional, defaults to None. Required for
        read/write.
    unique_identifier (string): The ID of the new object. Optional,
        defaults to None. Required for read/write.
    template_attribute (TemplateAttribute): A TemplateAttribute
        structure containing a set of attributes that were set on the
        new object. Optional, defaults to None.


super(ObtainLeaseResponsePayload, self).__init__(<EOL>enums.Tags.RESPONSE_PAYLOAD<EOL>)<EOL>self._unique_identifier = None<EOL>self._lease_time = None<EOL>self._last_change_date = None<EOL>self.unique_identifier = unique_identifier<EOL>self.lease_time = lease_time<EOL>self.last_change_date = last_change_date<EOL>

Construct an ObtainLease response payload struct.

Args:
    unique_identifier (string): The ID of the managed object (e.g.,
        a public key) a lease was obtained for. Optional, defaults to
        None.
    lease_time (int): The amount of time, in seconds, that the object
        lease is in effect for. Optional, defaults to None.
    last_change_date (int): The date, in seconds since the epoch,
        when the last change was made to the object or one of its
        attributes. Optional, defaults to None.


Read the data encoding the ObtainLease request payload and decode it
into its constituent parts.

Args:
    input_stream (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is missing from the
        encoded payload.


super(GetAttributeListRequestPayload, self).__init__(<EOL>enums.Tags.REQUEST_PAYLOAD)<EOL>self._unique_identifier = None<EOL>self.unique_identifier = unique_identifier<EOL>

Construct a GetAttributeList request payload.

Args:
    unique_identifier (string): The ID of the managed object with
        which the retrieved attribute names should be associated.
        Optional, defaults to None.


def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):

local_buffer = utils.BytearrayStream()<EOL>if self._unique_identifier:<EOL><INDENT>self._unique_identifier.write(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if self._attribute_names:<EOL><INDENT>if kmip_version < enums.KMIPVersion.KMIP_2_0:<EOL><INDENT>for attribute_name in self._attribute_names:<EOL><INDENT>attribute_name.write(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for attribute_name in self._attribute_names:<EOL><INDENT>t = enums.convert_attribute_name_to_tag(<EOL>attribute_name.value<EOL>)<EOL>e = primitives.Enumeration(<EOL>enums.Tags,<EOL>value=t,<EOL>tag=enums.Tags.ATTRIBUTE_REFERENCE<EOL>)<EOL>e.write(local_buffer, kmip_version=kmip_version)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>self.length = local_buffer.length()<EOL>super(GetAttributeListResponsePayload, self).write(<EOL>output_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>output_buffer.write(local_buffer.buffer)<EOL>

Write the data encoding the GetAttributeList response payload to a
stream.

Args:
    output_buffer (stream): A data stream in which to encode object
        data, supporting a write method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidField: Raised if the unique identifier or attribute name
        are not defined.


super(DecryptRequestPayload, self).__init__(<EOL>enums.Tags.REQUEST_PAYLOAD<EOL>)<EOL>self._unique_identifier = None<EOL>self._cryptographic_parameters = None<EOL>self._data = None<EOL>self._iv_counter_nonce = None<EOL>self.unique_identifier = unique_identifier<EOL>self.cryptographic_parameters = cryptographic_parameters<EOL>self.data = data<EOL>self.iv_counter_nonce = iv_counter_nonce<EOL>

Construct a Decrypt request payload struct.

Args:
    unique_identifier (string): The ID of the managed object (e.g.,
        a symmetric key) to be used for decryption. Optional, defaults
        to None. If not included, the ID placeholder will be used.
    cryptographic_parameters (CryptographicParameters): A
        CryptographicParameters struct containing the settings for
        the decryption algorithm. Optional, defaults to None. If not
        included, the CryptographicParameters associated with the
        managed object will be used instead.
    data (bytes): The data to decrypt in binary form. Required for
        encoding and decoding.
    iv_counter_nonce (bytes): The IV/counter/nonce value to be used
        with the decryption algorithm. Optional, defaults to None.


def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):

local_stream = utils.BytearrayStream()<EOL>if self._unique_identifier:<EOL><INDENT>self._unique_identifier.write(<EOL>local_stream,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if self._data:<EOL><INDENT>self._data.write(local_stream, kmip_version=kmip_version)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.length = local_stream.length()<EOL>super(DecryptResponsePayload, self).write(<EOL>output_stream,<EOL>kmip_version=kmip_version<EOL>)<EOL>output_stream.write(local_stream.buffer)<EOL>

Write the data encoding the Decrypt response payload to a stream.

Args:
    output_stream (stream): A data stream in which to encode object
        data, supporting a write method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the unique_identifier or data attributes
        are not defined.


Read the data encoding the Decrypt request payload and decode it
into its constituent parts.

Args:
    input_stream (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is missing from the
        encoded payload.


def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):

super(DeriveKeyResponsePayload, self).read(<EOL>input_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>local_buffer = utils.BytearrayStream(input_buffer.read(self.length))<EOL>if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer):<EOL><INDENT>self._unique_identifier = primitives.TextString(<EOL>tag=enums.Tags.UNIQUE_IDENTIFIER<EOL>)<EOL>self._unique_identifier.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidKmipEncoding(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if kmip_version < enums.KMIPVersion.KMIP_2_0:<EOL><INDENT>if self.is_tag_next(enums.Tags.TEMPLATE_ATTRIBUTE, local_buffer):<EOL><INDENT>self._template_attribute = objects.TemplateAttribute()<EOL>self._template_attribute.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT><DEDENT>self.is_oversized(local_buffer)<EOL>

Read the data encoding the DeriveKey response payload and decode it
into its constituent parts.

Args:
    input_buffer (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is missing from the
        encoded payload.


super(GetRequestPayload, self).__init__(<EOL>enums.Tags.REQUEST_PAYLOAD<EOL>)<EOL>self._unique_identifier = None<EOL>self._key_format_type = None<EOL>self._key_compression_type = None<EOL>self._key_wrapping_specification = None<EOL>self.unique_identifier = unique_identifier<EOL>self.key_format_type = key_format_type<EOL>self.key_compression_type = key_compression_type<EOL>self.key_wrapping_specification = key_wrapping_specification<EOL>

Construct a Get request payload struct.

Args:
    unique_identifier (string): The ID of the managed object (e.g., a
        symmetric key) to retrieve. Optional, defaults to None.
    key_format_type (KeyFormatType): A KeyFormatType enumeration that
        specifies the format in which the object should be returned.
        Optional, defaults to None.
    key_compression_type (KeyCompressionType): A KeyCompressionType
        enumeration that specifies the compression method to be used
        when returning elliptic curve public keys. Optional, defaults
        to None.
    key_wrapping_specification (KeyWrappingSpecification): A
        KeyWrappingSpecification struct that specifies keys and other
        information for wrapping the returned object. Optional,
        defaults to None.


Read the data encoding the Encrypt request payload and decode it
into its constituent parts.

Args:
    input_stream (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is missing from the
        encoded payload.


local_buffer = utils.BytearrayStream()<EOL>if self._located_items:<EOL><INDENT>self._located_items.write(local_buffer, kmip_version=kmip_version)<EOL><DEDENT>if self._unique_identifiers:<EOL><INDENT>for unique_identifier in self._unique_identifiers:<EOL><INDENT>unique_identifier.write(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT><DEDENT>self.length = local_buffer.length()<EOL>super(LocateResponsePayload, self).write(<EOL>output_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>output_buffer.write(local_buffer.buffer)<EOL>

Write the data encoding the Locate response payload to a buffer.

Args:
    output_buffer (stream): A data buffer in which to encode object
        data, supporting a write method.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.


local_buffer = utils.BytearrayStream()<EOL>if self._maximum_items:<EOL><INDENT>self._maximum_items.write(local_buffer, kmip_version=kmip_version)<EOL><DEDENT>if self._offset_items:<EOL><INDENT>self._offset_items.write(local_buffer, kmip_version=kmip_version)<EOL><DEDENT>if self._storage_status_mask:<EOL><INDENT>self._storage_status_mask.write(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>if self._object_group_member:<EOL><INDENT>self._object_group_member.write(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>if kmip_version < enums.KMIPVersion.KMIP_2_0:<EOL><INDENT>if self._attributes:<EOL><INDENT>for attribute in self.attributes:<EOL><INDENT>attribute.write(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if self._attributes:<EOL><INDENT>template_attribute = objects.TemplateAttribute(<EOL>attributes=self.attributes<EOL>)<EOL>attributes = objects.convert_template_attribute_to_attributes(<EOL>template_attribute<EOL>)<EOL>attributes.write(local_buffer, kmip_version=kmip_version)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>self.length = local_buffer.length()<EOL>super(LocateRequestPayload, self).write(<EOL>output_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>output_buffer.write(local_buffer.buffer)<EOL>

Write the data encoding the Locate request payload to a buffer.

Args:
    output_buffer (stream): A data buffer in which to encode object
        data, supporting a write method.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.


super(ArchiveResponsePayload, self).__init__(<EOL>enums.Tags.RESPONSE_PAYLOAD<EOL>)<EOL>self._unique_identifier = None<EOL>self.unique_identifier = unique_identifier<EOL>

Construct an Archive response payload struct.

Args:
    unique_identifier (string): The ID of the managed object (e.g.,
        a public key) that was archived. Optional, defaults to None.


Read the data encoding the Archive request payload and decode it into
its constituent parts.

Args:
    input_stream (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is missing from the
        encoded payload.


Write the data encoding the Archive request payload to a stream.

Args:
    output_stream (stream): A data stream in which to encode object
        data, supporting a write method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is not defined.


local_buffer = utils.BytearrayStream()<EOL>if self._query_functions:<EOL><INDENT>for query_function in self._query_functions:<EOL><INDENT>query_function.write(local_buffer, kmip_version=kmip_version)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>self.length = local_buffer.length()<EOL>super(QueryRequestPayload, self).write(<EOL>output_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>output_buffer.write(local_buffer.buffer)<EOL>

Write the data encoding the QueryRequestPayload object to a stream.

Args:
    output_buffer (Stream): A data stream in which to encode object
        data, supporting a write method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidField: Raised if the query functions are not defined.


super(QueryResponsePayload, self).read(<EOL>input_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>local_buffer = utils.BytearrayStream(input_buffer.read(self.length))<EOL>operations = []<EOL>while(self.is_tag_next(enums.Tags.OPERATION, local_buffer)):<EOL><INDENT>operation = primitives.Enumeration(<EOL>enums.Operation,<EOL>tag=enums.Tags.OPERATION<EOL>)<EOL>operation.read(local_buffer, kmip_version=kmip_version)<EOL>operations.append(operation)<EOL><DEDENT>self._operations = operations<EOL>object_types = []<EOL>while(self.is_tag_next(enums.Tags.OBJECT_TYPE, local_buffer)):<EOL><INDENT>object_type = primitives.Enumeration(<EOL>enums.ObjectType,<EOL>tag=enums.Tags.OBJECT_TYPE<EOL>)<EOL>object_type.read(local_buffer, kmip_version=kmip_version)<EOL>object_types.append(object_type)<EOL><DEDENT>self._object_types = object_types<EOL>if self.is_tag_next(enums.Tags.VENDOR_IDENTIFICATION, local_buffer):<EOL><INDENT>vendor_identification = primitives.TextString(<EOL>tag=enums.Tags.VENDOR_IDENTIFICATION<EOL>)<EOL>vendor_identification.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>self._vendor_identification = vendor_identification<EOL><DEDENT>if self.is_tag_next(enums.Tags.SERVER_INFORMATION, local_buffer):<EOL><INDENT>server_information = misc.ServerInformation()<EOL>server_information.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>self._server_information = server_information<EOL><DEDENT>application_namespaces = []<EOL>while(self.is_tag_next(<EOL>enums.Tags.APPLICATION_NAMESPACE,<EOL>local_buffer<EOL>)<EOL>):<EOL><INDENT>application_namespace = primitives.TextString(<EOL>tag=enums.Tags.APPLICATION_NAMESPACE<EOL>)<EOL>application_namespace.read(local_buffer, kmip_version=kmip_version)<EOL>application_namespaces.append(application_namespace)<EOL><DEDENT>self._application_namespaces = application_namespaces<EOL>if kmip_version >= enums.KMIPVersion.KMIP_1_1:<EOL><INDENT>extensions_information = []<EOL>while(self.is_tag_next(<EOL>enums.Tags.EXTENSION_INFORMATION,<EOL>local_buffer<EOL>)<EOL>):<EOL><INDENT>extension_information = objects.ExtensionInformation()<EOL>extension_information.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>extensions_information.append(extension_information)<EOL><DEDENT>self._extension_information = extensions_information<EOL><DEDENT>if kmip_version >= enums.KMIPVersion.KMIP_1_2:<EOL><INDENT>attestation_types = []<EOL>while(self.is_tag_next(enums.Tags.ATTESTATION_TYPE, local_buffer)):<EOL><INDENT>attestation_type = primitives.Enumeration(<EOL>enums.AttestationType,<EOL>tag=enums.Tags.ATTESTATION_TYPE<EOL>)<EOL>attestation_type.read(local_buffer, kmip_version=kmip_version)<EOL>attestation_types.append(attestation_type)<EOL><DEDENT>self._attestation_types = attestation_types<EOL><DEDENT>if kmip_version >= enums.KMIPVersion.KMIP_1_3:<EOL><INDENT>rngs_parameters = []<EOL>while(self.is_tag_next(enums.Tags.RNG_PARAMETERS, local_buffer)):<EOL><INDENT>rng_parameters = objects.RNGParameters()<EOL>rng_parameters.read(local_buffer, kmip_version=kmip_version)<EOL>rngs_parameters.append(rng_parameters)<EOL><DEDENT>self._rng_parameters = rngs_parameters<EOL>profiles_information = []<EOL>while(self.is_tag_next(<EOL>enums.Tags.PROFILE_INFORMATION,<EOL>local_buffer<EOL>)<EOL>):<EOL><INDENT>profile_information = objects.ProfileInformation()<EOL>profile_information.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>profiles_information.append(profile_information)<EOL><DEDENT>self._profile_information = profiles_information<EOL>validations_information = []<EOL>while(self.is_tag_next(<EOL>enums.Tags.VALIDATION_INFORMATION,<EOL>local_buffer<EOL>)<EOL>):<EOL><INDENT>validation_information = objects.ValidationInformation()<EOL>validation_information.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>validations_information.append(validation_information)<EOL><DEDENT>self._validation_information = validations_information<EOL>capabilities_information = []<EOL>while(self.is_tag_next(<EOL>enums.Tags.CAPABILITY_INFORMATION,<EOL>local_buffer<EOL>)<EOL>):<EOL><INDENT>capability_information = objects.CapabilityInformation()<EOL>capability_information.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>capabilities_information.append(capability_information)<EOL><DEDENT>self._capability_information = capabilities_information<EOL>client_registration_methods = []<EOL>while(self.is_tag_next(<EOL>enums.Tags.CLIENT_REGISTRATION_METHOD,<EOL>local_buffer<EOL>)<EOL>):<EOL><INDENT>client_registration_method = primitives.Enumeration(<EOL>enums.ClientRegistrationMethod,<EOL>tag=enums.Tags.CLIENT_REGISTRATION_METHOD<EOL>)<EOL>client_registration_method.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>client_registration_methods.append(client_registration_method)<EOL><DEDENT>self._client_registration_methods = client_registration_methods<EOL><DEDENT>if kmip_version >= enums.KMIPVersion.KMIP_2_0:<EOL><INDENT>if self.is_tag_next(enums.Tags.DEFAULTS_INFORMATION, local_buffer):<EOL><INDENT>defaults_information = objects.DefaultsInformation()<EOL>defaults_information.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>self._defaults_information = defaults_information<EOL><DEDENT>storage_protection_masks = []<EOL>while(self.is_tag_next(<EOL>enums.Tags.PROTECTION_STORAGE_MASK,<EOL>local_buffer<EOL>)<EOL>):<EOL><INDENT>storage_protection_mask = primitives.Integer(<EOL>tag=enums.Tags.PROTECTION_STORAGE_MASK<EOL>)<EOL>storage_protection_mask.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>storage_protection_masks.append(storage_protection_mask)<EOL><DEDENT>self._storage_protection_masks = storage_protection_masks<EOL><DEDENT>self.is_oversized(local_buffer)<EOL>

Read the data encoding the QueryResponsePayload object and decode it
into its constituent parts.

Args:
    input_buffer (Stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.


super(QueryRequestPayload, self).read(<EOL>input_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>local_buffer = utils.BytearrayStream(input_buffer.read(self.length))<EOL>query_functions = []<EOL>while(self.is_tag_next(enums.Tags.QUERY_FUNCTION, local_buffer)):<EOL><INDENT>query_function = primitives.Enumeration(<EOL>enums.QueryFunction,<EOL>tag=enums.Tags.QUERY_FUNCTION<EOL>)<EOL>query_function.read(local_buffer, kmip_version=kmip_version)<EOL>query_functions.append(query_function)<EOL><DEDENT>if query_functions:<EOL><INDENT>self._query_functions = query_functions<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidKmipEncoding(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>self.is_oversized(local_buffer)<EOL>

Read the data encoding the QueryRequestPayload object and decode it
into its constituent parts.

Args:
    input_buffer (Stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidKmipEncoding: Raised if the query functions are missing
        from the encoded payload.


Write the data encoding the SignatureVerify request payload to a
stream.

Args:
    output_stream (stream): A data stream in which to encode object
        data, supporting a write method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is not defined.


super(SignatureVerifyRequestPayload, self).read(<EOL>input_stream,<EOL>kmip_version=kmip_version<EOL>)<EOL>local_stream = utils.BytearrayStream(input_stream.read(self.length))<EOL>if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):<EOL><INDENT>self._unique_identifier = primitives.TextString(<EOL>tag=enums.Tags.UNIQUE_IDENTIFIER<EOL>)<EOL>self._unique_identifier.read(<EOL>local_stream,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>if self.is_tag_next(enums.Tags.CRYPTOGRAPHIC_PARAMETERS, local_stream):<EOL><INDENT>self._cryptographic_parameters =attributes.CryptographicParameters()<EOL>self._cryptographic_parameters.read(<EOL>local_stream,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>if self.is_tag_next(enums.Tags.DATA, local_stream):<EOL><INDENT>self._data = primitives.ByteString(tag=enums.Tags.DATA)<EOL>self._data.read(local_stream, kmip_version=kmip_version)<EOL><DEDENT>if self.is_tag_next(enums.Tags.DIGESTED_DATA, local_stream):<EOL><INDENT>self._digested_data = primitives.ByteString(<EOL>tag=enums.Tags.DIGESTED_DATA<EOL>)<EOL>self._digested_data.read(local_stream, kmip_version=kmip_version)<EOL><DEDENT>if self.is_tag_next(enums.Tags.SIGNATURE_DATA, local_stream):<EOL><INDENT>self._signature_data = primitives.ByteString(<EOL>tag=enums.Tags.SIGNATURE_DATA<EOL>)<EOL>self._signature_data.read(local_stream, kmip_version=kmip_version)<EOL><DEDENT>if self.is_tag_next(enums.Tags.CORRELATION_VALUE, local_stream):<EOL><INDENT>self._correlation_value = primitives.ByteString(<EOL>tag=enums.Tags.CORRELATION_VALUE<EOL>)<EOL>self._correlation_value.read(<EOL>local_stream,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>if self.is_tag_next(enums.Tags.INIT_INDICATOR, local_stream):<EOL><INDENT>self._init_indicator = primitives.Boolean(<EOL>tag=enums.Tags.INIT_INDICATOR<EOL>)<EOL>self._init_indicator.read(local_stream, kmip_version=kmip_version)<EOL><DEDENT>if self.is_tag_next(enums.Tags.FINAL_INDICATOR, local_stream):<EOL><INDENT>self._final_indicator = primitives.Boolean(<EOL>tag=enums.Tags.FINAL_INDICATOR<EOL>)<EOL>self._final_indicator.read(local_stream, kmip_version=kmip_version)<EOL><DEDENT>self.is_oversized(local_stream)<EOL>

Read the data encoding the SignatureVerify request payload and decode
it into its constituent parts.

Args:
    input_stream (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is missing from the
        encoded payload.


super(SignatureVerifyResponsePayload, self).__init__(<EOL>enums.Tags.RESPONSE_PAYLOAD<EOL>)<EOL>self._unique_identifier = None<EOL>self._validity_indicator = None<EOL>self._data = None<EOL>self._correlation_value = None<EOL>self.unique_identifier = unique_identifier<EOL>self.validity_indicator = validity_indicator<EOL>self.data = data<EOL>self.correlation_value = correlation_value<EOL>

Construct a SignatureVerify response payload struct.

Args:
    unique_identifier (string): The ID of the managed object (e.g.,
        a public key) used for signature verification. Optional,
        defaults to None. Required for read/write.
    validity_indicator (ValidityIndicator): A ValidityIndicator
        enumeration that specifies the validity of the signature.
        Optional, defaults to None. Required for read/write.
    data (bytes): The bytes representing any data recovered during the
        signature verification process. Optional, defaults to None.
    correlation_value (bytes): The bytes representing a correlation
        value, allowing the linking together of individual payloads
        for a single overarching operation. Optional, defaults to None.


Write the data encoding the Check response payload to a stream.

Args:
    output_stream (stream): A data stream in which to encode object
        data, supporting a write method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is not defined.


Write the data encoding the Check request payload to a stream.

Args:
    output_stream (stream): A data stream in which to encode object
        data, supporting a write method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.

Raises:
    ValueError: Raised if the data attribute is not defined.


super(RegisterResponsePayload, self).read(<EOL>input_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>local_buffer = utils.BytearrayStream(input_buffer.read(self.length))<EOL>if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer):<EOL><INDENT>self._unique_identifier = primitives.TextString(<EOL>tag=enums.Tags.UNIQUE_IDENTIFIER<EOL>)<EOL>self._unique_identifier.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidKmipEncoding(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if kmip_version < enums.KMIPVersion.KMIP_2_0:<EOL><INDENT>if self.is_tag_next(enums.Tags.TEMPLATE_ATTRIBUTE, local_buffer):<EOL><INDENT>self._template_attribute = objects.TemplateAttribute()<EOL>self._template_attribute.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT><DEDENT>self.is_oversized(local_buffer)<EOL>

Read the data encoding the Register response payload and decode it
into its constituent parts.

Args:
    input_buffer (stream): A data buffer containing encoded object
        data, supporting a read method.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidKmipEncoding: Raised if the unique identifier is missing
        from the encoded payload.


local_buffer = utils.BytearrayStream()<EOL>if self._unique_identifier:<EOL><INDENT>self._unique_identifier.write(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>if kmip_version < enums.KMIPVersion.KMIP_2_0:<EOL><INDENT>for attribute_name in self._attribute_names:<EOL><INDENT>attribute_name.write(local_buffer, kmip_version=kmip_version)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for attribute_name in self._attribute_names:<EOL><INDENT>t = enums.convert_attribute_name_to_tag(attribute_name.value)<EOL>e = primitives.Enumeration(<EOL>enums.Tags,<EOL>value=t,<EOL>tag=enums.Tags.ATTRIBUTE_REFERENCE<EOL>)<EOL>e.write(local_buffer, kmip_version=kmip_version)<EOL><DEDENT><DEDENT>self.length = local_buffer.length()<EOL>super(GetAttributesRequestPayload, self).write(<EOL>output_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>output_buffer.write(local_buffer.buffer)<EOL>

Write the data encoding the GetAttributes request payload to a
stream.

Args:
    output_buffer (stream): A data stream in which to encode object
        data, supporting a write method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.


def __init__(self, unique_identifier=None, attributes=None):

super(GetAttributesResponsePayload, self).__init__(<EOL>enums.Tags.RESPONSE_PAYLOAD)<EOL>self._unique_identifier = None<EOL>self._attributes = list()<EOL>self.unique_identifier = unique_identifier<EOL>self.attributes = attributes<EOL>

Construct a GetAttributes response payload.

Args:
    unique_identifier (string): The ID of the managed object with
        which the retrieved attributes should be associated. Optional,
        defaults to None.
    attributes (list): A list of attribute structures associated with
        the managed object. Optional, defaults to None.


super(GetAttributesRequestPayload, self).read(<EOL>input_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL>local_buffer = utils.BytearrayStream(input_buffer.read(self.length))<EOL>if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer):<EOL><INDENT>self._unique_identifier = primitives.TextString(<EOL>tag=enums.Tags.UNIQUE_IDENTIFIER<EOL>)<EOL>self._unique_identifier.read(<EOL>local_buffer,<EOL>kmip_version=kmip_version<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self._unique_identifier = None<EOL><DEDENT>names = list()<EOL>if kmip_version < enums.KMIPVersion.KMIP_2_0:<EOL><INDENT>while self.is_tag_next(enums.Tags.ATTRIBUTE_NAME, local_buffer):<EOL><INDENT>name = primitives.TextString(tag=enums.Tags.ATTRIBUTE_NAME)<EOL>name.read(local_buffer, kmip_version=kmip_version)<EOL>names.append(name)<EOL><DEDENT>self._attribute_names = names<EOL><DEDENT>else:<EOL><INDENT>while self.is_tag_next(<EOL>enums.Tags.ATTRIBUTE_REFERENCE,<EOL>local_buffer<EOL>):<EOL><INDENT>if self.is_type_next(enums.Types.STRUCTURE, local_buffer):<EOL><INDENT>reference = objects.AttributeReference()<EOL>reference.read(local_buffer, kmip_version=kmip_version)<EOL>names.append(<EOL>primitives.TextString(<EOL>value=reference.attribute_name,<EOL>tag=enums.Tags.ATTRIBUTE_NAME<EOL>)<EOL>)<EOL><DEDENT>elif self.is_type_next(enums.Types.ENUMERATION, local_buffer):<EOL><INDENT>reference = primitives.Enumeration(<EOL>enums.Tags,<EOL>tag=enums.Tags.ATTRIBUTE_REFERENCE<EOL>)<EOL>reference.read(local_buffer, kmip_version=kmip_version)<EOL>name = enums.convert_attribute_tag_to_name(reference.value)<EOL>names.append(<EOL>primitives.TextString(<EOL>value=name,<EOL>tag=enums.Tags.ATTRIBUTE_NAME<EOL>)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidKmipEncoding(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT>self._attribute_names = names<EOL><DEDENT>self.is_oversized(local_buffer)<EOL>

Read the data encoding the GetAttributes request payload and decode
it into its constituent parts.

Args:
    input_buffer (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidKmipEncoding: Raised if an invalid type is found for the
        AttributeReference encoding for KMIP 2.0+ encodings.


Read the data encoding the CreateKeyPair request payload and decode it
into its constituent parts.

Args:
    input_buffer (stream): A data buffer containing encoded object
        data, supporting a read method.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.


Write the data encoding the CreateKeyPair response payload to a buffer.

Args:
    output_buffer (stream): A data buffer in which to encode object
        data, supporting a write method.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.

Raises:
    InvalidField: Raised if the private key unique identifier or the
        public key unique identifier is not defined.


super(ActivateResponsePayload, self).read(<EOL>istream,<EOL>kmip_version=kmip_version<EOL>)<EOL>tstream = BytearrayStream(istream.read(self.length))<EOL>self.unique_identifier = attributes.UniqueIdentifier()<EOL>self.unique_identifier.read(tstream, kmip_version=kmip_version)<EOL>self.is_oversized(tstream)<EOL>self.validate()<EOL>

Read the data encoding the ActivateResponsePayload object and decode it
into its constituent parts.

Args:
    istream (Stream): A data stream containing encoded object data,
        supporting a read method; usually a BytearrayStream object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.


tstream = BytearrayStream()<EOL>if self.unique_identifier is not None:<EOL><INDENT>self.unique_identifier.write(tstream, kmip_version=kmip_version)<EOL><DEDENT>self.length = tstream.length()<EOL>super(ActivateRequestPayload, self).write(<EOL>ostream,<EOL>kmip_version=kmip_version<EOL>)<EOL>ostream.write(tstream.buffer)<EOL>

Write the data encoding the ActivateRequestPayload object to a stream.
Args:
    ostream (Stream): A data stream in which to encode object data,
        supporting a write method; usually a BytearrayStream object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be encoded. Optional,
        defaults to KMIP 1.0.


super(Authentication, self).read(<EOL>input_stream,<EOL>kmip_version=kmip_version<EOL>)<EOL>local_stream = utils.BytearrayStream(input_stream.read(self.length))<EOL>credentials = []<EOL>while self.is_tag_next(enums.Tags.CREDENTIAL, local_stream):<EOL><INDENT>credential = objects.Credential()<EOL>credential.read(local_stream, kmip_version=kmip_version)<EOL>credentials.append(credential)<EOL><DEDENT>if len(credentials) == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._credentials = credentials<EOL>self.is_oversized(local_stream)<EOL>

Read the data encoding the Authentication struct and decode it into
its constituent parts.

Args:
    input_stream (stream): A data stream containing encoded object
        data, supporting a read method; usually a BytearrayStream
        object.
    kmip_version (KMIPVersion): An enumeration defining the KMIP
        version with which the object will be decoded. Optional,
        defaults to KMIP 1.0.


super(KeyFormatTypeNotSupported, self).__init__(<EOL>reason=enums.ResultReason.KEY_FORMAT_TYPE_NOT_SUPPORTED,<EOL>message=message<EOL>)<EOL>

Create a KeyFormatTypeNotSupported exception.

Args:
    message (string): A string containing information about the error.


super(IllegalOperation, self).__init__(<EOL>reason=enums.ResultReason.ILLEGAL_OPERATION,<EOL>message=message<EOL>)<EOL>

Create an IllegalOperation exception.

Args:
    message (string): A string containing information about the error.


super(InvalidMessage, self).__init__(<EOL>reason=enums.ResultReason.INVALID_MESSAGE,<EOL>message=message<EOL>)<EOL>

Create an InvalidMessage exception.

Args:
    message (string): A string containing information about the error.


super(PermissionDenied, self).__init__(<EOL>reason=enums.ResultReason.PERMISSION_DENIED,<EOL>message=message<EOL>)<EOL>

Create a PermissionDenied exception.

Args:
    message (string): A string containing information about the error.


super(TLS12AuthenticationSuite, self).__init__(cipher_suites)<EOL>self._protocol = ssl.PROTOCOL_TLSv1_2<EOL>

Create a TLS12AuthenticationSuite object.

Args:
    cipher_suites (list): A list of strings representing the names of
        cipher suites to use. Overrides the default set of cipher
        suites. Optional, defaults to None.


super(BasicAuthenticationSuite, self).__init__(cipher_suites)<EOL>self._protocol = ssl.PROTOCOL_TLSv1<EOL>

Create a BasicAuthenticationSuite object.

Args:
    cipher_suites (list): A list of strings representing the names of
        cipher suites to use. Overrides the default set of cipher
        suites. Optional, defaults to None.


self._custom_suites = []<EOL>if cipher_suites:<EOL><INDENT>for cipher_suite in cipher_suites:<EOL><INDENT>if cipher_suite in self.openssl_cipher_suite_map.keys():<EOL><INDENT>suite = self.openssl_cipher_suite_map.get(cipher_suite)<EOL>if suite:<EOL><INDENT>self._custom_suites.append(suite)<EOL><DEDENT><DEDENT>elif cipher_suite in self.openssl_cipher_suite_map.values():<EOL><INDENT>if cipher_suite:<EOL><INDENT>self._custom_suites.append(cipher_suite)<EOL><DEDENT><DEDENT><DEDENT>self._custom_suites = list(set(self._custom_suites))<EOL><DEDENT>suites = []<EOL>if self._custom_suites:<EOL><INDENT>for suite in self._custom_suites:<EOL><INDENT>if suite in self._default_cipher_suites:<EOL><INDENT>suites.append(suite)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>suites = self._default_cipher_suites<EOL><DEDENT>self._cipher_suites = '<STR_LIT::>'.join(suites)<EOL>if self._cipher_suites == '<STR_LIT>':<EOL><INDENT>self._cipher_suites = '<STR_LIT::>'.join(self._default_cipher_suites)<EOL><DEDENT>

Create an AuthenticationSuite object.

Args:
    cipher_suites (list): A list of strings representing the names of
        cipher suites to use. Overrides the default set of cipher
        suites. Optional, defaults to None.


return self._protocol<EOL>

Get the authentication suite protocol.

Returns:
    int: The value of the ssl.PROTOCOL_* setting for this suite.


if setting not in self._expected_settings + self._optional_settings:<EOL><INDENT>raise exceptions.ConfigurationError(<EOL>"<STR_LIT>".format(setting)<EOL>)<EOL><DEDENT>if setting == '<STR_LIT>':<EOL><INDENT>self._set_hostname(value)<EOL><DEDENT>elif setting == '<STR_LIT:port>':<EOL><INDENT>self._set_port(value)<EOL><DEDENT>elif setting == '<STR_LIT>':<EOL><INDENT>self._set_certificate_path(value)<EOL><DEDENT>elif setting == '<STR_LIT>':<EOL><INDENT>self._set_key_path(value)<EOL><DEDENT>elif setting == '<STR_LIT>':<EOL><INDENT>self._set_ca_path(value)<EOL><DEDENT>elif setting == '<STR_LIT>':<EOL><INDENT>self._set_auth_suite(value)<EOL><DEDENT>elif setting == '<STR_LIT>':<EOL><INDENT>self._set_policy_path(value)<EOL><DEDENT>elif setting == '<STR_LIT>':<EOL><INDENT>self._set_enable_tls_client_auth(value)<EOL><DEDENT>elif setting == '<STR_LIT>':<EOL><INDENT>self._set_tls_cipher_suites(value)<EOL><DEDENT>elif setting == '<STR_LIT>':<EOL><INDENT>self._set_logging_level(value)<EOL><DEDENT>else:<EOL><INDENT>self._set_database_path(value)<EOL><DEDENT>

Set a specific setting value.

This will overwrite the current setting value for the specified
setting.

Args:
    setting (string): The name of the setting to set (e.g.,
        'certificate_path', 'hostname'). Required.
    value (misc): The value of the setting to set. Type varies based
        on setting. Required.
Raises:
    ConfigurationError: Raised if the setting is not supported or if
        the setting value is invalid.


<EOL>rule_set = self._attribute_rule_sets.get(attribute)<EOL>return rule_set.multiple_instances_permitted<EOL>

Check if the attribute is allowed to have multiple instances.

Args:
    attribute (string): The name of the attribute
        (e.g., 'State'). Required.


def is_attribute_applicable_to_object_type(self, attribute, object_type):

<EOL>rule_set = self._attribute_rule_sets.get(attribute)<EOL>if object_type in rule_set.applies_to_object_types:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Check if the attribute is supported by the given object type.

Args:
    attribute (string): The name of the attribute (e.g., 'Name').
        Required.
    object_type (ObjectType): An ObjectType enumeration
        (e.g., ObjectType.SYMMETRIC_KEY). Required.
Returns:
    bool: True if the attribute is applicable to the object type.
        False otherwise.


def _set_attributes_on_managed_object(self, managed_object, attributes):

for attribute_name, attribute_value in six.iteritems(attributes):<EOL><INDENT>object_type = managed_object._object_type<EOL>if self._attribute_policy.is_attribute_applicable_to_object_type(<EOL>attribute_name,<EOL>object_type):<EOL><INDENT>self._set_attribute_on_managed_object(<EOL>managed_object,<EOL>(attribute_name, attribute_value)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>name = object_type.name<EOL>raise exceptions.InvalidField(<EOL>"<STR_LIT>".format(<EOL>attribute_name,<EOL>'<STR_LIT>'.join([x.capitalize() for x in name.split('<STR_LIT:_>')])<EOL>)<EOL>)<EOL><DEDENT><DEDENT>

Given a kmip.pie object and a dictionary of attributes, attempt to set
the attribute values on the object.


@_synchronize<EOL><INDENT>def process_request(self, request, credential=None):<DEDENT>

self._client_identity = [None, None]<EOL>header = request.request_header<EOL>self._set_protocol_version(header.protocol_version)<EOL>max_response_size = None<EOL>if header.maximum_response_size:<EOL><INDENT>max_response_size = header.maximum_response_size.value<EOL><DEDENT>now = int(time.time())<EOL>if header.time_stamp:<EOL><INDENT>then = header.time_stamp.value<EOL>if (now >= then) and ((now - then) < <NUM_LIT>):<EOL><INDENT>self._logger.info("<STR_LIT>".format(<EOL>time.strftime(<EOL>"<STR_LIT>",<EOL>time.gmtime(then)<EOL>)<EOL>))<EOL><DEDENT>else:<EOL><INDENT>if now < then:<EOL><INDENT>self._logger.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>then,<EOL>now<EOL>)<EOL>)<EOL>raise exceptions.InvalidMessage(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self._logger.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(then, now)<EOL>)<EOL>raise exceptions.InvalidMessage(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>self._logger.info("<STR_LIT>".format(<EOL>time.strftime(<EOL>"<STR_LIT>",<EOL>time.gmtime(now)<EOL>)<EOL>))<EOL><DEDENT>self.is_asynchronous = False<EOL>if header.asynchronous_indicator is not None:<EOL><INDENT>self.is_asynchronous = header.asynchronous_indicator.value<EOL><DEDENT>if self.is_asynchronous:<EOL><INDENT>raise exceptions.InvalidMessage(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if header.authentication:<EOL><INDENT>if header.authentication.credentials:<EOL><INDENT>auth_credentials = header.authentication.credentials[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>auth_credentials = None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>auth_credentials = None<EOL><DEDENT>self._verify_credential(auth_credentials, credential)<EOL>batch_error_option = enums.BatchErrorContinuationOption.STOP<EOL>if header.batch_error_cont_option is not None:<EOL><INDENT>batch_error_option = header.batch_error_cont_option.value<EOL><DEDENT>if batch_error_option == enums.BatchErrorContinuationOption.UNDO:<EOL><INDENT>raise exceptions.InvalidMessage(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>batch_order_option = False<EOL>if header.batch_order_option:<EOL><INDENT>batch_order_option = header.batch_order_option.value<EOL><DEDENT>response_batch = self._process_batch(<EOL>request.batch_items,<EOL>batch_error_option,<EOL>batch_order_option<EOL>)<EOL>response = self._build_response(<EOL>header.protocol_version,<EOL>response_batch<EOL>)<EOL>return response, max_response_size, header.protocol_version<EOL>

Process a KMIP request message.

This routine is the main driver of the KmipEngine. It breaks apart and
processes the request header, handles any message errors that may
result, and then passes the set of request batch items on for
processing. This routine is thread-safe, allowing multiple client
connections to use the same KmipEngine.

Args:
    request (RequestMessage): The request message containing the batch
        items to be processed.
    credential (string): Identifying information about the client
        obtained from the client certificate. Optional, defaults to
        None.

Returns:
    ResponseMessage: The response containing all of the results from
        the request batch items.


def __init__(self, policies=None, database_path=None):

self._logger = logging.getLogger('<STR_LIT>')<EOL>self._cryptography_engine = engine.CryptographyEngine()<EOL>self.database_path = '<STR_LIT>'.format(database_path)<EOL>if not database_path:<EOL><INDENT>self.database_path = '<STR_LIT>'<EOL><DEDENT>self._data_store = sqlalchemy.create_engine(<EOL>self.database_path,<EOL>echo=False,<EOL>connect_args={'<STR_LIT>': False}<EOL>)<EOL>sqltypes.Base.metadata.create_all(self._data_store)<EOL>self._data_store_session_factory = sqlalchemy.orm.sessionmaker(<EOL>bind=self._data_store<EOL>)<EOL>self._lock = threading.RLock()<EOL>self._id_placeholder = None<EOL>self._protocol_versions = [<EOL>contents.ProtocolVersion(<NUM_LIT:1>, <NUM_LIT:4>),<EOL>contents.ProtocolVersion(<NUM_LIT:1>, <NUM_LIT:3>),<EOL>contents.ProtocolVersion(<NUM_LIT:1>, <NUM_LIT:2>),<EOL>contents.ProtocolVersion(<NUM_LIT:1>, <NUM_LIT:1>),<EOL>contents.ProtocolVersion(<NUM_LIT:1>, <NUM_LIT:0>)<EOL>]<EOL>self.default_protocol_version = self._protocol_versions[<NUM_LIT:2>]<EOL>self._protocol_version = self._protocol_versions[<NUM_LIT:2>]<EOL>self._object_map = {<EOL>enums.ObjectType.CERTIFICATE: objects.X509Certificate,<EOL>enums.ObjectType.SYMMETRIC_KEY: objects.SymmetricKey,<EOL>enums.ObjectType.PUBLIC_KEY: objects.PublicKey,<EOL>enums.ObjectType.PRIVATE_KEY: objects.PrivateKey,<EOL>enums.ObjectType.SPLIT_KEY: None,<EOL>enums.ObjectType.TEMPLATE: None,<EOL>enums.ObjectType.SECRET_DATA: objects.SecretData,<EOL>enums.ObjectType.OPAQUE_DATA: objects.OpaqueObject<EOL>}<EOL>self._attribute_policy = policy.AttributePolicy(self._protocol_version)<EOL>self._operation_policies = policies<EOL>self._client_identity = [None, None]<EOL>

Create a KmipEngine.

Args:
    policy_path (string): The path to the filesystem directory
        containing PyKMIP server operation policy JSON files.
        Optional, defaults to None.
    database_path (string): The path to the SQLite database file
        used to store all server data. Optional, defaults to None.
        If none, database path defaults to '/tmp/pykmip.database'.


def _set_attribute_on_managed_object(self, managed_object, attribute):

attribute_name = attribute[<NUM_LIT:0>]<EOL>attribute_value = attribute[<NUM_LIT:1>]<EOL>if self._attribute_policy.is_attribute_multivalued(attribute_name):<EOL><INDENT>if attribute_name == '<STR_LIT:Name>':<EOL><INDENT>managed_object.names.extend(<EOL>[x.name_value.value for x in attribute_value]<EOL>)<EOL>for name in managed_object.names:<EOL><INDENT>if managed_object.names.count(name) > <NUM_LIT:1>:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>".format(attribute_name)<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>field = None<EOL>value = attribute_value.value<EOL>if attribute_name == '<STR_LIT>':<EOL><INDENT>field = '<STR_LIT>'<EOL><DEDENT>elif attribute_name == '<STR_LIT>':<EOL><INDENT>field = '<STR_LIT>'<EOL><DEDENT>elif attribute_name == '<STR_LIT>':<EOL><INDENT>field = '<STR_LIT>'<EOL>value = list()<EOL>for e in enums.CryptographicUsageMask:<EOL><INDENT>if e.value & attribute_value.value:<EOL><INDENT>value.append(e)<EOL><DEDENT><DEDENT><DEDENT>elif attribute_name == '<STR_LIT>':<EOL><INDENT>field = '<STR_LIT>'<EOL><DEDENT>if field:<EOL><INDENT>existing_value = getattr(managed_object, field)<EOL>if existing_value:<EOL><INDENT>if existing_value != value:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>".format(<EOL>attribute_name<EOL>)<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>setattr(managed_object, field, value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>".format(attribute_name)<EOL>)<EOL><DEDENT><DEDENT>

Set the attribute value on the kmip.pie managed object.


def _get_attributes_from_managed_object(self, managed_object, attr_names):

attr_factory = attribute_factory.AttributeFactory()<EOL>retrieved_attributes = list()<EOL>if not attr_names:<EOL><INDENT>attr_names = self._attribute_policy.get_all_attribute_names()<EOL><DEDENT>for attribute_name in attr_names:<EOL><INDENT>object_type = managed_object._object_type<EOL>if not self._attribute_policy.is_attribute_supported(<EOL>attribute_name<EOL>):<EOL><INDENT>continue<EOL><DEDENT>if self._attribute_policy.is_attribute_applicable_to_object_type(<EOL>attribute_name,<EOL>object_type<EOL>):<EOL><INDENT>try:<EOL><INDENT>attribute_value = self._get_attribute_from_managed_object(<EOL>managed_object,<EOL>attribute_name<EOL>)<EOL><DEDENT>except Exception:<EOL><INDENT>attribute_value = None<EOL><DEDENT>if attribute_value is not None:<EOL><INDENT>if self._attribute_policy.is_attribute_multivalued(<EOL>attribute_name<EOL>):<EOL><INDENT>for count, value in enumerate(attribute_value):<EOL><INDENT>attribute = attr_factory.create_attribute(<EOL>enums.AttributeType(attribute_name),<EOL>value,<EOL>count<EOL>)<EOL>retrieved_attributes.append(attribute)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>attribute = attr_factory.create_attribute(<EOL>enums.AttributeType(attribute_name),<EOL>attribute_value<EOL>)<EOL>retrieved_attributes.append(attribute)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return retrieved_attributes<EOL>

Given a kmip.pie object and a list of attribute names, attempt to get
all of the existing attribute values from the object.


def build_error_response(self, version, reason, message):

Build a simple ResponseMessage with a single error result.

Args:
    version (ProtocolVersion): The protocol version the response
        should be addressed with.
    reason (ResultReason): An enumeration classifying the type of
        error occurred.
    message (str): A string providing additional information about
        the error.

Returns:
    ResponseMessage: The simple ResponseMessage containing a
        single error result.


if digital_signature_algorithm:<EOL><INDENT>(hash_alg, crypto_alg) = self._digital_signature_algorithms.get(<EOL>digital_signature_algorithm,<EOL>(None, None)<EOL>)<EOL><DEDENT>elif crypto_alg and hash_algorithm:<EOL><INDENT>hash_alg = self._encryption_hash_algorithms.get(<EOL>hash_algorithm, None<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if crypto_alg == enums.CryptographicAlgorithm.RSA:<EOL><INDENT>try:<EOL><INDENT>key = self._create_RSA_private_key(signing_key)<EOL><DEDENT>except Exception:<EOL><INDENT>raise exceptions.InvalidField('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if padding:<EOL><INDENT>padding_method = self._asymmetric_padding_methods.get(<EOL>padding, None<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if padding == enums.PaddingMethod.PSS:<EOL><INDENT>signature = key.sign(<EOL>data,<EOL>asymmetric_padding.PSS(<EOL>mgf=asymmetric_padding.MGF1(hash_alg()),<EOL>salt_length=asymmetric_padding.PSS.MAX_LENGTH<EOL>),<EOL>hash_alg()<EOL>)<EOL><DEDENT>elif padding == enums.PaddingMethod.PKCS1v15:<EOL><INDENT>signature = key.sign(<EOL>data,<EOL>padding_method(),<EOL>hash_alg()<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise exceptions.InvalidField(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(padding)<EOL>)<EOL><DEDENT>return signature<EOL>

Args:
    digital_signature_algorithm (DigitalSignatureAlgorithm): An
        enumeration specifying the asymmetric cryptographic algorithm
        and hashing algorithm to use for the signature operation. Can
        be None if cryptographic_algorithm and hash_algorithm are set.
    crypto_alg (CryptographicAlgorithm): An enumeration
        specifying the asymmetric cryptographic algorithm to use for
        the signature operation. Can be None if
        digital_signature_algorithm is set.
    hash_algorithm (HashingAlgorithm): An enumeration specifying the
        hash algorithm to use for the signature operation. Can be None
        if digital_signature_algorithm is set.
    padding (PaddingMethod): An enumeration specifying the asymmetric
        padding method to use for the signature operation.
    signing_key (bytes): The bytes of the private key to use for the
        signature operation.
    data (bytes): The data to be signed.

Returns:
    signature (bytes): the bytes of the signature data

Raises:
    CryptographicFailure: Raised when an error occurs during signature
        creation.
    InvalidField: Raised when an unsupported hashing or cryptographic
        algorithm is specified.


def _create_rsa_key_pair(self, length, public_exponent=<NUM_LIT>):

self.logger.info(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>length, public_exponent<EOL>)<EOL>)<EOL>try:<EOL><INDENT>private_key = rsa.generate_private_key(<EOL>public_exponent=public_exponent,<EOL>key_size=length,<EOL>backend=default_backend())<EOL>public_key = private_key.public_key()<EOL>private_bytes = private_key.private_bytes(<EOL>serialization.Encoding.DER,<EOL>serialization.PrivateFormat.PKCS8,<EOL>serialization.NoEncryption())<EOL>public_bytes = public_key.public_bytes(<EOL>serialization.Encoding.DER,<EOL>serialization.PublicFormat.PKCS1)<EOL><DEDENT>except Exception as e:<EOL><INDENT>self.logger.exception(e)<EOL>raise exceptions.CryptographicFailure(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>public_key = {<EOL>'<STR_LIT:value>': public_bytes,<EOL>'<STR_LIT>': enums.KeyFormatType.PKCS_1,<EOL>'<STR_LIT>': public_exponent<EOL>}<EOL>private_key = {<EOL>'<STR_LIT:value>': private_bytes,<EOL>'<STR_LIT>': enums.KeyFormatType.PKCS_8,<EOL>'<STR_LIT>': public_exponent<EOL>}<EOL>return public_key, private_key<EOL>

Create an RSA key pair.

Args:
    length(int): The length of the keys to be created. This value must
        be compliant with the constraints of the provided algorithm.
    public_exponent(int): The value of the public exponent needed to
        generate the keys. Usually a small Fermat prime number.
        Optional, defaults to 65537.

Returns:
    dict: A dictionary containing the public key data, with the
        following key/value fields:
        * value - the bytes of the key
        * format - a KeyFormatType enumeration for the bytes format
        * public_exponent - the public exponent integer
    dict: A dictionary containing the private key data, identical in
        structure to the one above.

Raises:
    CryptographicFailure: Raised when the key generation process
        fails.


Encrypt data using symmetric or asymmetric encryption.

Args:
    encryption_algorithm (CryptographicAlgorithm): An enumeration
        specifying the encryption algorithm to use for encryption.
    encryption_key (bytes): The bytes of the encryption key to use for
        encryption.
    plain_text (bytes): The bytes to be encrypted.
    cipher_mode (BlockCipherMode): An enumeration specifying the
        block cipher mode to use with the encryption algorithm.
        Required in the general case. Optional if the encryption
        algorithm is RC4 (aka ARC4). If optional, defaults to None.
    padding_method (PaddingMethod): An enumeration specifying the
        padding method to use on the data before encryption. Required
        if the cipher mode is for block ciphers (e.g., CBC, ECB).
        Optional otherwise, defaults to None.
    iv_nonce (bytes): The IV/nonce value to use to initialize the mode
        of the encryption algorithm. Optional, defaults to None. If
        required and not provided, it will be autogenerated and
        returned with the cipher text.
    hashing_algorithm (HashingAlgorithm): An enumeration specifying
        the hashing algorithm to use with the encryption algorithm,
        if needed. Required for OAEP-based asymmetric encryption.
        Optional, defaults to None.

Returns:
    dict: A dictionary containing the encrypted data, with at least
        the following key/value fields:
        * cipher_text - the bytes of the encrypted data
        * iv_nonce - the bytes of the IV/counter/nonce used if it
            was needed by the encryption scheme and if it was
            automatically generated for the encryption

Raises:
    InvalidField: Raised when the algorithm is unsupported or the
        length is incompatible with the algorithm.
    CryptographicFailure: Raised when the key generation process
        fails.

Example:
    >>> engine = CryptographyEngine()
    >>> result = engine.encrypt(
    ...     encryption_algorithm=CryptographicAlgorithm.AES,
    ...     encryption_key=(
    ...         b'\xF3\x96\xE7\x1C\xCF\xCD\xEC\x1F'
    ...         b'\xFC\xE2\x8E\xA6\xF8\x74\x28\xB0'
    ...     ),
    ...     plain_text=(
    ...         b'\x00\x01\x02\x03\x04\x05\x06\x07'
    ...         b'\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F'
    ...     ),
    ...     cipher_mode=BlockCipherMode.CBC,
    ...     padding_method=PaddingMethod.ANSI_X923,
    ... )
    >>> result.get('cipher_text')
    b'\x18[\xb9y\x1bL\xd1\x8f\x9a\xa0e\x02b\xa3=c'
    >>> result.iv_counter_nonce
    b'8qA\x05\xc4\x86\x03\xd9=\xef\xdf\xb8ke\x9a\xa2'


self.logger = logging.getLogger('<STR_LIT>')<EOL>self._symmetric_key_algorithms = {<EOL>enums.CryptographicAlgorithm.TRIPLE_DES: algorithms.TripleDES,<EOL>enums.CryptographicAlgorithm.AES:        algorithms.AES,<EOL>enums.CryptographicAlgorithm.BLOWFISH:   algorithms.Blowfish,<EOL>enums.CryptographicAlgorithm.CAMELLIA:   algorithms.Camellia,<EOL>enums.CryptographicAlgorithm.CAST5:      algorithms.CAST5,<EOL>enums.CryptographicAlgorithm.IDEA:       algorithms.IDEA,<EOL>enums.CryptographicAlgorithm.RC4:        algorithms.ARC4<EOL>}<EOL>self._asymmetric_key_algorithms = {<EOL>enums.CryptographicAlgorithm.RSA: self._create_rsa_key_pair<EOL>}<EOL>self._hash_algorithms = {<EOL>enums.CryptographicAlgorithm.HMAC_SHA1: hashes.SHA1,<EOL>enums.CryptographicAlgorithm.HMAC_SHA224: hashes.SHA224,<EOL>enums.CryptographicAlgorithm.HMAC_SHA256: hashes.SHA256,<EOL>enums.CryptographicAlgorithm.HMAC_SHA384: hashes.SHA384,<EOL>enums.CryptographicAlgorithm.HMAC_SHA512: hashes.SHA512,<EOL>enums.CryptographicAlgorithm.HMAC_MD5: hashes.MD5<EOL>}<EOL>self._encryption_hash_algorithms = {<EOL>enums.HashingAlgorithm.MD5:     hashes.MD5,<EOL>enums.HashingAlgorithm.SHA_1:   hashes.SHA1,<EOL>enums.HashingAlgorithm.SHA_224: hashes.SHA224,<EOL>enums.HashingAlgorithm.SHA_256: hashes.SHA256,<EOL>enums.HashingAlgorithm.SHA_384: hashes.SHA384,<EOL>enums.HashingAlgorithm.SHA_512: hashes.SHA512<EOL>}<EOL>self._modes = {<EOL>enums.BlockCipherMode.CBC: modes.CBC,<EOL>enums.BlockCipherMode.ECB: modes.ECB,<EOL>enums.BlockCipherMode.OFB: modes.OFB,<EOL>enums.BlockCipherMode.CFB: modes.CFB,<EOL>enums.BlockCipherMode.CTR: modes.CTR<EOL>}<EOL>self._asymmetric_padding_methods = {<EOL>enums.PaddingMethod.OAEP:     asymmetric_padding.OAEP,<EOL>enums.PaddingMethod.PKCS1v15: asymmetric_padding.PKCS1v15,<EOL>enums.PaddingMethod.PSS:      asymmetric_padding.PSS<EOL>}<EOL>self._symmetric_padding_methods = {<EOL>enums.PaddingMethod.ANSI_X923: symmetric_padding.ANSIX923,<EOL>enums.PaddingMethod.PKCS5:     symmetric_padding.PKCS7<EOL>}<EOL>self._no_mode_needed = [<EOL>enums.CryptographicAlgorithm.RC4<EOL>]<EOL>self._no_padding_needed = [<EOL>enums.BlockCipherMode.CTR,<EOL>enums.BlockCipherMode.OFB,<EOL>enums.BlockCipherMode.CFB,<EOL>enums.BlockCipherMode.GCM<EOL>]<EOL>self._digital_signature_algorithms = {<EOL>enums.DigitalSignatureAlgorithm.MD5_WITH_RSA_ENCRYPTION:<EOL>(hashes.MD5, enums.CryptographicAlgorithm.RSA),<EOL>enums.DigitalSignatureAlgorithm.SHA1_WITH_RSA_ENCRYPTION:<EOL>(hashes.SHA1, enums.CryptographicAlgorithm.RSA),<EOL>enums.DigitalSignatureAlgorithm.SHA224_WITH_RSA_ENCRYPTION:<EOL>(hashes.SHA224, enums.CryptographicAlgorithm.RSA),<EOL>enums.DigitalSignatureAlgorithm.SHA256_WITH_RSA_ENCRYPTION:<EOL>(hashes.SHA256, enums.CryptographicAlgorithm.RSA),<EOL>enums.DigitalSignatureAlgorithm.SHA384_WITH_RSA_ENCRYPTION:<EOL>(hashes.SHA384, enums.CryptographicAlgorithm.RSA),<EOL>enums.DigitalSignatureAlgorithm.SHA512_WITH_RSA_ENCRYPTION:<EOL>(hashes.SHA512, enums.CryptographicAlgorithm.RSA)<EOL>}<EOL>


def __init__(self, policy_directory, policy_store, live_monitoring=True):

super(PolicyDirectoryMonitor, self).__init__()<EOL>self.halt_trigger = multiprocessing.Event()<EOL>self.policy_directory = policy_directory<EOL>self.live_monitoring = live_monitoring<EOL>self.file_timestamps = None<EOL>self.policy_cache = None<EOL>self.policy_files = None<EOL>self.policy_map = None<EOL>self.policy_store = policy_store<EOL>self.reserved_policies = ['<STR_LIT:default>', '<STR_LIT>']<EOL>def interrupt_handler(trigger, frame):<EOL><INDENT>self.stop()<EOL><DEDENT>signal.signal(signal.SIGINT, interrupt_handler)<EOL>signal.signal(signal.SIGTERM, interrupt_handler)<EOL>self.logger = logging.getLogger("<STR_LIT>")<EOL>self.initialize_tracking_structures()<EOL>

Set up the file monitor with the policy directory to track.

Args:
    policy_directory (string): The system path of the policy directory
        that should be monitored. Required.
    policy_store (DictProxy): A dictionary proxy created by the server
        multiprocessing resource manager. Used to store and share the
        policy information across server processes and threads.
        Required.
    live_monitoring (boolean): A boolean indicating whether or not
        live monitoring should continue indefinitely. Optional,
        defaults to True.


f = [os.path.join(p, x) for x in os.listdir(p) if x.endswith("<STR_LIT>")]<EOL>return sorted(f)<EOL>

Scan the provided policy directory for all JSON policy files.


The main thread routine executed by invoking thread.start.

This method manages the new client connection, running a message
handling loop. Once this method completes, the thread is finished.


operation = Operation(OperationEnum.DECRYPT)<EOL>request_payload = payloads.DecryptRequestPayload(<EOL>unique_identifier=unique_identifier,<EOL>data=data,<EOL>cryptographic_parameters=cryptographic_parameters,<EOL>iv_counter_nonce=iv_counter_nonce<EOL>)<EOL>batch_item = messages.RequestBatchItem(<EOL>operation=operation,<EOL>request_payload=request_payload<EOL>)<EOL>request = self._build_request_message(credential, [batch_item])<EOL>response = self._send_and_receive_message(request)<EOL>batch_item = response.batch_items[<NUM_LIT:0>]<EOL>payload = batch_item.response_payload<EOL>result = {}<EOL>if payload:<EOL><INDENT>result['<STR_LIT>'] = payload.unique_identifier<EOL>result['<STR_LIT:data>'] = payload.data<EOL><DEDENT>result['<STR_LIT>'] = batch_item.result_status.value<EOL>try:<EOL><INDENT>result['<STR_LIT>'] = batch_item.result_reason.value<EOL><DEDENT>except Exception:<EOL><INDENT>result['<STR_LIT>'] = batch_item.result_reason<EOL><DEDENT>try:<EOL><INDENT>result['<STR_LIT>'] = batch_item.result_message.value<EOL><DEDENT>except Exception:<EOL><INDENT>result['<STR_LIT>'] = batch_item.result_message<EOL><DEDENT>return result<EOL>

Decrypt data using the specified decryption key and parameters.

Args:
    data (bytes): The bytes to decrypt. Required.
    unique_identifier (string): The unique ID of the decryption key
        to use. Optional, defaults to None.
    cryptographic_parameters (CryptographicParameters): A structure
        containing various cryptographic settings to be used for the
        decryption. Optional, defaults to None.
    iv_counter_nonce (bytes): The bytes to use for the IV/counter/
        nonce, if needed by the decryption algorithm and/or cipher
        mode. Optional, defaults to None.
    credential (Credential): A credential object containing a set of
        authorization parameters for the operation. Optional, defaults
        to None.

Returns:
    dict: The results of the decrypt operation, containing the
        following key/value pairs:

        Key                 | Value
        --------------------|-----------------------------------------
        'unique_identifier' | (string) The unique ID of the decryption
                            | key used to decrypt the data.
        'data'              | (bytes) The decrypted data.
        'result_status'     | (ResultStatus) An enumeration indicating
                            | the status of the operation result.
        'result_reason'     | (ResultReason) An enumeration providing
                            | context for the result status.
        'result_message'    | (string) A message providing additional
                            | context for the operation result.


return authentication_suite in self.authentication_suites<EOL>

Check if an AuthenticationSuite is supported by the client.

Args:
    authentication_suite (AuthenticationSuite): An AuthenticationSuite
        enumeration to check against the list of supported
        AuthenticationSuites.

Returns:
    bool: True if the AuthenticationSuite is supported, False
        otherwise.

Example:
    >>> suite = AuthenticationSuite.BASIC
    >>> client.is_authentication_suite_supported(suite)
    True
    >>> suite = AuthenticationSuite.TLS12
    >>> client.is_authentication_suite_supported(suite)
    False


operation = Operation(OperationEnum.SIGNATURE_VERIFY)<EOL>request_payload = payloads.SignatureVerifyRequestPayload(<EOL>unique_identifier=unique_identifier,<EOL>cryptographic_parameters=cryptographic_parameters,<EOL>data=message,<EOL>signature_data=signature<EOL>)<EOL>batch_item = messages.RequestBatchItem(<EOL>operation=operation,<EOL>request_payload=request_payload<EOL>)<EOL>request = self._build_request_message(credential, [batch_item])<EOL>response = self._send_and_receive_message(request)<EOL>batch_item = response.batch_items[<NUM_LIT:0>]<EOL>payload = batch_item.response_payload<EOL>result = {}<EOL>if payload:<EOL><INDENT>result['<STR_LIT>'] = payload.unique_identifier<EOL>result['<STR_LIT>'] = payload.validity_indicator<EOL><DEDENT>result['<STR_LIT>'] = batch_item.result_status.value<EOL>try:<EOL><INDENT>result['<STR_LIT>'] = batch_item.result_reason.value<EOL><DEDENT>except Exception:<EOL><INDENT>result['<STR_LIT>'] = batch_item.result_reason<EOL><DEDENT>try:<EOL><INDENT>result['<STR_LIT>'] = batch_item.result_message.value<EOL><DEDENT>except Exception:<EOL><INDENT>result['<STR_LIT>'] = batch_item.result_message<EOL><DEDENT>return result<EOL>

Verify a message signature using the specified signing key.

Args:
    message (bytes): The bytes of the signed message. Required.
    signature (bytes): The bytes of the message signature. Required.
    unique_identifier (string): The unique ID of the signing key to
        use. Optional, defaults to None.
    cryptographic_parameters (CryptographicParameters): A structure
        containing various cryptographic settings to be used for
        signature verification. Optional, defaults to None.
    credential (Credential): A credential object containing a set of
        authorization parameters for the operation. Optional, defaults
        to None.

Returns:
    dict: The results of the signature verify operation, containing the
        following key/value pairs:

        Key                  | Value
        ---------------------|-----------------------------------------
        'unique_identifier'  | (string) The unique ID of the signing
                             | key used to verify the signature.
        'validity_indicator' | (ValidityIndicator) An enumeration
                             | indicating the result of signature
                             | verification.
        'result_status'      | (ResultStatus) An enumeration indicating
                             | the status of the operation result.
        'result_reason'      | (ResultReason) An enumeration providing
                             | context for the result status.
        'result_message'     | (string) A message providing additional
                             | context for the operation result.


batch_item = self._build_get_attribute_list_batch_item(uid)<EOL>request = self._build_request_message(None, [batch_item])<EOL>response = self._send_and_receive_message(request)<EOL>results = self._process_batch_items(response)<EOL>return results[<NUM_LIT:0>]<EOL>

Send a GetAttributeList request to the server.

Args:
    uid (string): The ID of the managed object with which the retrieved
        attribute names should be associated.

Returns:
    result (GetAttributeListResult): A structure containing the results
        of the operation.


return int if self._type == AggrType.count else float<EOL>

r"""Return type.

        * "count": :py:class:`int`
        * "other": :py:class:`float`


raise NotImplementedError("<STR_LIT>")<EOL>

Header of warning message.

        Returns:
            str


if not isinstance(obj, list):<EOL><INDENT>obj = [obj]<EOL><DEDENT>self.register(Descriptor.from_json(j) for j in obj)<EOL>

Register Descriptors from json descriptor objects.

        Parameters:
            obj(list or dict): descriptors to register


try:<EOL><INDENT>yield<EOL><DEDENT>except exception as e:<EOL><INDENT>self.fail(e)<EOL><DEDENT>

[contextmanager] treat any exceptions as known exception.


return (<EOL>isinstance(desc, type)<EOL>and issubclass(desc, Descriptor)<EOL>and (True if include_abstract else not inspect.isabstract(desc))<EOL>)<EOL>

r"""Check calculatable descriptor class or not.

    Returns:
        bool


raise MissingValueException(exception)<EOL>

Raise known exception and return missing value.

        Raises:
            MissingValueException


return ((k, v) for k, v in zip(self.keys(), self.values()))<EOL>

r"""Get items.

        Returns:
            Iterable[(Descriptor, value)]


return GetValueByIndex(self._values)<EOL>

r"""Access descriptor value by index.

        >>> from mordred import Calculator, Lipinski
        >>> from rdkit import Chem
        >>> result = Calculator(Lipinski.Lipinski)(Chem.MolFromSmiles("C1CCCCC1"))
        >>> result.ix[0]
        True


@classmethod<EOL><INDENT>def from_mol(cls, mol, conformer=-<NUM_LIT:1>, solvent_radius=<NUM_LIT>, level=<NUM_LIT:4>):<DEDENT>

rs = atoms_to_numpy(lambda a: vdw_radii[a.GetAtomicNum()] + solvent_radius, mol)<EOL>conf = mol.GetConformer(conformer)<EOL>ps = np.array([list(conf.GetAtomPosition(i)) for i in range(mol.GetNumAtoms())])<EOL>return cls(rs, ps, level)<EOL>

r"""Construct SurfaceArea from rdkit Mol type.

        :type mol: rdkit.Chem.Mol
        :param mol: input molecule

        :type conformer: int
        :param conformer: conformer id

        :type solvent_radius: float
        :param solvent_radius: solvent radius

        :type level: int
        :param level: mesh level

        :rtype: SurfaceArea


def __init__(self, url, access_token, index,<EOL>source="<STR_LIT>", verify=True, timeout=<NUM_LIT>):

url = urlparse(url)<EOL>self.url = "<STR_LIT>".format(url.scheme,<EOL>url.netloc)<EOL>self.access_token = access_token.lstrip("<STR_LIT>")<EOL>self.index = index<EOL>self.host = socket.getfqdn()<EOL>self.source = source<EOL>self.session = requests.Session()<EOL>self.timeout = timeout<EOL>self.session.verify = verify<EOL>self._common_data = dict(host=self.host, source=self.source,<EOL>index=self.index)<EOL>self.session.headers = {<EOL>"<STR_LIT>": "<STR_LIT>".format(__version__),<EOL>"<STR_LIT>": "<STR_LIT>".format(self.access_token)<EOL>}<EOL>

Initializes the HECClient
Args:
    url (str): The URL of the HEC
    access_token (str): The HEC access token
    index (str): The name of the index
    source (str): The source name
    verify (bool): Verify SSL certificates
    timeout (float): Number of seconds to wait for the server to send
    data before giving up


logger.debug("<STR_LIT>")<EOL>if type(aggregate_reports) == dict:<EOL><INDENT>aggregate_reports = [aggregate_reports]<EOL><DEDENT>if len(aggregate_reports) < <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>data = self._common_data.copy()<EOL>json_str = "<STR_LIT>"<EOL>for report in aggregate_reports:<EOL><INDENT>for record in report["<STR_LIT>"]:<EOL><INDENT>new_report = dict()<EOL>for metadata in report["<STR_LIT>"]:<EOL><INDENT>new_report[metadata] = report["<STR_LIT>"][metadata]<EOL><DEDENT>new_report["<STR_LIT>"] = report["<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT:source>"][<EOL>"<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT:source>"]["<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT:source>"][<EOL>"<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT:source>"][<EOL>"<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT:count>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT>"][<EOL>"<STR_LIT>"<EOL>]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT>"]["<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT>"]["<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT>"]["<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT>"][<EOL>"<STR_LIT>"]<EOL>new_report["<STR_LIT>"] = record["<STR_LIT>"][<EOL>"<STR_LIT>"]<EOL>if "<STR_LIT>" in record["<STR_LIT>"]:<EOL><INDENT>new_report["<STR_LIT>"] = record["<STR_LIT>"][<EOL>"<STR_LIT>"]<EOL><DEDENT>if "<STR_LIT>" in record["<STR_LIT>"]:<EOL><INDENT>new_report["<STR_LIT>"] = record["<STR_LIT>"][<EOL>"<STR_LIT>"]<EOL><DEDENT>data["<STR_LIT>"] = "<STR_LIT>"<EOL>timestamp = human_timestamp_to_timestamp(<EOL>new_report["<STR_LIT>"])<EOL>data["<STR_LIT:time>"] = timestamp<EOL>data["<STR_LIT>"] = new_report.copy()<EOL>json_str += "<STR_LIT>".format(json.dumps(data))<EOL><DEDENT><DEDENT>if not self.session.verify:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>response = self.session.post(self.url, data=json_str,<EOL>timeout=self.timeout)<EOL>response = response.json()<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise SplunkError(e.__str__())<EOL><DEDENT>if response["<STR_LIT:code>"] != <NUM_LIT:0>:<EOL><INDENT>raise SplunkError(response["<STR_LIT:text>"])<EOL><DEDENT>

Saves aggregate DMARC reports to Splunk

Args:
    aggregate_reports: A list of aggregate report dictionaries
    to save in Splunk


def set_hosts(hosts, use_ssl=False, ssl_cert_path=None):

if type(hosts) != list:<EOL><INDENT>hosts = [hosts]<EOL><DEDENT>conn_params = {<EOL>"<STR_LIT>": hosts,<EOL>"<STR_LIT>": <NUM_LIT:20><EOL>}<EOL>if use_ssl:<EOL><INDENT>conn_params['<STR_LIT>'] = True<EOL>if ssl_cert_path:<EOL><INDENT>conn_params['<STR_LIT>'] = True<EOL>conn_params['<STR_LIT>'] = ssl_cert_path<EOL><DEDENT>else:<EOL><INDENT>conn_params['<STR_LIT>'] = False<EOL><DEDENT><DEDENT>connections.create_connection(**conn_params)<EOL>

Sets the Elasticsearch hosts to use

Args:
    hosts (str): A single hostname or URL, or list of hostnames or URLs
    use_ssl (bool): Use a HTTPS connection to the server
    ssl_cert_path (str): Path to the certificate chain


psl_path = os.path.join(tempdir, "<STR_LIT>")<EOL>def download_psl():<EOL><INDENT>url = "<STR_LIT>"<EOL>headers = {"<STR_LIT>": USER_AGENT}<EOL>fresh_psl = requests.get(url, headers=headers).text<EOL>with open(psl_path, "<STR_LIT:w>", encoding="<STR_LIT:utf-8>") as fresh_psl_file:<EOL><INDENT>fresh_psl_file.write(fresh_psl)<EOL><DEDENT><DEDENT>if use_fresh_psl:<EOL><INDENT>if not os.path.exists(psl_path):<EOL><INDENT>download_psl()<EOL><DEDENT>else:<EOL><INDENT>psl_age = datetime.now() - datetime.fromtimestamp(<EOL>os.stat(psl_path).st_mtime)<EOL>if psl_age > timedelta(hours=<NUM_LIT>):<EOL><INDENT>try:<EOL><INDENT>download_psl()<EOL><DEDENT>except Exception as error:<EOL><INDENT>logger.warning(<EOL>"<STR_LIT>".format(error))<EOL><DEDENT><DEDENT><DEDENT>with open(psl_path, encoding="<STR_LIT:utf-8>") as psl_file:<EOL><INDENT>psl = publicsuffix2.PublicSuffixList(psl_file)<EOL><DEDENT>return psl.get_public_suffix(domain)<EOL><DEDENT>else:<EOL><INDENT>return publicsuffix2.get_public_suffix(domain)<EOL><DEDENT>

Gets the base domain name for the given domain

.. note::
    Results are based on a list of public domain suffixes at
    https://publicsuffix.org/list/public_suffix_list.dat.

Args:
    domain (str): A domain or subdomain
    use_fresh_psl (bool): Download a fresh Public Suffix List

Returns:
    str: The base domain of the given domain


invalid_filename_chars = ['<STR_LIT:\\>', '<STR_LIT:/>', '<STR_LIT::>', '<STR_LIT:">', '<STR_LIT:*>', '<STR_LIT:?>', '<STR_LIT:|>', '<STR_LIT:\n>',<EOL>'<STR_LIT:\r>']<EOL>if string is None:<EOL><INDENT>string = "<STR_LIT:None>"<EOL><DEDENT>for char in invalid_filename_chars:<EOL><INDENT>string = string.replace(char, "<STR_LIT>")<EOL><DEDENT>string = string.rstrip("<STR_LIT:.>")<EOL>return string<EOL>

Converts a string to a string that is safe for a filename
Args:
    string (str): A string to make safe for a filename

Returns:
    str: A string safe for a filename


<EOL>if not self._pool:<EOL><INDENT>self._pool = ThreadPoolExecutor(max_workers=self._max_workers)<EOL><DEDENT>old_future = self._pool.submit(query)<EOL>new_future = Future()<EOL>IOLoop.current().add_future(<EOL>old_future, lambda f: chain_future(f, new_future)<EOL>)<EOL>return new_future<EOL>

Wrap a `sqlalchemy.orm.query.Query` object into a
        `concurrent.futures.Future` so that it can be yielded.

        Parameters
        ----------
        query : sqlalchemy.orm.query.Query
            SQLAlchemy query object to execute

        Returns
        -------
            tornado.concurrent.Future
                A `Future` object wrapping the given query so that tornado can
                await/yield on it


def __exit__(self, exc_type, exc_val, exc_tbf):

self.run_time = time.time() - self._start_time<EOL>signal.setitimer(signal.ITIMER_PROF, <NUM_LIT:0>)<EOL>


with open(self._run_object, '<STR_LIT:rb>') as srcfile, _StatProfiler() as prof:<EOL><INDENT>code = compile(srcfile.read(), self._run_object, '<STR_LIT>')<EOL>prof.base_frame = inspect.currentframe()<EOL>try:<EOL><INDENT>exec(code, self._globs, None)<EOL><DEDENT>except SystemExit:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>call_tree = prof.call_tree<EOL>return {<EOL>'<STR_LIT>': self._object_name,<EOL>'<STR_LIT>': _SAMPLE_INTERVAL,<EOL>'<STR_LIT>': prof.run_time,<EOL>'<STR_LIT>': call_tree,<EOL>'<STR_LIT>': call_tree.get('<STR_LIT>', <NUM_LIT:0>),<EOL>'<STR_LIT>': int(time.time())<EOL>}<EOL>


res_filename = os.path.join(<EOL>os.path.dirname(__file__), _PROFILE_HTML)<EOL>with io.open(res_filename, '<STR_LIT:rb>') as res_file:<EOL><INDENT>content = res_file.read()<EOL><DEDENT>return content, '<STR_LIT>'<EOL>


result = []<EOL>regex = re.compile(r'<STR_LIT>')<EOL>for obj_type, obj_count in objects.items():<EOL><INDENT>if obj_count != <NUM_LIT:0>:<EOL><INDENT>match = re.findall(regex, repr(obj_type))<EOL>if match:<EOL><INDENT>obj_type, obj_name = match[<NUM_LIT:0>]<EOL>result.append(("<STR_LIT>" % (obj_type, obj_name), obj_count))<EOL><DEDENT><DEDENT><DEDENT>return sorted(result, key=operator.itemgetter(<NUM_LIT:1>), reverse=True)<EOL>


sys.settrace(self.original_trace_function)<EOL>if self.prev_timestamp:<EOL><INDENT>runtime = time.time() - self.prev_timestamp<EOL>self.lines.append([self.prev_path, self.prev_lineno, runtime])<EOL><DEDENT>


def _format_heatmap(self, filename, heatmap, execution_count):

with open(filename) as src_file:<EOL><INDENT>file_source = src_file.read().split('<STR_LIT:\n>')<EOL>skip_map = self._calc_skips(heatmap, len(file_source))<EOL><DEDENT>run_time = sum(time for time in heatmap.values())<EOL>return {<EOL>'<STR_LIT:name>': filename,<EOL>'<STR_LIT>': heatmap,<EOL>'<STR_LIT>': execution_count,<EOL>'<STR_LIT>': self._skip_lines(file_source, skip_map),<EOL>'<STR_LIT>': run_time<EOL>}<EOL>


prev_line = None<EOL>current_module_path = inspect.getabsfile(inspect.currentframe())<EOL>for module_path, lineno, runtime in self.lines:<EOL><INDENT>module_abspath = os.path.abspath(module_path)<EOL>if not prev_line:<EOL><INDENT>prev_line = [module_abspath, lineno, runtime]<EOL><DEDENT>else:<EOL><INDENT>if (not check_standard_dir(module_path) and<EOL>module_abspath != current_module_path):<EOL><INDENT>yield prev_line<EOL>prev_line = [module_abspath, lineno, runtime]<EOL><DEDENT>else:<EOL><INDENT>prev_line[<NUM_LIT:2>] += runtime<EOL><DEDENT><DEDENT><DEDENT>yield prev_line<EOL>

Filters code from standard library from self.lines.


with _CodeHeatmapCalculator() as prof:<EOL><INDENT>result = self._run_object(*self._run_args, **self._run_kwargs)<EOL><DEDENT>code_lines, start_line = inspect.getsourcelines(self._run_object)<EOL>source_lines = []<EOL>for line in code_lines:<EOL><INDENT>source_lines.append(('<STR_LIT>', start_line, line))<EOL>start_line += <NUM_LIT:1><EOL><DEDENT>filename = os.path.abspath(inspect.getsourcefile(self._run_object))<EOL>heatmap = prof.heatmap[filename]<EOL>run_time = sum(time for time in heatmap.values())<EOL>return {<EOL>'<STR_LIT>': self._object_name,<EOL>'<STR_LIT>': run_time,<EOL>'<STR_LIT:result>': result,<EOL>'<STR_LIT>': int(time.time()),<EOL>'<STR_LIT>': [{<EOL>'<STR_LIT:name>': self._object_name,<EOL>'<STR_LIT>': heatmap,<EOL>'<STR_LIT>': prof.execution_count[filename],<EOL>'<STR_LIT>': source_lines,<EOL>'<STR_LIT>': run_time<EOL>}]<EOL>}<EOL>


if not self._heatmap:<EOL><INDENT>self.fill_heatmap()<EOL><DEDENT>return self._heatmap<EOL>

Returns heatmap with absolute path names.


def record_line(self, frame, event, arg):

if event == '<STR_LIT>':<EOL><INDENT>if self.prev_timestamp:<EOL><INDENT>runtime = time.time() - self.prev_timestamp<EOL>self.lines.append([self.prev_path, self.prev_lineno, runtime])<EOL><DEDENT>self.prev_lineno = frame.f_lineno<EOL>self.prev_path = frame.f_code.co_filename<EOL>self.prev_timestamp = time.time()<EOL><DEDENT>return self.record_line<EOL>


records = []<EOL>for info, params in prof.stats.items():<EOL><INDENT>filename, lineno, funcname = info<EOL>cum_calls, num_calls, time_per_call, cum_time, _ = params<EOL>if prof.total_tt == <NUM_LIT:0>:<EOL><INDENT>percentage = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>percentage = round(<NUM_LIT:100> * (cum_time / prof.total_tt), <NUM_LIT:4>)<EOL><DEDENT>cum_time = round(cum_time, <NUM_LIT:4>)<EOL>func_name = '<STR_LIT>' % (funcname, filename)<EOL>color_hash = base_profiler.hash_name(func_name)<EOL>records.append(<EOL>(filename, lineno, funcname, cum_time, percentage, num_calls,<EOL>cum_calls, time_per_call, filename, color_hash))<EOL><DEDENT>return sorted(records, key=operator.itemgetter(<NUM_LIT:4>), reverse=True)<EOL>


prof = cProfile.Profile()<EOL>prof.enable()<EOL>result = self._run_object(*self._run_args, **self._run_kwargs)<EOL>prof.disable()<EOL>prof_stats = pstats.Stats(prof)<EOL>prof_stats.calc_callees()<EOL>return {<EOL>'<STR_LIT>': self._object_name,<EOL>'<STR_LIT>': self._transform_stats(prof_stats),<EOL>'<STR_LIT>': prof_stats.total_tt,<EOL>'<STR_LIT>': prof_stats.prim_calls,<EOL>'<STR_LIT>': prof_stats.total_calls,<EOL>'<STR_LIT:result>': result,<EOL>'<STR_LIT>': int(time.time())<EOL>}<EOL>


return base_profiler.run_in_separate_process(self._profile_package)<EOL>

Runs package profiler in separate process.


return self.result._getvalue()<EOL>


raise NotImplementedError<EOL>

Profiles function.

        Runs object self._run_object as a Python function.
        Must be overridden.


return zlib.adler32(name.encode('<STR_LIT:utf-8>'))<EOL>