# Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# Generated Thu Apr 11 15:06:25 2013 by generateDS.py version 2.9a.
#

import sys
import getopt
import re as re_

import cybox.bindings.cybox_core as cybox_core_binding
import stix.bindings.stix_common as stix_common_binding
import stix.bindings.data_marking as data_marking_binding

import base64
from datetime import datetime, tzinfo, timedelta

XML_NS  = "http://stix.mitre.org/Indicator-2"

etree_ = None
Verbose_import_ = False
(   XMLParser_import_none, XMLParser_import_lxml,
    XMLParser_import_elementtree
    ) = range(3)
XMLParser_import_library = None

# lxml
from lxml import etree as etree_
XMLParser_import_library = XMLParser_import_lxml
if Verbose_import_:
    print("running with lxml.etree")


def parsexml_(*args, **kwargs):
    if (XMLParser_import_library == XMLParser_import_lxml and
        'parser' not in kwargs):
        # Use the lxml ElementTree compatible parser so that, e.g.,
        #   we ignore comments.
        kwargs['parser'] = etree_.ETCompatXMLParser()
    doc = etree_.parse(*args, **kwargs)
    return doc

#
# User methods
#
# Calls to the methods in these classes are generated by generateDS.py.
# You can replace these methods by re-implementing the following class
#   in a module named generatedssuper.py.

try:
    from generatedssuper import GeneratedsSuper
except ImportError, exp:

    class GeneratedsSuper(object):
        tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$')
        class _FixedOffsetTZ(tzinfo):
            def __init__(self, offset, name):
                self.__offset = timedelta(minutes = offset)
                self.__name = name
            def utcoffset(self, dt):
                return self.__offset
            def tzname(self, dt):
                return self.__name
            def dst(self, dt):
                return None
        def gds_format_string(self, input_data, input_name=''):
            return input_data
        def gds_validate_string(self, input_data, node, input_name=''):
            return input_data
        def gds_format_base64(self, input_data, input_name=''):
            return base64.b64encode(input_data)
        def gds_validate_base64(self, input_data, node, input_name=''):
            return input_data
        def gds_format_integer(self, input_data, input_name=''):
            return '%d' % input_data
        def gds_validate_integer(self, input_data, node, input_name=''):
            return input_data
        def gds_format_integer_list(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_integer_list(self, input_data, node, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    fvalue = float(value)
                except (TypeError, ValueError), exp:
                    raise_parse_error(node, 'Requires sequence of integers')
            return input_data
        def gds_format_float(self, input_data, input_name=''):
            return '%f' % input_data
        def gds_validate_float(self, input_data, node, input_name=''):
            return input_data
        def gds_format_float_list(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_float_list(self, input_data, node, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    fvalue = float(value)
                except (TypeError, ValueError), exp:
                    raise_parse_error(node, 'Requires sequence of floats')
            return input_data
        def gds_format_double(self, input_data, input_name=''):
            return '%e' % input_data
        def gds_validate_double(self, input_data, node, input_name=''):
            return input_data
        def gds_format_double_list(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_double_list(self, input_data, node, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    fvalue = float(value)
                except (TypeError, ValueError), exp:
                    raise_parse_error(node, 'Requires sequence of doubles')
            return input_data
        def gds_format_boolean(self, input_data, input_name=''):
            return ('%s' % input_data).lower()
        def gds_validate_boolean(self, input_data, node, input_name=''):
            return input_data
        def gds_format_boolean_list(self, input_data, input_name=''):
            return '%s' % input_data
        def gds_validate_boolean_list(self, input_data, node, input_name=''):
            values = input_data.split()
            for value in values:
                if value not in ('true', '1', 'false', '0', ):
                    raise_parse_error(node,
                        'Requires sequence of booleans '
                        '("true", "1", "false", "0")')
            return input_data
        def gds_validate_datetime(self, input_data, node, input_name=''):
            return input_data
        def gds_format_datetime(self, input_data, input_name=''):
            if input_data.microsecond == 0:
                _svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S')
            else:
                _svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S.%f')
            if input_data.tzinfo is not None:
                tzoff = input_data.tzinfo.utcoffset(input_data)
                if tzoff is not None:
                    total_seconds = tzoff.seconds + (86400 * tzoff.days)
                    if total_seconds == 0:
                        _svalue += 'Z'
                    else:
                        if total_seconds < 0:
                            _svalue += '-'
                            total_seconds *= -1
                        else:
                            _svalue += '+'
                        hours = total_seconds // 3600
                        minutes = (total_seconds - (hours * 3600)) // 60
                        _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
            return _svalue
        def gds_parse_datetime(self, input_data, node, input_name=''):
            tz = None
            if input_data[-1] == 'Z':
                tz = GeneratedsSuper._FixedOffsetTZ(0, 'GMT')
                input_data = input_data[:-1]
            else:
                results = GeneratedsSuper.tzoff_pattern.search(input_data)
                if results is not None:
                    tzoff_parts = results.group(2).split(':')
                    tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
                    if results.group(1) == '-':
                        tzoff *= -1
                    tz = GeneratedsSuper._FixedOffsetTZ(
                        tzoff, results.group(0))
                    input_data = input_data[:-6]
            if len(input_data.split('.')) > 1:
                dt = datetime.strptime(
                        input_data, '%Y-%m-%dT%H:%M:%S.%f')
            else:
                dt = datetime.strptime(
                        input_data, '%Y-%m-%dT%H:%M:%S')
            return dt.replace(tzinfo = tz)

        def gds_validate_date(self, input_data, node, input_name=''):
            return input_data
        def gds_format_date(self, input_data, input_name=''):
            _svalue = input_data.strftime('%Y-%m-%d')
            if input_data.tzinfo is not None:
                tzoff = input_data.tzinfo.utcoffset(input_data)
                if tzoff is not None:
                    total_seconds = tzoff.seconds + (86400 * tzoff.days)
                    if total_seconds == 0:
                        _svalue += 'Z'
                    else:
                        if total_seconds < 0:
                            _svalue += '-'
                            total_seconds *= -1
                        else:
                            _svalue += '+'
                        hours = total_seconds // 3600
                        minutes = (total_seconds - (hours * 3600)) // 60
                        _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
            return _svalue
        def gds_parse_date(self, input_data, node, input_name=''):
            tz = None
            if input_data[-1] == 'Z':
                tz = GeneratedsSuper._FixedOffsetTZ(0, 'GMT')
                input_data = input_data[:-1]
            else:
                results = GeneratedsSuper.tzoff_pattern.search(input_data)
                if results is not None:
                    tzoff_parts = results.group(2).split(':')
                    tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
                    if results.group(1) == '-':
                        tzoff *= -1
                    tz = GeneratedsSuper._FixedOffsetTZ(
                        tzoff, results.group(0))
                    input_data = input_data[:-6]
            return datetime.strptime(input_data,
                '%Y-%m-%d').replace(tzinfo = tz)
        def gds_str_lower(self, instring):
            return instring.lower()
        def get_path_(self, node):
            path_list = []
            self.get_path_list_(node, path_list)
            path_list.reverse()
            path = '/'.join(path_list)
            return path
        Tag_strip_pattern_ = re_.compile(r'\{.*\}')
        def get_path_list_(self, node, path_list):
            if node is None:
                return
            tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
            if tag:
                path_list.append(tag)
            self.get_path_list_(node.getparent(), path_list)
        def get_class_obj_(self, node, default_class=None):
            class_obj1 = default_class
            if 'xsi' in node.nsmap:
                classname = node.get('{%s}type' % node.nsmap['xsi'])
                if classname is not None:
                    names = classname.split(':')
                    if len(names) == 2:
                        classname = names[1]
                    class_obj2 = globals().get(classname)
                    if class_obj2 is not None:
                        class_obj1 = class_obj2
            return class_obj1
        def gds_build_any(self, node, type_name=None):
            return None


#
# If you have installed IPython you can uncomment and use the following.
# IPython is available from http://ipython.scipy.org/.
#

## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
##     banner = 'Dropping into IPython',
##     exit_msg = 'Leaving Interpreter, back to program.')

# Then use the following line where and when you want to drop into the
# IPython shell:
#    ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')

#
# Globals
#

ExternalEncoding = 'utf-8'
Tag_pattern_ = re_.compile(r'({.*})?(.*)')
String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')

#
# Support/utility functions.
#

def showIndent(outfile, level, pretty_print=True):
    if pretty_print:
        for idx in range(level):
            outfile.write('    ')

def quote_xml(inStr):
    if not inStr:
        return ''
    s1 = (isinstance(inStr, basestring) and inStr or
          '%s' % inStr)
    s1 = s1.replace('&', '&amp;')
    s1 = s1.replace('<', '&lt;')
    s1 = s1.replace('>', '&gt;')
    return s1

def quote_attrib(inStr):
    s1 = (isinstance(inStr, basestring) and inStr or
          '%s' % inStr)
    s1 = s1.replace('&', '&amp;')
    s1 = s1.replace('<', '&lt;')
    s1 = s1.replace('>', '&gt;')
    if '"' in s1:
        if "'" in s1:
            s1 = '"%s"' % s1.replace('"', "&quot;")
        else:
            s1 = "'%s'" % s1
    else:
        s1 = '"%s"' % s1
    return s1

def quote_python(inStr):
    s1 = inStr
    if s1.find("'") == -1:
        if s1.find('\n') == -1:
            return "'%s'" % s1
        else:
            return "'''%s'''" % s1
    else:
        if s1.find('"') != -1:
            s1 = s1.replace('"', '\\"')
        if s1.find('\n') == -1:
            return '"%s"' % s1
        else:
            return '"""%s"""' % s1

def get_all_text_(node):
    if node.text is not None:
        text = node.text
    else:
        text = ''
    for child in node:
        if child.tail is not None:
            text += child.tail
    return text

def find_attr_value_(attr_name, node):
    attrs = node.attrib
    attr_parts = attr_name.split(':')
    value = None
    if len(attr_parts) == 1:
        value = attrs.get(attr_name)
    elif len(attr_parts) == 2:
        prefix, name = attr_parts
        namespace = node.nsmap.get(prefix)
        if namespace is not None:
            value = attrs.get('{%s}%s' % (namespace, name, ))
    return value


class GDSParseError(Exception):
    pass

def raise_parse_error(node, msg):
    if XMLParser_import_library == XMLParser_import_lxml:
        msg = '%s (element %s/line %d)' % (
            msg, node.tag, node.sourceline, )
    else:
        msg = '%s (element %s)' % (msg, node.tag, )
    raise GDSParseError(msg)


class MixedContainer:
    # Constants for category:
    CategoryNone = 0
    CategoryText = 1
    CategorySimple = 2
    CategoryComplex = 3
    # Constants for content_type:
    TypeNone = 0
    TypeText = 1
    TypeString = 2
    TypeInteger = 3
    TypeFloat = 4
    TypeDecimal = 5
    TypeDouble = 6
    TypeBoolean = 7
    TypeBase64 = 8
    def __init__(self, category, content_type, name, value):
        self.category = category
        self.content_type = content_type
        self.name = name
        self.value = value
    def getCategory(self):
        return self.category
    def getContenttype(self, content_type):
        return self.content_type
    def getValue(self):
        return self.value
    def getName(self):
        return self.name
    def export(self, outfile, level, name, namespace, pretty_print=True):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                outfile.write(self.value)
        elif self.category == MixedContainer.CategorySimple:
            self.exportSimple(outfile, level, name)
        else:    # category == MixedContainer.CategoryComplex
            self.value.export(outfile, level, namespace, name, pretty_print)
    def exportSimple(self, outfile, level, name):
        if self.content_type == MixedContainer.TypeString:
            outfile.write('<%s>%s</%s>' %
                (self.name, self.value, self.name))
        elif self.content_type == MixedContainer.TypeInteger or \
                self.content_type == MixedContainer.TypeBoolean:
            outfile.write('<%s>%d</%s>' %
                (self.name, self.value, self.name))
        elif self.content_type == MixedContainer.TypeFloat or \
                self.content_type == MixedContainer.TypeDecimal:
            outfile.write('<%s>%f</%s>' %
                (self.name, self.value, self.name))
        elif self.content_type == MixedContainer.TypeDouble:
            outfile.write('<%s>%g</%s>' %
                (self.name, self.value, self.name))
        elif self.content_type == MixedContainer.TypeBase64:
            outfile.write('<%s>%s</%s>' %
                (self.name, base64.b64encode(self.value), self.name))
    def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
    def to_etree_simple(self):
        if self.content_type == MixedContainer.TypeString:
            text = self.value
        elif (self.content_type == MixedContainer.TypeInteger or
                self.content_type == MixedContainer.TypeBoolean):
            text = '%d' % self.value
        elif (self.content_type == MixedContainer.TypeFloat or
                self.content_type == MixedContainer.TypeDecimal):
            text = '%f' % self.value
        elif self.content_type == MixedContainer.TypeDouble:
            text = '%g' % self.value
        elif self.content_type == MixedContainer.TypeBase64:
            text = '%s' % base64.b64encode(self.value)
        return text
    def exportLiteral(self, outfile, level, name):
        if self.category == MixedContainer.CategoryText:
            showIndent(outfile, level)
            outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n'
                % (self.category, self.content_type, self.name, self.value))
        elif self.category == MixedContainer.CategorySimple:
            showIndent(outfile, level)
            outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n'
                % (self.category, self.content_type, self.name, self.value))
        else:    # category == MixedContainer.CategoryComplex
            showIndent(outfile, level)
            outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \
                (self.category, self.content_type, self.name,))
            self.value.exportLiteral(outfile, level + 1)
            showIndent(outfile, level)
            outfile.write(')\n')


class MemberSpec_(object):
    def __init__(self, name='', data_type='', container=0):
        self.name = name
        self.data_type = data_type
        self.container = container
    def set_name(self, name): self.name = name
    def get_name(self): return self.name
    def set_data_type(self, data_type): self.data_type = data_type
    def get_data_type_chain(self): return self.data_type
    def get_data_type(self):
        if isinstance(self.data_type, list):
            if len(self.data_type) > 0:
                return self.data_type[-1]
            else:
                return 'xs:string'
        else:
            return self.data_type
    def set_container(self, container): self.container = container
    def get_container(self): return self.container

def _cast(typ, value):
    if typ is None or value is None:
        return value
    return typ(value)

#
# Data representation classes.
#

class ValidTimeType(GeneratedsSuper):
    """A basic representation of a temporal window when the thing (e.g.,
    indicator) is valid."""
    subclass = None
    superclass = None
    def __init__(self, Start_Time=None, End_Time=None):
        self.Start_Time = Start_Time
        self.End_Time = End_Time
    def factory(*args_, **kwargs_):
        if ValidTimeType.subclass:
            return ValidTimeType.subclass(*args_, **kwargs_)
        else:
            return ValidTimeType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Start_Time(self): return self.Start_Time
    def set_Start_Time(self, Start_Time): self.Start_Time = Start_Time
    def get_End_Time(self): return self.End_Time
    def set_End_Time(self, End_Time): self.End_Time = End_Time
    def hasContent_(self):
        if (
            self.Start_Time is not None or
            self.End_Time is not None
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='ValidTimeType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='ValidTimeType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_=XML_NS, name_='ValidTimeType'):
        pass
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='ValidTimeType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.Start_Time is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%s:Start_Time>%s</%s:Start_Time>%s' % (nsmap[namespace_], self.gds_format_datetime(self.Start_Time, input_name='Start_Time'), nsmap[namespace_], eol_))
        if self.End_Time is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%s:End_Time>%s</%s:End_Time>%s' % (nsmap[namespace_], self.gds_format_datetime(self.End_Time, input_name='End_Time'), nsmap[namespace_], eol_))
    def exportLiteral(self, outfile, level, name_='ValidTimeType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        pass
    def exportLiteralChildren(self, outfile, level, name_):
        if self.Start_Time is not None:
            showIndent(outfile, level)
            outfile.write('Start_Time=datetime_.strptime("%s", "%%Y-%%m-%%dT%%H:%%M:%%S"),\n' % self.gds_format_datetime(self.Start_Time, input_name='Start_Time'))
        if self.End_Time is not None:
            showIndent(outfile, level)
            outfile.write('End_Time=datetime_.strptime("%s", "%%Y-%%m-%%dT%%H:%%M:%%S"),\n' % self.gds_format_datetime(self.End_Time, input_name='End_Time'))
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        pass
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Start_Time':
            sval_ = child_.text
            dval_ = self.gds_parse_datetime(sval_, node, 'Start_Time')
            self.Start_Time = dval_
        elif nodeName_ == 'End_Time':
            sval_ = child_.text
            dval_ = self.gds_parse_datetime(sval_, node, 'End_Time')
            self.End_Time = dval_
# end class ValidTimeType

class CompositeIndicatorExpressionType(GeneratedsSuper):
    """Type for allowing content creators to create composite indicator
    expressions using basic boolean logic. Specifies the logical
    composition operator for this composite cyber threat Indicator."""
    subclass = None
    superclass = None
    def __init__(self, operator=None, Indicator=None):
        self.operator = _cast(None, operator)
        if Indicator is None:
            self.Indicator = []
        else:
            self.Indicator = Indicator
    def factory(*args_, **kwargs_):
        if CompositeIndicatorExpressionType.subclass:
            return CompositeIndicatorExpressionType.subclass(*args_, **kwargs_)
        else:
            return CompositeIndicatorExpressionType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Indicator(self): return self.Indicator
    def set_Indicator(self, Indicator): self.Indicator = Indicator
    def add_Indicator(self, value): self.Indicator.append(value)
    def insert_Indicator(self, index, value): self.Indicator[index] = value
    def get_operator(self): return self.operator
    def set_operator(self, operator): self.operator = operator
    def hasContent_(self):
        if (
            self.Indicator
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='CompositeIndicatorExpressionType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='CompositeIndicatorExpressionType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_=XML_NS, name_='CompositeIndicatorExpressionType'):
        if self.operator is not None and 'operator' not in already_processed:
            already_processed.add('operator')
            outfile.write(' operator=%s' % (quote_attrib(self.operator), ))
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='CompositeIndicatorExpressionType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Indicator_ in self.Indicator:
            Indicator_.export(outfile, level, nsmap, namespace_, name_='Indicator', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='CompositeIndicatorExpressionType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.operator is not None and 'operator' not in already_processed:
            already_processed.add('operator')
            showIndent(outfile, level)
            outfile.write('operator = %s,\n' % (self.operator,))
    def exportLiteralChildren(self, outfile, level, name_):
        showIndent(outfile, level)
        outfile.write('Indicator=[\n')
        level += 1
        for Indicator_ in self.Indicator:
            outfile.write('model_.Indicator(\n')
            Indicator_.exportLiteral(outfile, level)
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('operator', node)
        if value is not None and 'operator' not in already_processed:
            already_processed.add('operator')
            self.operator = value
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Indicator':
            obj_ = IndicatorType.factory()
            obj_.build(child_)
            self.Indicator.append(obj_)
# end class CompositeIndicatorExpressionType

class TestMechanismType(GeneratedsSuper):
    """The TestMechanismType specifies a non-standard Test Mechanism
    effective at identifying the cyber Observables specified in this
    cyber threat Indicator. This type is defined as abstract and is
    intended to be extended to enable the expression of any
    structured or unstructured test mechanism. STIX provides five
    default options, Generic, OpenIOC, OVAL, Snort, and YARA.
    Additionally, those who wish to use another format may do so by
    using either the existing Generic test mechanism and putting the
    mechanism specification in the CDATA block or by defining a new
    extension to this type. The information for the STIX-provided
    extensions is: 1. Generic: The Generic test mechanism allows for
    the specification of any generic test mechanism through the use
    of a raw CDATA section. The type is named
    GenericTestMechanismType and is in the
    http://stix.mitre.org/extensions/TestMechanism#Generic-1
    namespace. The extension is defined in the file
    extensions/test_mechanism/generic.xsd or at the URL http://stix.
    mitre.org/XMLSchema/extensions/test_mechanism/generic/1.0/generi
    c.xsd. 2. OpenIOC: The OpenIOC test mechanism allows for the
    specification of an OpenIOC test by importing the OpenIOC
    schema. The type is named IOCTestMechanismType and is in the
    http://stix.mitre.org/extensions/TestMechanism#OpenIOC-1
    namespace. The extension is defined in the file
    extensions/test_mechanism/openioc-1.0.xsd or at the URL http://s
    tix.mitre.org/XMLSchema/extensions/test_mechanism/openioc-1.0/1.
    0/openioc-1.0.xsd. 3. OVAL: The OVAL test mechanism allows for
    the specification of an OVAL definition through importing the
    OVAL schemas. The type is named OVALTestMechanismType and is in
    the http://stix.mitre.org/extensions/TestMechanism#OVAL-1
    namespace. The extension is defined in the file
    extensions/test_mechanism/oval-5.10.1.xsd or at the URL http://s
    tix.mitre.org/XMLSchema/extensions/test_mechanism/oval-5.10.1/1.
    0/oval-5.10.1.xsd. 4. Snort: The Snort test mechanism allows for
    the specification of a snort signature through the use of a raw
    CDATA section. The type is named SnortTestMechanismType and is
    in the http://stix.mitre.org/extensions/TestMechanism#Snort-1
    namespace. The extension is defined in the file
    extensions/test_mechanism/snort.xsd or at the URL http://stix.mi
    tre.org/XMLSchema/extensions/test_mechanism/snort/1.0/snort.xsd.
    5. YARA: The YARA test mechanism allows for the specification of
    a YARA test through the use of a raw CDATA section. The type is
    named YaraTestMechanismType and is in the
    http://stix.mitre.org/extensions/TestMechanism#YARA-1 namespace.
    The extension is defined in the file
    extensions/test_mechanism/yara.xsd or at the URL http://stix.mit
    re.org/XMLSchema/extensions/test_mechanism/yara/1.0/yara.xsd.
    Specifies a unique ID for this Test Mechanism.Specifies a
    reference to the ID of a Test Mechanism specified elsewhere."""
    subclass = None
    superclass = None
    def __init__(self, idref=None, id=None, Efficacy=None, Producer=None, xsi_type=None):
        self.idref = _cast(None, idref)
        self.id = _cast(None, id)
        self.Efficacy = Efficacy
        self.Producer = Producer
        self.xsi_type = xsi_type
    def factory(*args_, **kwargs_):
        if TestMechanismType.subclass:
            return TestMechanismType.subclass(*args_, **kwargs_)
        else:
            return TestMechanismType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Efficacy(self): return self.Efficacy
    def set_Efficacy(self, Efficacy): self.Efficacy = Efficacy
    def get_Producer(self): return self.Producer
    def set_Producer(self, Producer): self.Producer = Producer
    def get_idref(self): return self.idref
    def set_idref(self, idref): self.idref = idref
    def get_id(self): return self.id
    def set_id(self, id): self.id = id
    def get_xsi_type(self): return self.xsi_type
    def set_xsi_type(self, xsi_type): self.xsi_type = xsi_type
    def hasContent_(self):
        if (
            self.Efficacy is not None and
            self.Producer is not None
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='TestMechanismType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='TestMechanismType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='indicator:', name_='TestMechanismType'):
        if self.idref is not None and 'idref' not in already_processed:
            already_processed.add('idref')
            outfile.write(' idref=%s' % (quote_attrib(self.idref), ))
        if self.id is not None and 'id' not in already_processed:
            already_processed.add('id')
            outfile.write(' id=%s' % (quote_attrib(self.id), ))
        #=======================================================================
        # if self.xsi_type is not None and 'xsi:type' not in already_processed:
        #    already_processed.add('xsi:type')
        #    outfile.write('  xsi:type="%s"' % self.xsi_type)
        #=======================================================================
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='TestMechanismType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.Efficacy is not None:
            self.Efficacy.export(outfile, level, nsmap, namespace_, name_='Efficacy', pretty_print=pretty_print)
        if self.Producer is not None:
            self.Producer.export(outfile, level, nsmap, namespace_, name_='Producer', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='TestMechanismType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.idref is not None and 'idref' not in already_processed:
            already_processed.add('idref')
            showIndent(outfile, level)
            outfile.write('idref = %s,\n' % (self.idref,))
        if self.id is not None and 'id' not in already_processed:
            already_processed.add('id')
            showIndent(outfile, level)
            outfile.write('id = %s,\n' % (self.id,))
    def exportLiteralChildren(self, outfile, level, name_):
        if self.Efficacy is not None:
            outfile.write('Efficacy=model_.stix_common_binding.StatementType(\n')
            self.Efficacy.exportLiteral(outfile, level, name_='Efficacy')
            outfile.write('),\n')
        if self.Producer is not None:
            outfile.write('Producer=model_.stix_common_binding.InformationSourceType(\n')
            self.Producer.exportLiteral(outfile, level, name_='Producer')
            outfile.write('),\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('idref', node)
        if value is not None and 'idref' not in already_processed:
            already_processed.add('idref')
            self.idref = value
        value = find_attr_value_('id', node)
        if value is not None and 'id' not in already_processed:
            already_processed.add('id')
            self.id = value
        #=======================================================================
        # value = find_attr_value_('xsi:type', node)
        # if value is not None and 'xsi:type' not in already_processed:
        #    already_processed.add('xsi:type')
        #    self.xsi_type = value
        #=======================================================================
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Efficacy':
            obj_ = stix_common_binding.StatementType.factory()
            obj_.build(child_)
            self.set_Efficacy(obj_)
        elif nodeName_ == 'Producer':
            obj_ = stix_common_binding.InformationSourceType.factory()
            obj_.build(child_)
            self.set_Producer(obj_)
# end class TestMechanismType

class SightingsType(GeneratedsSuper):
    """The total number of times this Indicator was reported as sighted."""
    subclass = None
    superclass = None
    def __init__(self, sightings_count=None, Sighting=None):
        self.sightings_count = _cast(int, sightings_count)
        if Sighting is None:
            self.Sighting = []
        else:
            self.Sighting = Sighting
    def factory(*args_, **kwargs_):
        if SightingsType.subclass:
            return SightingsType.subclass(*args_, **kwargs_)
        else:
            return SightingsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Sighting(self): return self.Sighting
    def set_Sighting(self, Sighting): self.Sighting = Sighting
    def add_Sighting(self, value): self.Sighting.append(value)
    def insert_Sighting(self, index, value): self.Sighting[index] = value
    def get_sightings_count(self): return self.sightings_count
    def set_sightings_count(self, sightings_count): self.sightings_count = sightings_count
    def hasContent_(self):
        if (
            self.Sighting
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='SightingsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='SightingsType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='indicator:', name_='SightingsType'):
        if self.sightings_count is not None and 'sightings_count' not in already_processed:
            already_processed.add('sightings_count')
            outfile.write(' sightings_count="%s"' % self.gds_format_integer(self.sightings_count, input_name='sightings_count'))
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='SightingsType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Sighting_ in self.Sighting:
            Sighting_.export(outfile, level, nsmap, namespace_, name_='Sighting', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='SightingsType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.sightings_count is not None and 'sightings_count' not in already_processed:
            already_processed.add('sightings_count')
            showIndent(outfile, level)
            outfile.write('sightings_count = %d,\n' % (self.sightings_count,))
    def exportLiteralChildren(self, outfile, level, name_):
        showIndent(outfile, level)
        outfile.write('Sighting=[\n')
        level += 1
        for Sighting_ in self.Sighting:
            outfile.write('model_.SightingType(\n')
            Sighting_.exportLiteral(outfile, level, name_='SightingType')
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('sightings_count', node)
        if value is not None and 'sightings_count' not in already_processed:
            already_processed.add('sightings_count')
            try:
                self.sightings_count = int(value)
            except ValueError, exp:
                raise_parse_error(node, 'Bad integer attribute: %s' % exp)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Sighting':
            obj_ = SightingType.factory()
            obj_.build(child_)
            self.Sighting.append(obj_)
# end class SightingsType

class SightingType(GeneratedsSuper):
    """Describes a single sighting of an indicator.This field provides the
    date and time of the Indicator sighting."""
    subclass = None
    superclass = None
    def __init__(self, timestamp=None, Source=None, Reference=None, Confidence=None):
        self.timestamp = _cast(None, timestamp)
        self.Source = Source
        self.Reference = Reference
        self.Confidence = Confidence
    def factory(*args_, **kwargs_):
        if SightingType.subclass:
            return SightingType.subclass(*args_, **kwargs_)
        else:
            return SightingType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Source(self): return self.Source
    def set_Source(self, Source): self.Source = Source
    def get_Reference(self): return self.Reference
    def set_Reference(self, Reference): self.Reference = Reference
    def get_Confidence(self): return self.Confidence
    def set_Confidence(self, Confidence): self.Confidence = Confidence
    def get_timestamp(self): return self.timestamp
    def set_timestamp(self, timestamp): self.timestamp = timestamp
    def hasContent_(self):
        if (
            self.Source is not None or
            self.Reference is not None or
            self.Confidence is not None
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='SightingType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='SightingType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='indicator:', name_='SightingType'):
        if self.timestamp is not None and 'timestamp' not in already_processed:
            already_processed.add('timestamp')
            outfile.write(' timestamp="%s"' % self.gds_format_datetime(self.timestamp, input_name='timestamp'))
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='SightingType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.Source is not None:
            self.Source.export(outfile, level, nsmap, namespace_, name_='Source', pretty_print=pretty_print)
        if self.Reference is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%s:Reference>%s</%s:Reference>%s' % (nsmap[namespace_], self.gds_format_string(quote_xml(self.Reference).encode(ExternalEncoding), input_name='Reference'), nsmap[namespace_], eol_))
        if self.Confidence is not None:
            self.Confidence.export(outfile, level, nsmap, namespace_, name_='Confidence', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='SightingType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.timestamp is not None and 'timestamp' not in already_processed:
            already_processed.add('timestamp')
            showIndent(outfile, level)
            outfile.write('timestamp = "%s",\n' % (self.timestamp,))
    def exportLiteralChildren(self, outfile, level, name_):
        if self.Source is not None:
            outfile.write('Source=model_.stix_common_binding.StructuredTextType(\n')
            self.Source.exportLiteral(outfile, level, name_='Source')
            outfile.write('),\n')
        if self.Reference is not None:
            showIndent(outfile, level)
            outfile.write('Reference=%s,\n' % quote_python(self.Reference).encode(ExternalEncoding))
        if self.Confidence is not None:
            outfile.write('Confidence=model_.stix_common_binding.ConfidenceType(\n')
            self.Confidence.exportLiteral(outfile, level, name_='Confidence')
            outfile.write('),\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('timestamp', node)
        if value is not None and 'timestamp' not in already_processed:
            already_processed.add('timestamp')
            try:
                self.timestamp = self.gds_parse_datetime(value, node, 'timestamp')
            except ValueError, exp:
                raise ValueError('Bad date-time attribute (timestamp): %s' % exp)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Source':
            obj_ = stix_common_binding.StructuredTextType.factory()
            obj_.build(child_)
            self.set_Source(obj_)
        elif nodeName_ == 'Reference':
            Reference_ = child_.text
            Reference_ = self.gds_validate_string(Reference_, node, 'Reference')
            self.Reference = Reference_
        elif nodeName_ == 'Confidence':
            obj_ = stix_common_binding.ConfidenceType.factory()
            obj_.build(child_)
            self.set_Confidence(obj_)
# end class SightingType

class TestMechanismsType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, Test_Mechanism=None):
        if Test_Mechanism is None:
            self.Test_Mechanism = []
        else:
            self.Test_Mechanism = Test_Mechanism
    def factory(*args_, **kwargs_):
        if TestMechanismsType.subclass:
            return TestMechanismsType.subclass(*args_, **kwargs_)
        else:
            return TestMechanismsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Test_Mechanism(self): return self.Test_Mechanism
    def set_Test_Mechanism(self, Test_Mechanism): self.Test_Mechanism = Test_Mechanism
    def add_Test_Mechanism(self, value): self.Test_Mechanism.append(value)
    def insert_Test_Mechanism(self, index, value): self.Test_Mechanism[index] = value
    def hasContent_(self):
        if (
            self.Test_Mechanism
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='TestMechanismsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='TestMechanismsType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='indicator:', name_='TestMechanismsType'):
        pass
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='TestMechanismsType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Test_Mechanism_ in self.get_Test_Mechanism():
            Test_Mechanism_.export(outfile, level, nsmap, namespace_, name_='Test_Mechanism', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='TestMechanismsType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        pass
    def exportLiteralChildren(self, outfile, level, name_):
        showIndent(outfile, level)
        outfile.write('Test_Mechanism=[\n')
        level += 1
        for Test_Mechanism_ in self.Test_Mechanism:
            outfile.write('model_.TestMechanismType(\n')
            Test_Mechanism_.exportLiteral(outfile, level, name_='TestMechanismType')
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        pass
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Test_Mechanism':
            type_name_ = child_.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}type')
            if type_name_ is None:
                type_name_ = child_.attrib.get('type')
            if type_name_ is not None:
                type_names_ = type_name_.split(':')
                if len(type_names_) == 1:
                    type_name_ = type_names_[0]
                else:
                    type_name_ = type_names_[1]            
                    if type_name_ == "OVAL5.10TestMechanismType":
                        import stix.bindings.extensions.test_mechanism.oval_5_10 as oval_5_10_tm_binding
                        obj_ = oval_5_10_tm_binding.OVAL5_10TestMechanismType.factory()
                    elif type_name_ == "YaraTestMechanismType":
                        import stix.bindings.extensions.test_mechanism.yara as yara_tm_binding
                        obj_ = yara_tm_binding.YaraTestMechanismType.factory()
                    elif type_name_ == "SnortTestMechanismType":
                        import stix.bindings.extensions.test_mechanism.snort as snort_tm_binding
                        obj_ = snort_tm_binding.SnortTestMechanismType.factory()
                    elif type_name_ == "OpenIOC2010TestMechanismType":
                        import stix.bindings.extensions.test_mechanism.open_ioc_2010 as openioc_tm_binding
                        obj_ = openioc_tm_binding.OpenIOC2010TestMechanismType.factory()
                    elif type_name_ == "GenericTestMechanismType":
                        import stix.bindings.extensions.test_mechanism.generic as generic_tm_binding
                        obj_ = generic_tm_binding.GenericTestMechanismType.factory()
                    else:
                        raise NotImplementedError('Class not implemented for <Test_Mechanism> element: ' + type_name_)
            else:
                raise NotImplementedError(
                    'Class not implemented for <Test_Mechanism> element: no xsi:type attribute found')
            
            obj_.build(child_)
            self.Test_Mechanism.append(obj_)
# end class TestMechanismsType

class SuggestedCOAsType(stix_common_binding.GenericRelationshipListType):
    subclass = None
    superclass = stix_common_binding.GenericRelationshipListType
    def __init__(self, scope='exclusive', Suggested_COA=None):
        super(SuggestedCOAsType, self).__init__(scope, )
        if Suggested_COA is None:
            self.Suggested_COA = []
        else:
            self.Suggested_COA = Suggested_COA
    def factory(*args_, **kwargs_):
        if SuggestedCOAsType.subclass:
            return SuggestedCOAsType.subclass(*args_, **kwargs_)
        else:
            return SuggestedCOAsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Suggested_COA(self): return self.Suggested_COA
    def set_Suggested_COA(self, Suggested_COA): self.Suggested_COA = Suggested_COA
    def add_Suggested_COA(self, value): self.Suggested_COA.append(value)
    def insert_Suggested_COA(self, index, value): self.Suggested_COA[index] = value
    def hasContent_(self):
        if (
            self.Suggested_COA or
            super(SuggestedCOAsType, self).hasContent_()
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='SuggestedCOAsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='SuggestedCOAsType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='indicator:', name_='SuggestedCOAsType'):
        super(SuggestedCOAsType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='SuggestedCOAsType')
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='SuggestedCOAsType', fromsubclass_=False, pretty_print=True):
        super(SuggestedCOAsType, self).exportChildren(outfile, level, nsmap, namespace_, name_, True, pretty_print=pretty_print)
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Suggested_COA_ in self.Suggested_COA:
            Suggested_COA_.export(outfile, level, nsmap, namespace_, name_='Suggested_COA', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='SuggestedCOAsType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        super(SuggestedCOAsType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
    def exportLiteralChildren(self, outfile, level, name_):
        super(SuggestedCOAsType, self).exportLiteralChildren(outfile, level, name_)
        showIndent(outfile, level)
        outfile.write('Suggested_COA=[\n')
        level += 1
        for Suggested_COA_ in self.Suggested_COA:
            outfile.write('model_.stix_common_binding.RelatedCourseOfActionType(\n')
            Suggested_COA_.exportLiteral(outfile, level, name_='stix_common_binding.RelatedCourseOfActionType')
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        super(SuggestedCOAsType, self).buildAttributes(node, attrs, already_processed)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Suggested_COA':
            obj_ = stix_common_binding.RelatedCourseOfActionType.factory()
            obj_.build(child_)
            self.Suggested_COA.append(obj_)
        super(SuggestedCOAsType, self).buildChildren(child_, node, nodeName_, True)
# end class SuggestedCOAsType

class RelatedIndicatorsType(stix_common_binding.GenericRelationshipListType):
    subclass = None
    superclass = stix_common_binding.GenericRelationshipListType
    def __init__(self, scope='exclusive', Related_Indicator=None):
        super(RelatedIndicatorsType, self).__init__(scope, )
        if Related_Indicator is None:
            self.Related_Indicator = []
        else:
            self.Related_Indicator = Related_Indicator
    def factory(*args_, **kwargs_):
        if RelatedIndicatorsType.subclass:
            return RelatedIndicatorsType.subclass(*args_, **kwargs_)
        else:
            return RelatedIndicatorsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Related_Indicator(self): return self.Related_Indicator
    def set_Related_Indicator(self, Related_Indicator): self.Related_Indicator = Related_Indicator
    def add_Related_Indicator(self, value): self.Related_Indicator.append(value)
    def insert_Related_Indicator(self, index, value): self.Related_Indicator[index] = value
    def hasContent_(self):
        if (
            self.Related_Indicator or
            super(RelatedIndicatorsType, self).hasContent_()
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='RelatedIndicatorsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='RelatedIndicatorsType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='indicator:', name_='RelatedIndicatorsType'):
        super(RelatedIndicatorsType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='RelatedIndicatorsType')
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='RelatedIndicatorsType', fromsubclass_=False, pretty_print=True):
        super(RelatedIndicatorsType, self).exportChildren(outfile, level, nsmap, namespace_, name_, True, pretty_print=pretty_print)
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Related_Indicator_ in self.Related_Indicator:
            Related_Indicator_.export(outfile, level, nsmap, namespace_, name_='Related_Indicator', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='RelatedIndicatorsType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        super(RelatedIndicatorsType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
    def exportLiteralChildren(self, outfile, level, name_):
        super(RelatedIndicatorsType, self).exportLiteralChildren(outfile, level, name_)
        showIndent(outfile, level)
        outfile.write('Related_Indicator=[\n')
        level += 1
        for Related_Indicator_ in self.Related_Indicator:
            outfile.write('model_.stix_common_binding.RelatedIndicatorType(\n')
            Related_Indicator_.exportLiteral(outfile, level, name_='stix_common_binding.RelatedIndicatorType')
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        super(RelatedIndicatorsType, self).buildAttributes(node, attrs, already_processed)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Related_Indicator':
            obj_ = stix_common_binding.RelatedIndicatorType.factory()
            obj_.build(child_)
            self.Related_Indicator.append(obj_)
        super(RelatedIndicatorsType, self).buildChildren(child_, node, nodeName_, True)
# end class RelatedIndicatorsType

class IndicatorType(stix_common_binding.IndicatorBaseType):
    """The IndicatorType characterizes a cyber threat indicator made up of
    a pattern identifying certain observable conditions as well as
    contextual information about the patterns meaning, how and when
    it should be acted on, etc. Content creators should either
    create a "simple indicator" containing one observable, or a
    "composite indicator" containing multiple indicators.Specifies
    the relevant STIX-Indicator schema version for this content.The
    negate field applies when using an Indicator as a pattern and
    specifies the absence of the pattern."""
    subclass = None
    superclass = stix_common_binding.IndicatorBaseType
    def __init__(self, idref=None, id=None, negate=False, version='2.0', Title=None, Type=None, Alternative_ID=None, Description=None, Valid_Time_Position=None, Observable=None, Composite_Indicator_Expression=None, Indicated_TTP=None, Kill_Chain_Phases=None, Test_Mechanisms=None, Likely_Impact=None, Suggested_COAs=None, Handling=None, Confidence=None, Sightings=None, Related_Indicators=None, Producer=None):
        super(IndicatorType, self).__init__(idref, id, )
        self.xmlns          = "http://stix.mitre.org/Indicator-2"
        self.xmlns_prefix   = "indicator"
        self.xml_type       = "IndicatorType"
        
        self.negate = _cast(bool, negate)
        self.version = _cast(None, version)
        self.Title = Title
        self.Type = Type
        if Alternative_ID is None:
            self.Alternative_ID = []
        else:
            self.Alternative_ID = Alternative_ID
        self.Description = Description
        if Valid_Time_Position is None:
            self.Valid_Time_Position = []
        else:
            self.Valid_Time_Position = Valid_Time_Position
        self.Observable = Observable
        self.Composite_Indicator_Expression = Composite_Indicator_Expression
        if Indicated_TTP is None:
            self.Indicated_TTP = []
        else:
            self.Indicated_TTP = Indicated_TTP
        self.Kill_Chain_Phases = Kill_Chain_Phases
        self.Test_Mechanisms = Test_Mechanisms
        self.Likely_Impact = Likely_Impact
        self.Suggested_COAs = Suggested_COAs
        self.Handling = Handling
        self.Confidence = Confidence
        self.Sightings = Sightings
        self.Related_Indicators = Related_Indicators
        self.Producer = Producer
    def factory(*args_, **kwargs_):
        if IndicatorType.subclass:
            return IndicatorType.subclass(*args_, **kwargs_)
        else:
            return IndicatorType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Title(self): return self.Title
    def set_Title(self, Title): self.Title = Title
    def get_Type(self): return self.Type
    def set_Type(self, Type): self.Type = Type
    def get_Alternative_ID(self): return self.Alternative_ID
    def set_Alternative_ID(self, Alternative_ID): self.Alternative_ID = Alternative_ID
    def add_Alternative_ID(self, value): self.Alternative_ID.append(value)
    def insert_Alternative_ID(self, index, value): self.Alternative_ID[index] = value
    def get_Description(self): return self.Description
    def set_Description(self, Description): self.Description = Description
    def get_Valid_Time_Position(self): return self.Valid_Time_Position
    def set_Valid_Time_Position(self, Valid_Time_Position): self.Valid_Time_Position = Valid_Time_Position
    def add_Valid_Time_Position(self, value): self.Valid_Time_Position.append(value)
    def insert_Valid_Time_Position(self, index, value): self.Valid_Time_Position[index] = value
    def get_Observable(self): return self.Observable
    def set_Observable(self, Observable): self.Observable = Observable
    def get_Composite_Indicator_Expression(self): return self.Composite_Indicator_Expression
    def set_Composite_Indicator_Expression(self, Composite_Indicator_Expression): self.Composite_Indicator_Expression = Composite_Indicator_Expression
    def get_Indicated_TTP(self): return self.Indicated_TTP
    def set_Indicated_TTP(self, Indicated_TTP): self.Indicated_TTP = Indicated_TTP
    def add_Indicated_TTP(self, value): self.Indicated_TTP.append(value)
    def insert_Indicated_TTP(self, index, value): self.Indicated_TTP[index] = value
    def get_Kill_Chain_Phases(self): return self.Kill_Chain_Phases
    def set_Kill_Chain_Phases(self, Kill_Chain_Phases): self.Kill_Chain_Phases = Kill_Chain_Phases
    def get_Test_Mechanisms(self): return self.Test_Mechanisms
    def set_Test_Mechanisms(self, Test_Mechanisms): self.Test_Mechanisms = Test_Mechanisms
    def get_Likely_Impact(self): return self.Likely_Impact
    def set_Likely_Impact(self, Likely_Impact): self.Likely_Impact = Likely_Impact
    def get_Suggested_COAs(self): return self.Suggested_COAs
    def set_Suggested_COAs(self, Suggested_COAs): self.Suggested_COAs = Suggested_COAs
    def get_Handling(self): return self.Handling
    def set_Handling(self, Handling): self.Handling = Handling
    def get_Confidence(self): return self.Confidence
    def set_Confidence(self, Confidence): self.Confidence = Confidence
    def get_Sightings(self): return self.Sightings
    def set_Sightings(self, Sightings): self.Sightings = Sightings
    def get_Related_Indicators(self): return self.Related_Indicators
    def set_Related_Indicators(self, Related_Indicators): self.Related_Indicators = Related_Indicators
    def get_Producer(self): return self.Producer
    def set_Producer(self, Producer): self.Producer = Producer
    def get_negate(self): return self.negate
    def set_negate(self, negate): self.negate = negate
    def get_version(self): return self.version
    def set_version(self, version): self.version = version
    def hasContent_(self):
        if (
            self.Title is not None or
            self.Type is not None or
            self.Alternative_ID or
            self.Description is not None or
            self.Valid_Time_Position or
            self.Observable is not None or
            self.Composite_Indicator_Expression is not None or
            self.Indicated_TTP or
            self.Kill_Chain_Phases is not None or
            self.Test_Mechanisms is not None or
            self.Likely_Impact is not None or
            self.Suggested_COAs is not None or
            self.Handling is not None or
            self.Confidence is not None or
            self.Sightings is not None or
            self.Related_Indicators is not None or
            self.Producer is not None or
            super(IndicatorType, self).hasContent_()
            ):
            return True
        else:
            return False
    def export(self, outfile, level, nsmap, namespace_=XML_NS, name_='IndicatorType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, XML_NS, name_='IndicatorType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_=XML_NS, name_='IndicatorType'):
        super(IndicatorType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='IndicatorType')
        if 'xmlns' not in already_processed:
            already_processed.add('xmlns')
            xmlns = " xmlns:%s='%s'" % (self.xmlns_prefix, self.xmlns)
            outfile.write(xmlns)   
        if 'xsi:type' not in already_processed:
            already_processed.add('xsi:type')
            xsi_type = " xsi:type='%s:%s'" % (self.xmlns_prefix, self.xml_type)
            outfile.write(xsi_type)
        if self.negate is not None and 'negate' not in already_processed:
            already_processed.add('negate')
            outfile.write(' negate="%s"' % self.gds_format_boolean(self.negate, input_name='negate'))
        if self.version is not None and 'version' not in already_processed:
            already_processed.add('version')
            outfile.write(' version=%s' % (quote_attrib(self.version), ))
    def exportChildren(self, outfile, level, nsmap, namespace_=XML_NS, name_='IndicatorType', fromsubclass_=False, pretty_print=True):
        super(IndicatorType, self).exportChildren(outfile, level, namespace_, name_, True, pretty_print=pretty_print)
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.Title is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%s:Title>%s</%s:Title>%s' % (nsmap[namespace_], self.gds_format_string(quote_xml(self.Title).encode(ExternalEncoding), input_name='Title'), nsmap[namespace_], eol_))
        if self.Type is not None:
            self.Type.export(outfile, level, nsmap, namespace_, name_='Type', pretty_print=pretty_print)
        for Alternative_ID_ in self.Alternative_ID:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%s:Alternative_ID>%s</%s:Alternative_ID>%s' % (nsmap[namespace_], self.gds_format_string(quote_xml(Alternative_ID_).encode(ExternalEncoding), input_name='Alternative_ID'), nsmap[namespace_], eol_))
        if self.Description is not None:
            self.Description.export(outfile, level, nsmap, namespace_, name_='Description', pretty_print=pretty_print)
        for Valid_Time_Position_ in self.Valid_Time_Position:
            Valid_Time_Position_.export(outfile, level, nsmap, namespace_, name_='Valid_Time_Position', pretty_print=pretty_print)
        if self.Observable is not None:
            self.Observable.export(outfile, level, "%s:" % (nsmap[namespace_]), name_='Observable', pretty_print=pretty_print) # requires a hack to make the namespace work..no nsmap parameter
        if self.Composite_Indicator_Expression is not None:
            self.Composite_Indicator_Expression.export(outfile, level, nsmap, namespace_, name_='Composite_Indicator_Expression', pretty_print=pretty_print)
        for Indicated_TTP_ in self.Indicated_TTP:
            Indicated_TTP_.export(outfile, level, nsmap, namespace_, name_='Indicated_TTP', pretty_print=pretty_print)
        if self.Kill_Chain_Phases is not None:
            self.Kill_Chain_Phases.export(outfile, level, nsmap, namespace_, name_='Kill_Chain_Phases', pretty_print=pretty_print)
        if self.Test_Mechanisms is not None:
            self.Test_Mechanisms.export(outfile, level, nsmap, namespace_, name_='Test_Mechanisms', pretty_print=pretty_print)
        if self.Likely_Impact is not None:
            self.Likely_Impact.export(outfile, level, nsmap, namespace_, name_='Likely_Impact', pretty_print=pretty_print)
        if self.Suggested_COAs is not None:
            self.Suggested_COAs.export(outfile, level, nsmap, namespace_, name_='Suggested_COAs', pretty_print=pretty_print)
        if self.Handling is not None:
            self.Handling.export(outfile, level, nsmap, namespace_, name_='Handling', pretty_print=pretty_print)
        if self.Confidence is not None:
            self.Confidence.export(outfile, level, nsmap, namespace_, name_='Confidence', pretty_print=pretty_print)
        if self.Sightings is not None:
            self.Sightings.export(outfile, level, nsmap, namespace_, name_='Sightings', pretty_print=pretty_print)
        if self.Related_Indicators is not None:
            self.Related_Indicators.export(outfile, level, nsmap, namespace_, name_='Related_Indicators', pretty_print=pretty_print)
        if self.Producer is not None:
            self.Producer.export(outfile, level, nsmap, namespace_, name_='Producer', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='IndicatorType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.negate is not None and 'negate' not in already_processed:
            already_processed.add('negate')
            showIndent(outfile, level)
            outfile.write('negate = %s,\n' % (self.negate,))
        if self.version is not None and 'version' not in already_processed:
            already_processed.add('version')
            showIndent(outfile, level)
            outfile.write('version = %s,\n' % (self.version,))
        super(IndicatorType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
    def exportLiteralChildren(self, outfile, level, name_):
        super(IndicatorType, self).exportLiteralChildren(outfile, level, name_)
        if self.Title is not None:
            showIndent(outfile, level)
            outfile.write('Title=%s,\n' % quote_python(self.Title).encode(ExternalEncoding))
        if self.Type is not None:
            outfile.write('Type=model_.stix_common_binding.ControlledVocabularyStringType(\n')
            self.Type.exportLiteral(outfile, level, name_='Type')
            outfile.write('),\n')
        showIndent(outfile, level)
        outfile.write('Alternative_ID=[\n')
        level += 1
        for Alternative_ID_ in self.Alternative_ID:
            showIndent(outfile, level)
            outfile.write('%s,\n' % quote_python(Alternative_ID_).encode(ExternalEncoding))
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
        if self.Description is not None:
            outfile.write('Description=model_.stix_common_binding.StructuredTextType(\n')
            self.Description.exportLiteral(outfile, level, name_='Description')
            outfile.write('),\n')
        showIndent(outfile, level)
        outfile.write('Valid_Time_Position=[\n')
        level += 1
        for Valid_Time_Position_ in self.Valid_Time_Position:
            outfile.write('model_.ValidTimeType(\n')
            Valid_Time_Position_.exportLiteral(outfile, level, name_='ValidTimeType')
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
        if self.Observable is not None:
            outfile.write('Observable=model_.cybox_core_binding.ObservableType(\n')
            self.Observable.exportLiteral(outfile, level, name_='Observable')
            outfile.write('),\n')
        if self.Composite_Indicator_Expression is not None:
            outfile.write('Composite_Indicator_Expression=model_.CompositeIndicatorExpressionType(\n')
            self.Composite_Indicator_Expression.exportLiteral(outfile, level, name_='Composite_Indicator_Expression')
            outfile.write('),\n')
        showIndent(outfile, level)
        outfile.write('Indicated_TTP=[\n')
        level += 1
        for Indicated_TTP_ in self.Indicated_TTP:
            outfile.write('model_.stix_common_binding.RelatedTTPType(\n')
            Indicated_TTP_.exportLiteral(outfile, level, name_='stix_common_binding.RelatedTTPType')
            showIndent(outfile, level)
            outfile.write('),\n')
        level -= 1
        showIndent(outfile, level)
        outfile.write('],\n')
        if self.Kill_Chain_Phases is not None:
            outfile.write('Kill_Chain_Phases=model_.stix_common_binding.KillChainPhasesReferenceType(\n')
            self.Kill_Chain_Phases.exportLiteral(outfile, level, name_='Kill_Chain_Phases')
            outfile.write('),\n')
        if self.Test_Mechanisms is not None:
            outfile.write('Test_Mechanisms=model_.TestMechanismsType(\n')
            self.Test_Mechanisms.exportLiteral(outfile, level, name_='Test_Mechanisms')
            outfile.write('),\n')
        if self.Likely_Impact is not None:
            outfile.write('Likely_Impact=model_.stix_common_binding.StatementType(\n')
            self.Likely_Impact.exportLiteral(outfile, level, name_='Likely_Impact')
            outfile.write('),\n')
        if self.Suggested_COAs is not None:
            outfile.write('Suggested_COAs=model_.SuggestedCOAsType(\n')
            self.Suggested_COAs.exportLiteral(outfile, level, name_='Suggested_COAs')
            outfile.write('),\n')
        if self.Handling is not None:
            outfile.write('Handling=model_.data_marking_binding.MarkingType(\n')
            self.Handling.exportLiteral(outfile, level, name_='Handling')
            outfile.write('),\n')
        if self.Confidence is not None:
            outfile.write('Confidence=model_.stix_common_binding.ConfidenceType(\n')
            self.Confidence.exportLiteral(outfile, level, name_='Confidence')
            outfile.write('),\n')
        if self.Sightings is not None:
            outfile.write('Sightings=model_.SightingsType(\n')
            self.Sightings.exportLiteral(outfile, level, name_='Sightings')
            outfile.write('),\n')
        if self.Related_Indicators is not None:
            outfile.write('Related_Indicators=model_.RelatedIndicatorsType(\n')
            self.Related_Indicators.exportLiteral(outfile, level, name_='Related_Indicators')
            outfile.write('),\n')
        if self.Producer is not None:
            outfile.write('Producer=model_.stix_common_binding.InformationSourceType(\n')
            self.Producer.exportLiteral(outfile, level, name_='Producer')
            outfile.write('),\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('negate', node)
        if value is not None and 'negate' not in already_processed:
            already_processed.add('negate')
            if value in ('true', '1'):
                self.negate = True
            elif value in ('false', '0'):
                self.negate = False
            else:
                raise_parse_error(node, 'Bad boolean attribute')
        value = find_attr_value_('version', node)
        if value is not None and 'version' not in already_processed:
            already_processed.add('version')
            self.version = value
        super(IndicatorType, self).buildAttributes(node, attrs, already_processed)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Title':
            Title_ = child_.text
            Title_ = self.gds_validate_string(Title_, node, 'Title')
            self.Title = Title_
        elif nodeName_ == 'Type':
            obj_ = stix_common_binding.ControlledVocabularyStringType.factory()
            obj_.build(child_)
            self.set_Type(obj_)
        elif nodeName_ == 'Alternative_ID':
            Alternative_ID_ = child_.text
            Alternative_ID_ = self.gds_validate_string(Alternative_ID_, node, 'Alternative_ID')
            self.Alternative_ID.append(Alternative_ID_)
        elif nodeName_ == 'Description':
            obj_ = stix_common_binding.StructuredTextType.factory()
            obj_.build(child_)
            self.set_Description(obj_)
        elif nodeName_ == 'Valid_Time_Position':
            obj_ = ValidTimeType.factory()
            obj_.build(child_)
            self.Valid_Time_Position.append(obj_)
        elif nodeName_ == 'Observable':
            obj_ = cybox_core_binding.ObservableType.factory()
            obj_.build(child_)
            self.set_Observable(obj_)
        elif nodeName_ == 'Composite_Indicator_Expression':
            obj_ = CompositeIndicatorExpressionType.factory()
            obj_.build(child_)
            self.set_Composite_Indicator_Expression(obj_)
        elif nodeName_ == 'Indicated_TTP':
            obj_ = stix_common_binding.RelatedTTPType.factory()
            obj_.build(child_)
            self.Indicated_TTP.append(obj_)
        elif nodeName_ == 'Kill_Chain_Phases':
            obj_ = stix_common_binding.KillChainPhasesReferenceType.factory()
            obj_.build(child_)
            self.set_Kill_Chain_Phases(obj_)
        elif nodeName_ == 'Test_Mechanisms':
            obj_ = TestMechanismsType.factory()
            obj_.build(child_)
            self.set_Test_Mechanisms(obj_)
        elif nodeName_ == 'Likely_Impact':
            obj_ = stix_common_binding.StatementType.factory()
            obj_.build(child_)
            self.set_Likely_Impact(obj_)
        elif nodeName_ == 'Suggested_COAs':
            obj_ = SuggestedCOAsType.factory()
            obj_.build(child_)
            self.set_Suggested_COAs(obj_)
        elif nodeName_ == 'Handling':
            obj_ = data_marking_binding.MarkingType.factory()
            obj_.build(child_)
            self.set_Handling(obj_)
        elif nodeName_ == 'Confidence':
            obj_ = stix_common_binding.ConfidenceType.factory()
            obj_.build(child_)
            self.set_Confidence(obj_)
        elif nodeName_ == 'Sightings':
            obj_ = SightingsType.factory()
            obj_.build(child_)
            self.set_Sightings(obj_)
        elif nodeName_ == 'Related_Indicators':
            obj_ = RelatedIndicatorsType.factory()
            obj_.build(child_)
            self.set_Related_Indicators(obj_)
        elif nodeName_ == 'Producer':
            obj_ = stix_common_binding.InformationSourceType.factory()
            obj_.build(child_)
            self.set_Producer(obj_)
        super(IndicatorType, self).buildChildren(child_, node, nodeName_, True)
# end class IndicatorType

GDSClassesMapping = {
    'Relationships': cybox_core_binding.RelationshipsType,
    'Indicator': stix_common_binding.IndicatorBaseType,
    'Defined_Effect': cybox_core_binding.DefinedEffectType,
    'Action_Argument': cybox_core_binding.ActionArgumentType,
    'Exploit_Target': stix_common_binding.ExploitTargetBaseType,
    'Action': cybox_core_binding.ActionType,
    'Suggested_COA': stix_common_binding.RelatedCourseOfActionType,
    'Object': cybox_core_binding.ObjectType,
    'Incident': stix_common_binding.IncidentBaseType,
    'Information_Source_Type': stix_common_binding.ControlledVocabularyStringType,
    'Confidence_Assertion_Chain': stix_common_binding.ConfidenceAssertionChainType,
    'Observable': cybox_core_binding.ObservableType,
    'Observable_Composition': cybox_core_binding.ObservableCompositionType,
    'Confidence_Assertion': stix_common_binding.ConfidenceType,
    'Value': stix_common_binding.ControlledVocabularyStringType,
    'Information_Source': stix_common_binding.InformationSourceType,
    'Evasion_Techniques': cybox_core_binding.ObfuscationTechniquesType,
    'Producer': stix_common_binding.InformationSourceType,
    'Encoding': stix_common_binding.ControlledVocabularyStringType,
    'Kill_Chain_Phases': stix_common_binding.KillChainPhasesReferenceType,
    'Associated_Objects': cybox_core_binding.AssociatedObjectsType,
    'Event': cybox_core_binding.EventType,
    'Domain_Specific_Object_Properties': cybox_core_binding.DomainSpecificObjectPropertiesType,
    'Source': stix_common_binding.ControlledVocabularyStringType,
    'State': stix_common_binding.ControlledVocabularyStringType,
    'Marking_Structure': data_marking_binding.MarkingStructureType,
    'Action_Arguments': cybox_core_binding.ActionArgumentsType,
    'Type': stix_common_binding.ControlledVocabularyStringType,
    'Tool_Type': stix_common_binding.ControlledVocabularyStringType,
    'Relationship': stix_common_binding.ControlledVocabularyStringType,
    'TTP': stix_common_binding.TTPBaseType,
    'Obfuscation_Technique': cybox_core_binding.ObfuscationTechniqueType,
    'Indicated_TTP': stix_common_binding.RelatedTTPType,
    'Action_Pool': cybox_core_binding.ActionPoolType,
    'Course_Of_Action': stix_common_binding.CourseOfActionBaseType,
    'Contributors': stix_common_binding.ContributorsType,
    'Campaign': stix_common_binding.CampaignBaseType,
    'Reference_Description': stix_common_binding.StructuredTextType,
    'Association_Type': stix_common_binding.ControlledVocabularyStringType,
    'Confidence': stix_common_binding.ConfidenceType,
    'Associated_Object': cybox_core_binding.AssociatedObjectType,
    'Related_Objects': cybox_core_binding.RelatedObjectsType,
    'Related_Identities': stix_common_binding.RelatedIdentitiesType,
    'Likely_Impact': stix_common_binding.StatementType,
    'Property_Pool': cybox_core_binding.PropertyPoolType,
    'Identity': stix_common_binding.IdentityType,
    'Action_Reference': cybox_core_binding.ActionReferenceType,
    'Usage_Context_Assumption': stix_common_binding.StructuredTextType,
    'Pools': cybox_core_binding.PoolsType,
    'Threat_Actor': stix_common_binding.ThreatActorBaseType,
    'Event_Pool': cybox_core_binding.EventPoolType,
    'Kill_Chain': stix_common_binding.KillChainType,
    'Old_Object': cybox_core_binding.ObjectType,
    'Object_Pool': cybox_core_binding.ObjectPoolType,
    'Properties': cybox_core_binding.PropertiesType,
    'Frequency': cybox_core_binding.FrequencyType,
    'References': stix_common_binding.ReferencesType,
    'Keywords': cybox_core_binding.KeywordsType,
    'Pattern_Fidelity': cybox_core_binding.PatternFidelityType,
    'Description': stix_common_binding.StructuredTextType,
    'Efficacy': stix_common_binding.StatementType,
    'Action_Pertinent_Object_Properties': cybox_core_binding.ActionPertinentObjectPropertiesType,
    'Related_Indicator': stix_common_binding.RelatedIndicatorType,
    'Related_Object': cybox_core_binding.RelatedObjectType,
    'Handling': data_marking_binding.MarkingType,
    'Kill_Chain_Phase': stix_common_binding.KillChainPhaseReferenceType,
    'Related_Identity': stix_common_binding.RelatedIdentityType,
    'Values': cybox_core_binding.ValuesType,
    'Marking': data_marking_binding.MarkingSpecificationType,
    'Observables': cybox_core_binding.ObservablesType,
    'New_Object': cybox_core_binding.ObjectType,
    'Argument_Name': stix_common_binding.ControlledVocabularyStringType,
    'Actions': cybox_core_binding.ActionsType,
    'Dependency_Description': stix_common_binding.StructuredTextType,
    'Contributor': stix_common_binding.IdentityType,
    'Action_Aliases': cybox_core_binding.ActionAliasesType,
}

USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
"""

def usage():
    print USAGE_TEXT
    sys.exit(1)

def get_root_tag(node):
    tag = Tag_pattern_.match(node.tag).groups()[-1]
    rootClass = GDSClassesMapping.get(tag)
    if rootClass is None:
        rootClass = globals().get(tag)
    return tag, rootClass

def parse(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'Indicator'
        rootClass = IndicatorType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    sys.stdout.write('<?xml version="1.0" ?>\n')
    rootObj.export(sys.stdout, 0, name_=rootTag,
        namespacedef_='',
        pretty_print=True)
    return rootObj

def parseEtree(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'Indicator'
        rootClass = IndicatorType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    rootElement = rootObj.to_etree(None, name_=rootTag)
    content = etree_.tostring(rootElement, pretty_print=True,
        xml_declaration=True, encoding="utf-8")
    sys.stdout.write(content)
    sys.stdout.write('\n')
    return rootObj, rootElement

def parseString(inString):
    from StringIO import StringIO
    doc = parsexml_(StringIO(inString))
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'Indicator'
        rootClass = IndicatorType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    sys.stdout.write('<?xml version="1.0" ?>\n')
    rootObj.export(sys.stdout, 0, name_="Indicator",
        namespacedef_='')
    return rootObj

def parseLiteral(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'Indicator'
        rootClass = IndicatorType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    sys.stdout.write('#from indicator import *\n\n')
    sys.stdout.write('from datetime import datetime as datetime_\n\n')
    sys.stdout.write('import indicator as model_\n\n')
    sys.stdout.write('rootObj = model_.rootTag(\n')
    rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
    sys.stdout.write(')\n')
    return rootObj

def main():
    args = sys.argv[1:]
    if len(args) == 1:
        parse(args[0])
    else:
        usage()

if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    main()

__all__ = [
    "ValidTimeType",
    "CompositeIndicatorExpressionType",
    "TestMechanismType",
    "SightingsType",
    "SightingType",
    "TestMechanismsType",
    "SuggestedCOAsType",
    "RelatedIndicatorsType",
    "IndicatorType"
    ]