text:
import sys

import cybox.bindings.cybox_core as cybox_core_binding
from mixbox.binding_utils import *

from stix.bindings import lookup_extension
import stix.bindings.stix_common as stix_common_binding
import stix.bindings.data_marking as data_marking_binding

XML_NS = "http://stix.mitre.org/stix-1"

#
# Data representation classes.
#

class STIXType(GeneratedsSuper):
    """STIXType defines a bundle of information characterized in the
    Structured Threat Information eXpression (STIX)
    language.Specifies a globally unique identifier for this STIX
    Package. Specifies a globally unique identifier of a STIX
    Package specified elsewhere.Specifies the relevant STIX schema
    version for this content."""
    subclass = None
    superclass = None
    def __init__(self, idref=None, id=None, timestamp=None, version=None, STIX_Header=None, Observables=None, Indicators=None, TTPs=None, Exploit_Targets=None, Incidents=None, Courses_Of_Action=None, Campaigns=None, Threat_Actors=None, Related_Packages=None, Reports=None):
        self.idref = _cast(None, idref)
        self.id = _cast(None, id)
        self.timestamp = _cast(None, timestamp)
        self.version = _cast(None, version)
        self.STIX_Header = STIX_Header
        self.Observables = Observables
        self.Indicators = Indicators
        self.TTPs = TTPs
        self.Exploit_Targets = Exploit_Targets
        self.Incidents = Incidents
        self.Courses_Of_Action = Courses_Of_Action
        self.Campaigns = Campaigns
        self.Threat_Actors = Threat_Actors
        self.Related_Packages = Related_Packages
        self.Reports = Reports
        self.nsmap = {}
    def factory(*args_, **kwargs_):
        if STIXType.subclass:
            return STIXType.subclass(*args_, **kwargs_)
        else:
            return STIXType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_STIX_Header(self): return self.STIX_Header
    def set_STIX_Header(self, STIX_Header): self.STIX_Header = STIX_Header
    def get_Observables(self): return self.Observables
    def set_Observables(self, Observables): self.Observables = Observables
    def get_Indicators(self): return self.Indicators
    def set_Indicators(self, Indicators): self.Indicators = Indicators
    def get_TTPs(self): return self.TTPs
    def set_TTPs(self, TTPs): self.TTPs = TTPs
    def get_Exploit_Targets(self): return self.Exploit_Targets
    def set_Exploit_Targets(self, Exploit_Targets): self.Exploit_Targets = Exploit_Targets
    def get_Incidents(self): return self.Incidents
    def set_Incidents(self, Incidents): self.Incidents = Incidents
    def get_Courses_Of_Action(self): return self.Courses_Of_Action
    def set_Courses_Of_Action(self, Courses_Of_Action): self.Courses_Of_Action = Courses_Of_Action
    def get_Campaigns(self): return self.Campaigns
    def set_Campaigns(self, Campaigns): self.Campaigns = Campaigns
    def get_Threat_Actors(self): return self.Threat_Actors
    def set_Threat_Actors(self, Threat_Actors): self.Threat_Actors = Threat_Actors
    def get_Related_Packages(self): return self.Related_Packages
    def set_Related_Packages(self, value): self.Related_Packages = value
    def get_Reports(self): return self.Reports
    def set_Reports(self, value): self.Reports = value
    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_version(self): return self.version
    def set_version(self, version): self.version = version
    def get_timestamp(self): return self.timestamp
    def set_timestamp(self, timestamp): self.timestamp = timestamp
    def hasContent_(self):
        if (
            self.STIX_Header is not None or
            self.Observables is not None or
            self.Indicators is not None or
            self.TTPs is not None or
            self.Exploit_Targets is not None or
            self.Incidents is not None or
            self.Courses_Of_Action is not None or
            self.Campaigns is not None or
            self.Threat_Actors is not None or
            self.Related_Packages is not None or
            self.Reports
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='STIX_Package', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, nsmap, already_processed, namespace_, name_='STIXType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, nsmap, already_processed, namespace_=XML_NS, name_='STIXType'):
        if self.idref is not None and 'idref' not in already_processed:
            already_processed.add('idref')
            lwrite(' idref=%s' % (quote_attrib(self.idref), ))
        if self.id is not None and 'id' not in already_processed:
            already_processed.add('id')
            lwrite(' id=%s' % (quote_attrib(self.id), ))
        if self.version is not None and 'version' not in already_processed:
            already_processed.add('version')
            lwrite(' version=%s' % (quote_attrib(self.version), ))
        if self.timestamp is not None and 'timestamp' not in already_processed:
            already_processed.add('timestamp')
            lwrite(' timestamp="%s"' % self.gds_format_datetime(self.timestamp, input_name='timestamp'))

    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='STIXType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.STIX_Header is not None:
            self.STIX_Header.export(lwrite, level, nsmap, namespace_, name_='STIX_Header', pretty_print=pretty_print)
        if self.Observables is not None:
            self.Observables.export(lwrite, level, "%s:" % (nsmap[namespace_]), name_='Observables', pretty_print=pretty_print) # no nsmap parameter, so we use this hack to pass the right namespace prefix
        if self.Indicators is not None:
            self.Indicators.export(lwrite, level, nsmap, namespace_, name_='Indicators', pretty_print=pretty_print)
        if self.TTPs is not None:
            self.TTPs.export(lwrite, level, nsmap, namespace_, name_='TTPs', pretty_print=pretty_print)
        if self.Exploit_Targets is not None:
            self.Exploit_Targets.export(lwrite, level, nsmap, namespace_, name_='Exploit_Targets', pretty_print=pretty_print)
        if self.Incidents is not None:
            self.Incidents.export(lwrite, level, nsmap, namespace_, name_='Incidents', pretty_print=pretty_print)
        if self.Courses_Of_Action is not None:
            self.Courses_Of_Action.export(lwrite, level, nsmap, namespace_, name_='Courses_Of_Action', pretty_print=pretty_print)
        if self.Campaigns is not None:
            self.Campaigns.export(lwrite, level, nsmap, namespace_, name_='Campaigns', pretty_print=pretty_print)
        if self.Threat_Actors is not None:
            self.Threat_Actors.export(lwrite, level, nsmap, namespace_, name_='Threat_Actors', pretty_print=pretty_print)
        if self.Reports is not None:
            self.Reports.export(lwrite, level, nsmap, namespace_, name_='Reports', pretty_print=pretty_print)
        if self.Related_Packages is not None:
            self.Related_Packages.export(lwrite, level, nsmap, namespace_, name_='Related_Packages', pretty_print=pretty_print)
    def build(self, node):
        already_processed = set()
        self.nsmap = node.nsmap
        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_('version', node)
        if value is not None and 'version' not in already_processed:
            already_processed.add('version')
            self.version = value
        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_ == 'STIX_Header':
            obj_ = STIXHeaderType.factory()
            obj_.build(child_)
            self.set_STIX_Header(obj_)
        elif nodeName_ == 'Observables':
            obj_ = cybox_core_binding.ObservablesType.factory()
            obj_.build(child_)
            self.set_Observables(obj_)
        elif nodeName_ == 'Indicators':
            obj_ = IndicatorsType.factory()
            obj_.build(child_)
            self.set_Indicators(obj_)
        elif nodeName_ == 'TTPs':
            obj_ = TTPsType.factory()
            obj_.build(child_)
            self.set_TTPs(obj_)
        elif nodeName_ == 'Exploit_Targets':
            obj_ = stix_common_binding.ExploitTargetsType.factory()
            obj_.build(child_)
            self.set_Exploit_Targets(obj_)
        elif nodeName_ == 'Incidents':
            obj_ = IncidentsType.factory()
            obj_.build(child_)
            self.set_Incidents(obj_)
        elif nodeName_ == 'Courses_Of_Action':
            obj_ = CoursesOfActionType.factory()
            obj_.build(child_)
            self.set_Courses_Of_Action(obj_)
        elif nodeName_ == 'Campaigns':
            obj_ = CampaignsType.factory()
            obj_.build(child_)
            self.set_Campaigns(obj_)
        elif nodeName_ == 'Threat_Actors':
            obj_ = ThreatActorsType.factory()
            obj_.build(child_)
            self.set_Threat_Actors(obj_)
        elif nodeName_ == 'Reports':
            obj_ = ReportsType.factory()
            obj_.build(child_)
            self.set_Reports(obj_)
        elif nodeName_ == 'Related_Packages':
            obj_ = RelatedPackagesType.factory()
            obj_.build(child_)
            self.set_Related_Packages(obj_)
# end class STIXType

class RelatedPackagesType(stix_common_binding.GenericRelationshipListType):
    subclass = None
    superclass = stix_common_binding.GenericRelationshipListType
    def __init__(self, scope='exclusive', Related_Package=None):
        super(RelatedPackagesType, self).__init__(scope=scope)
        if Related_Package is None:
            self.Related_Package = []
        else:
            self.Related_Package = Related_Package
    def factory(*args_, **kwargs_):
        if RelatedPackagesType.subclass:
            return RelatedPackagesType.subclass(*args_, **kwargs_)
        else:
            return RelatedPackagesType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Related_Package(self): return self.Related_Package
    def set_Related_Package(self, Related_Package): self.Related_Package = Related_Package
    def add_Related_Package(self, value): self.Related_Package.append(value)
    def insert_Related_Package(self, index, value): self.Related_Package[index] = value
    def hasContent_(self):
        if (
            self.Related_Package or
            super(RelatedPackagesType, self).hasContent_()
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='RelatedPackagesType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='RelatedPackagesType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_='stix:', name_='RelatedPackagesType'):
        super(RelatedPackagesType, self).exportAttributes(lwrite, level, already_processed, namespace_, name_='RelatedPackagesType')
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='RelatedPackagesType', fromsubclass_=False, pretty_print=True):
        super(RelatedPackagesType, self).exportChildren(lwrite, level, nsmap, namespace_, name_, True, pretty_print=pretty_print)
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Related_Package_ in self.Related_Package:
            Related_Package_.export(lwrite, level, nsmap, namespace_, name_='Related_Package', pretty_print=pretty_print)
    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(RelatedPackagesType, self).buildAttributes(node, attrs, already_processed)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Related_Package':
            obj_ = RelatedPackageType.factory()
            obj_.build(child_)
            self.Related_Package.append(obj_)
        super(RelatedPackagesType, self).buildChildren(child_, node, nodeName_, True)
# end class RelatedPackagesType

class RelatedPackageType(stix_common_binding.GenericRelationshipType):
    """Identifies or characterizes a relationship to a Package."""
    subclass = None
    superclass = stix_common_binding.GenericRelationshipType
    def __init__(self, Confidence=None, Information_Source=None, Relationship=None, Package=None):
        super(RelatedPackageType, self).__init__(Confidence=Confidence, Information_Source=Information_Source, Relationship=Relationship)
        self.Package = Package
    def factory(*args_, **kwargs_):
        if RelatedPackageType.subclass:
            return RelatedPackageType.subclass(*args_, **kwargs_)
        else:
            return RelatedPackageType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Package(self): return self.Package
    def set_Package(self, Package): self.Package = Package
    def hasContent_(self):
        if (
            self.Package is not None or
            super(RelatedPackageType, self).hasContent_()
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='RelatedPackageType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='RelatedPackageType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_='stix:', name_='RelatedPackageType'):
        super(RelatedPackageType, self).exportAttributes(lwrite, level, already_processed, namespace_, name_='RelatedPackageType')
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='RelatedPackageType', fromsubclass_=False, pretty_print=True):
        super(RelatedPackageType, self).exportChildren(lwrite, level, nsmap, stix_common_binding.XML_NS, name_, True, pretty_print=pretty_print)
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.Package is not None:
            self.Package.export(lwrite, level, nsmap, namespace_, name_='Package', pretty_print=pretty_print)
    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(RelatedPackageType, self).buildAttributes(node, attrs, already_processed)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Package':
            obj_ = STIXType.factory()
            obj_.build(child_)
            self.set_Package(obj_)
        super(RelatedPackageType, self).buildChildren(child_, node, nodeName_, True)
# end class RelatedPackageType

class STIXHeaderType(GeneratedsSuper):
    """The STIXHeaderType provides a structure for characterizing a package
    of STIX content."""
    subclass = None
    superclass = None
    def __init__(self, Title=None, Package_Intent=None, Description=None, Short_Description=None, Profiles=None, Handling=None, Information_Source=None):
        self.Title = Title
        if Package_Intent is None:
            self.Package_Intent = []
        else:
            self.Package_Intent = Package_Intent
        if Description is None:
            self.Description = []
        else:
            self.Description = Description
        self.Handling = Handling
        if Short_Description is None:
            self.Short_Description = []
        else:
            self.Short_Description = Short_Description
        self.Profiles = Profiles
        self.Information_Source = Information_Source
    def factory(*args_, **kwargs_):
        if STIXHeaderType.subclass:
            return STIXHeaderType.subclass(*args_, **kwargs_)
        else:
            return STIXHeaderType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Title(self): return self.Title
    def set_Title(self, Title): self.Title = Title
    def get_Package_Intent(self): return self.Package_Intent
    def set_Package_Intent(self, Package_Intent): self.Package_Intent = Package_Intent
    def add_Package_Intent(self, value): self.Package_Intent.append(value)
    def insert_Package_Intent(self, index, value): self.Package_Intent[index] = value
    def insert_Description(self, index, value): self.Description[index] = value
    def add_Description(self, Description): self.Description.append(Description)
    def get_Description(self): return self.Description
    def set_Description(self, Description): self.Description = Description
    def insert_Short_Description(self, index, value): self.Short_Description[index] = value
    def add_Short_Description(self, Short_Description): self.Short_Description.append(Short_Description)
    def get_Short_Description(self): return self.Short_Description
    def set_Short_Description(self, Short_Description): self.Short_Description = Short_Description
    def get_Profiles(self): return self.Profiles
    def set_Profiles(self, Profiles): self.Profiles = Profiles
    def get_Handling(self): return self.Handling
    def set_Handling(self, Handling): self.Handling = Handling
    def get_Information_Source(self): return self.Information_Source
    def set_Information_Source(self, Information_Source): self.Information_Source = Information_Source
    def hasContent_(self):
        if (
            self.Title is not None or
            self.Package_Intent or
            self.Description or
            self.Short_Description or
            self.Profiles is not None or
            self.Handling is not None or
            self.Information_Source is not None
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='STIXHeaderType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='STIXHeaderType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_=XML_NS, name_='STIXHeaderType'):
        pass
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='STIXHeaderType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.Title is not None:
            showIndent(lwrite, level, pretty_print)
            lwrite('<%s:Title>%s</%s:Title>%s' % (nsmap[namespace_], quote_xml(self.Title), nsmap[namespace_], eol_))
        for Package_Intent_ in self.Package_Intent:
            Package_Intent_.export(lwrite, level, nsmap, namespace_, name_='Package_Intent', pretty_print=pretty_print)
        for Description in self.Description:
            Description.export(lwrite, level, nsmap, namespace_, name_='Description', pretty_print=pretty_print)
        for Short_Description in self.Short_Description:
            Short_Description.export(lwrite, level, nsmap, namespace_, name_='Short_Description', pretty_print=pretty_print)
        if self.Profiles is not None:
            self.Profiles.export(lwrite, level, nsmap, namespace_, name_='Profiles', pretty_print=pretty_print)
        if self.Handling is not None:
            self.Handling.export(lwrite, level, nsmap, namespace_, name_='Handling', pretty_print=pretty_print)
        if self.Information_Source is not None:
            self.Information_Source.export(lwrite, level, nsmap, namespace_, name_='Information_Source', pretty_print=pretty_print)
    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_ == 'Title':
            Title_ = child_.text
            Title_ = self.gds_validate_string(Title_, node, 'Title')
            self.Title = Title_
        elif nodeName_ == 'Package_Intent':
            obj_ = stix_common_binding.ControlledVocabularyStringType.factory()
            obj_.build(child_)
            self.Package_Intent.append(obj_)
        elif nodeName_ == 'Description':
            obj_ = stix_common_binding.StructuredTextType.factory()
            obj_.build(child_)
            self.add_Description(obj_)
        elif nodeName_ == 'Short_Description':
            obj_ = stix_common_binding.StructuredTextType.factory()
            obj_.build(child_)
            self.add_Short_Description(obj_)
        elif nodeName_ == 'Profiles':
            obj_ = stix_common_binding.ProfilesType.factory()
            obj_.build(child_)
            self.set_Profiles(obj_)
        elif nodeName_ == 'Handling':
            obj_ = data_marking_binding.MarkingType.factory()
            obj_.build(child_)
            self.set_Handling(obj_)
        elif nodeName_ == 'Information_Source':
            obj_ = stix_common_binding.InformationSourceType.factory()
            obj_.build(child_)
            self.set_Information_Source(obj_)
# end class STIXHeaderType

class IndicatorsType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, Indicator=None):
        if Indicator is None:
            self.Indicator = []
        else:
            self.Indicator = Indicator
    def factory(*args_, **kwargs_):
        if IndicatorsType.subclass:
            return IndicatorsType.subclass(*args_, **kwargs_)
        else:
            return IndicatorsType(*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 hasContent_(self):
        if (
            self.Indicator
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='IndicatorsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='IndicatorsType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_=XML_NS, name_='IndicatorsType'):
        pass
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='IndicatorsType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Indicator_ in self.Indicator:
            Indicator_.export(lwrite, level, nsmap, namespace_, name_='Indicator', pretty_print=pretty_print)
    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_ == 'Indicator':
            from . import indicator
            obj_ = lookup_extension(child_, stix_common_binding.IndicatorBaseType).factory()
            obj_.build(child_)
            self.Indicator.append(obj_)

# end class IndicatorsType

class TTPsType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, TTP=None, Kill_Chains=None):
        if TTP is None:
            self.TTP = []
        else:
            self.TTP = TTP
        self.Kill_Chains = Kill_Chains
    def factory(*args_, **kwargs_):
        if TTPsType.subclass:
            return TTPsType.subclass(*args_, **kwargs_)
        else:
            return TTPsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_TTP(self): return self.TTP
    def set_TTP(self, TTP): self.TTP = TTP
    def add_TTP(self, value): self.TTP.append(value)
    def insert_TTP(self, index, value): self.TTP[index] = value
    def get_Kill_Chains(self): return self.Kill_Chains
    def set_Kill_Chains(self, Kill_Chains): self.Kill_Chains = Kill_Chains
    def hasContent_(self):
        if (
            self.TTP or
            self.Kill_Chains is not None
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='TTPsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='TTPsType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_=XML_NS, name_='TTPsType'):
        pass
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='TTPsType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for TTP_ in self.TTP:
            TTP_.export(lwrite, level, nsmap, namespace_, name_='TTP', pretty_print=pretty_print)
        if self.Kill_Chains is not None:
            self.Kill_Chains.export(lwrite, level, nsmap, namespace_, name_='Kill_Chains', pretty_print=pretty_print)
    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_ == 'TTP':
            from . import ttp
            obj_ = lookup_extension(child_, stix_common_binding.TTPBaseType).factory()
            obj_.build(child_)
            self.TTP.append(obj_)

        elif nodeName_ == 'Kill_Chains':
            obj_ = stix_common_binding.KillChainsType.factory()
            obj_.build(child_)
            self.set_Kill_Chains(obj_)
# end class TTPsType

class IncidentsType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, Incident=None):
        if Incident is None:
            self.Incident = []
        else:
            self.Incident = Incident
    def factory(*args_, **kwargs_):
        if IncidentsType.subclass:
            return IncidentsType.subclass(*args_, **kwargs_)
        else:
            return IncidentsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Incident(self): return self.Incident
    def set_Incident(self, Incident): self.Incident = Incident
    def add_Incident(self, value): self.Incident.append(value)
    def insert_Incident(self, index, value): self.Incident[index] = value
    def hasContent_(self):
        if (
            self.Incident
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='IncidentsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='IncidentsType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_=XML_NS, name_='IncidentsType'):
        pass
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='IncidentsType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Incident_ in self.Incident:
            Incident_.export(lwrite, level, nsmap, namespace_, name_='Incident', pretty_print=pretty_print)
    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_ == 'Incident':
            from . import incident
            obj_ = lookup_extension(child_, stix_common_binding.IncidentBaseType).factory()
            obj_.build(child_)
            self.Incident.append(obj_)

# end class IncidentsType

class CoursesOfActionType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, Course_Of_Action=None):
        if Course_Of_Action is None:
            self.Course_Of_Action = []
        else:
            self.Course_Of_Action = Course_Of_Action
    def factory(*args_, **kwargs_):
        if CoursesOfActionType.subclass:
            return CoursesOfActionType.subclass(*args_, **kwargs_)
        else:
            return CoursesOfActionType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Course_Of_Action(self): return self.Course_Of_Action
    def set_Course_Of_Action(self, Course_Of_Action): self.Course_Of_Action = Course_Of_Action
    def add_Course_Of_Action(self, value): self.Course_Of_Action.append(value)
    def insert_Course_Of_Action(self, index, value): self.Course_Of_Action[index] = value
    def hasContent_(self):
        if (
            self.Course_Of_Action
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='CoursesOfActionType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='CoursesOfActionType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_=XML_NS, name_='CoursesOfActionType'):
        pass
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='CoursesOfActionType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Course_Of_Action_ in self.Course_Of_Action:
            Course_Of_Action_.export(lwrite, level, nsmap, namespace_, name_='Course_Of_Action', pretty_print=pretty_print)
    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_ == 'Course_Of_Action':
            from . import course_of_action
            obj_ = lookup_extension(child_, stix_common_binding.CourseOfActionBaseType).factory()
            obj_.build(child_)
            self.Course_Of_Action.append(obj_)
# end class CoursesOfActionType

class CampaignsType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, Campaign=None):
        if Campaign is None:
            self.Campaign = []
        else:
            self.Campaign = Campaign
    def factory(*args_, **kwargs_):
        if CampaignsType.subclass:
            return CampaignsType.subclass(*args_, **kwargs_)
        else:
            return CampaignsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Campaign(self): return self.Campaign
    def set_Campaign(self, Campaign): self.Campaign = Campaign
    def add_Campaign(self, value): self.Campaign.append(value)
    def insert_Campaign(self, index, value): self.Campaign[index] = value
    def hasContent_(self):
        if (
            self.Campaign
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='CampaignsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='CampaignsType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_=XML_NS, name_='CampaignsType'):
        pass
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='CampaignsType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Campaign_ in self.Campaign:
            Campaign_.export(lwrite, level, nsmap, namespace_, name_='Campaign', pretty_print=pretty_print)
    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_ == 'Campaign':
            from . import campaign
            obj_ = lookup_extension(child_, stix_common_binding.CampaignBaseType).factory()
            obj_.build(child_)
            self.Campaign.append(obj_)
# end class CampaignsType

class ThreatActorsType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, Threat_Actor=None):
        if Threat_Actor is None:
            self.Threat_Actor = []
        else:
            self.Threat_Actor = Threat_Actor
    def factory(*args_, **kwargs_):
        if ThreatActorsType.subclass:
            return ThreatActorsType.subclass(*args_, **kwargs_)
        else:
            return ThreatActorsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Threat_Actor(self): return self.Threat_Actor
    def set_Threat_Actor(self, Threat_Actor): self.Threat_Actor = Threat_Actor
    def add_Threat_Actor(self, value): self.Threat_Actor.append(value)
    def insert_Threat_Actor(self, index, value): self.Threat_Actor[index] = value
    def hasContent_(self):
        if (
            self.Threat_Actor
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='ThreatActorsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='ThreatActorsType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_=XML_NS, name_='ThreatActorsType'):
        pass
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='ThreatActorsType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Threat_Actor_ in self.Threat_Actor:
            Threat_Actor_.export(lwrite, level, nsmap, namespace_, name_='Threat_Actor', pretty_print=pretty_print)
    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_ == 'Threat_Actor':
            from . import threat_actor
            obj_ = lookup_extension(child_, stix_common_binding.ThreatActorBaseType).factory()
            obj_.build(child_)
            self.Threat_Actor.append(obj_)
# end class ThreatActorsType

class ReportsType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, Report=None):
        if Report is None:
            self.Report = []
        else:
            self.Report = Report
    def factory(*args_, **kwargs_):
        if ReportsType.subclass:
            return ReportsType.subclass(*args_, **kwargs_)
        else:
            return ReportsType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Report(self): return self.Report
    def set_Report(self, Report): self.Report = Report
    def add_Report(self, value): self.Report.append(value)
    def insert_Report(self, index, value): self.Report[index] = value
    def hasContent_(self):
        if (
            self.Report
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, nsmap, namespace_=XML_NS, name_='ReportsType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s:%s%s' % (nsmap[namespace_], name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='ReportsType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, nsmap, XML_NS, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s:%s>%s' % (nsmap[namespace_], name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_=XML_NS, name_='ReportsType'):
        pass
    def exportChildren(self, lwrite, level, nsmap, namespace_=XML_NS, name_='ReportsType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        for Report_ in self.Report:
            Report_.export(lwrite, level, nsmap, namespace_, name_='Report', pretty_print=pretty_print)

    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_ == 'Report':
            from . import report
            obj_ = lookup_extension(child_, stix_common_binding.ReportBaseType).factory()
            obj_.build(child_)
            self.Report.append(obj_)
# end class TTPsType

GDSClassesMapping = {}

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, nsmap=None):
    if not nsmap:
        from stix.utils.nsparser import DEFAULT_STIX_NS_TO_PREFIX
        nsmap = DEFAULT_STIX_NS_TO_PREFIX

    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'STIX_Package'
        rootClass = STIXType
    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, nsmap, 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 = 'STIX_Package'
        rootClass = STIXType
    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 = 'STIX_Package'
        rootClass = STIXType
    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_="STIX_Package",
    #     namespacedef_='')
    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__ = [
    "STIXType",
    "STIXHeaderType",
    "IndicatorsType",
    "TTPsType",
    "IncidentsType",
    "CoursesOfActionType",
    "CampaignsType",
    "ThreatActorsType"
    ]


text:
# skeleton-object

## Introduction

Functional traits to use in objects

The traits specified here take into account some special configuration
parameters that can be set within the class.

### disallow_set (array)

    private static $class_configuration = array (
      'disallow_set' => array (
        'directory',
        'full_path',
        'password',
      ),
    );

Prevents the direct setting of some class variables

###  database_table (string)

    private static $class_configuration = [
      'database_table' => 'my_super_special_class',
    ];

Overrides the default strtolower(get_class()) as tablename

###  database_config_name (string)

    private static $class_configuration = [
      'database_config_name' => 'database_dsn',
	];

Overrides the default database when using Database::get();

###  table_field_id (string)

	private static $class_configuration = [
	  'table_field_id' => 'my_strange_id',
	];

###  table_field_created (string)

	private static $class_configuration = [
	  'table_field_created' => 'my_strange_created_field',
	];

###  table_field_updated (string)

	private static $class_configuration = [
	  'table_field_updated' => 'my_strange_updated_field',
	];

###  table_field_archived (string)

	private static $class_configuration = [
	  'table_field_archived' => 'my_strange_updated_archived',
	];

###  sluggable (string)

	private static $class_configuration = [
	  'sluggable' => 'my_field_to_slug',
	];

## Traits

### Model trait

This trait provides basic functionality for an object in the database

    $object = new MyClass();
    $object->database_field_1 = $value1;
    $object->database_field_2 = $value2;

    $dirty_fields = $object->get_dirty_fields();

This variable now contains [ 'database_field_1', 'database_field_2' ]

    $object->load_array( $_POST['form_for_object'] );

### Delete trait

    $object->delete()

deletes the object permanently

    $object->archive()

stores the archive-date in field 'archived'

    $object->restore()

resets the field 'archived'

## Get trait

    $object->get_info()

returns an array containing all database fields of the object

    $object->get_classname()

returns the classname of the object

    Object::get_by_id($id)

returns the object with id '$id'

    Object::get_all($sort, $direction)

returns all objects. If the an archived column exists, this will be taken into account

Optional parameters:

    $sort: the field to sort on
    $direction: ASC/DESC

## Slug trait

When using the Slug trait, it is possible to auto update the slug when
saving the object (default is false).

    /**
     * Set the auto update slug flag
     */
    \Skeleton\Object\Config::$auto_update_slug = true;

## UUID trait

When the UUID trait is in use, the field with the name "uuid" will be
populated with a random and unique UUIDv4.

## Child trait

Use this trait if you want to extend from a skeleton object and maybe
store information specific to the child in a separate table.

You'll need to adhere to a few simple rules for this to work:

  * The child class can only have the `Child` trait and must extend
    from a proper skeleton object
  * The child class can have its own database table which contains a
    reference to the parent. By default, this is the parent classname
    in lowercase appended with `_id`. You can override this via the
    class configuration `parent_field_id`.
  * If the child should not use a database table, set the
    `database_table` in the `class_configuration` of the child to
    `null`.
  * The parent class needs to have a field to store the classname of
    the child object. This value should be set via the class
    configuration `child_classname_field`.
  * A child can be casted into another child class via

    $new_class = $object->cast('another_child_class');

## Cache trait

Use this trait if you want to reduce the amount of database lookups. Activating
the cache can be done per Skeleton Object:

    use \Skeleton\Object\Cache;

There are 3 caching flavours:

### Memory
This is a per-process caching technique. Objects are stored in
a process cache. If the same object is requested multiple times, it is
only queried once from database.
Be aware that this cache does not take care of other PHP processes. If
an object gets updated in another process, your cache won't be invalidated.

    \Skeleton\Object\Config::$cache_handler = 'Memory';

### Memcache
Caching technique with php-memcache
(http://php.net/manual/en/book.memcache.php). Hostname, port and expire should
be set via cache config.

    \Skeleton\Object\Config::$cache_handler = 'Memcache';
    \Skeleton\Object\Config::$cache_handler_config = [
    	'hostname' => '127.0.0.1',
    	'port' => '11211',
    	'expire' => 600,
    ];

### Memcached
Caching technique with php-memcached
(http://php.net/manual/en/book.memcached.php). Hostname, port and expire
should be set via cache config.

    \Skeleton\Object\Config::$cache_handler = 'Memcached';
    \Skeleton\Object\Config::$cache_handler_config = [
    	'hostname' => '127.0.0.1',
    	'port' => '11211',
    	'expire' => 600,
    ];

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Http\Responses;

use Illuminate\Contracts\Support\Responsable;

class RedirectResponse implements Responsable
{
    protected $route;

    protected $message;

    public function __construct($route, $message)
    {
        $this->route = $route;
        $this->message = $message;
    }

    public function toResponse($request)
    {
        return redirect()
            ->to($this->route)
            ->with($this->message);
    }
}


text:
package com.youtube.rest.waterflow;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import java.sql.*;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.youtube.dao.PostgreCon;
import com.youtube.util.ToJSON;

@Path("/v1/waterflow")
public class V1_waterflow {

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response returnAllWaterflowData() throws Exception {

		PreparedStatement query = null;
		String returnString = null;
		Connection conn = null;
		Response rb = null;
		//JSONArray json = new JSONArray();

		try {

			conn = PostgreCon.PostgreConConnection().getConnection();
			query = conn.prepareStatement("SELECT * FROM WATERFLOW as flow");

			ResultSet rs = query.executeQuery();

			ToJSON convertor = new ToJSON();
			JSONArray json = new JSONArray();

			json = convertor.toJSONArray(rs);
			query.close();

			returnString = json.toString();

			//Schema308tube dao = new Schema308tube();

			//json = dao.queryAllPcParts();
			//returnString = json.toString();

			rb = Response.ok(returnString).build();

		}
		catch (Exception e) {
			e.printStackTrace();
		} finally{

			if(conn!=null){conn.close();}
		}

		return rb;
	}

}


text:
package org.apidesign.demo.minesweeper;

import org.netbeans.api.htmlui.OpenHTMLRegistration;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;

public class NbMain {
    private static final NbOpenURL openUrl = new NbOpenURL();

    private NbMain() {
    }

    @ActionID(
        category = "Games",
        id = "org.apidesign.demo.minesweeper.OpenPage"
    )
    @OpenHTMLRegistration(
        url="index.html",
        displayName = "Fair Mainsweeper!",
        iconBase = "org/apidesign/demo/minesweeper/icon.png"
    )
    @ActionReferences({
        @ActionReference(path = "Menu/Window", position = 153),
        @ActionReference(path = "Toolbars/Games")
    })
    public static void onPageLoad() throws Exception {
        Main.onPageLoad();
    }
}


text:
import fetch from 'isomorphic-fetch';
import { sortBy } from 'lodash';

import {
    REQUEST_SCHEDULE, RECEIVE_SCHEDULE
} from '~/constants/actions';

function requestSchedule(id, field) {
    return {
        type: REQUEST_SCHEDULE,
        id, field
    };
}

function receiveSchedule(id, field, parent, allocations) {
    return {
        type: RECEIVE_SCHEDULE,
        id, field, parent, allocations
    };
}

function fetchSchedule(id, field) {
    /*return async dispatch => {
        dispatch(requestSchedule(id, field));

        try {
            const response = await fetch(`/api/${field}s/${id}/schedules`);
            const { parent, allocations } = await response.json();

            const items = sortBy(allocations, [ 'day', 'hour' ]);

            dispatch(receiveSchedule(id, field, parent, items));
        } catch (error) {
            console.warn(error);
        }
    };*/
}

export { fetchSchedule };


text:
var path = require('path');

module.exports = {
    build: {
        env: require('./prod.env'),
        index: path.resolve(__dirname, '../dist/index.html'),
        assetsRoot: path.resolve(__dirname, '../dist'),
        assetsSubDirectory: 'static',
        assetsPublicPath: './',
        productionSourceMap: true,
        // Gzip off by default as many popular static hosts such as
        // Surge or Netlify already gzip all static assets for you.
        // Before setting to `true`, make sure to:
        // npm install --save-dev compression-webpack-plugin
        productionGzip: false,
        productionGzipExtensions: ['js', 'css']
    },
    dev: {
        env: require('./dev.env'),
        port: 8090,
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
            '/slsAdminApi': {
                target: 'http://slsadmin.api.sls.com',
                changeOrigin: true,
                pathRewrite: {
                    '^/slsAdminApi': ''
                }
            },
	        '/slsAdminQiniu': {
		        target: '//up-z2.qiniu.com',
		        changeOrigin: true,
		        pathRewrite: {
			        '^/slsAdminQiniu': ''
		        }
	        }
        },
        // CSS Sourcemaps off by default because relative paths are "buggy"
        // with this option, according to the CSS-Loader README
        // (https://github.com/webpack/css-loader#sourcemaps)
        // In our experience, they generally work as expected,
        // just be aware of this issue when enabling this option.
        cssSourceMap: false
    }
}


text:
package org.apache.geronimo.corba.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Map;

import javax.ejb.EJBObject;
import javax.rmi.CORBA.Util;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.omg.CORBA.SystemException;
import org.omg.CORBA.portable.ApplicationException;
import org.omg.CORBA.portable.RemarshalException;
import org.omg.CORBA.portable.ServantObject;
import org.omg.CORBA_2_3.portable.InputStream;
import org.omg.CORBA_2_3.portable.OutputStream;

/**
 * @version $Revision: 502310 $ $Date: 2007-02-01 10:34:57 -0800 (Thu, 01 Feb 2007) $
 */
public class StubMethodInterceptor implements MethodInterceptor {
    private static final Method ISIDENTICAL;

    static {
        try {
            ISIDENTICAL = EJBObject.class.getMethod("isIdentical", new Class[]{EJBObject.class});
        } catch (NoSuchMethodException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    private final Class type;
    private final Map operations;

    public StubMethodInterceptor(Class type) {
        this.type = type;
        this.operations = Collections.unmodifiableMap(org.apache.geronimo.corba.util.Util.mapMethodToOperation(type));
    }

    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        ClientContextHolderStub stub = (ClientContextHolderStub) proxy;

        // handle is identical in stub to avoid unnecessary round trip
        if (method.equals(ISIDENTICAL)) {
            org.omg.CORBA.Object otherObject = (org.omg.CORBA.Object) args[0];
            return new Boolean(stub._is_equivalent(otherObject));
        }

        // get the operation name object
        String operationName = (String) operations.get(method);
        if (operationName == null) {
            throw new IllegalStateException("Unknown method: " + method);
        }

        while (true) {
            // if this is a stub to a remote object we invoke over the wire
            if (!Util.isLocal(stub)) {

                InputStream in = null;
                try {
                    // create the request output stream
                    OutputStream out = (OutputStream) stub._request(operationName, true);

                    // write the arguments
                    Class[] parameterTypes = method.getParameterTypes();
                    for (int i = 0; i < parameterTypes.length; i++) {
                        Class parameterType = parameterTypes[i];
                        org.apache.geronimo.corba.util.Util.writeObject(parameterType, args[i], out);
                    }

                    // send the invocation
                    in = (InputStream) stub._invoke(out);

                    // read the result
                    Object result = org.apache.geronimo.corba.util.Util.readObject(method.getReturnType(), in);
                    return result;
                } catch (RemarshalException exception) {
                    continue;
                } catch (ApplicationException exception) {
                    org.apache.geronimo.corba.util.Util.throwException(method, (InputStream) exception.getInputStream());
                } catch (SystemException e) {
                    throw Util.mapSystemException(e);
                } finally {
                    stub._releaseReply(in);
                }
            } else {
                // get the servant
                ServantObject servantObject = stub._servant_preinvoke(operationName, type);
                if (servantObject == null) {
                    continue;
                }

                try {
                    // copy the arguments
                    Object[] argsCopy = Util.copyObjects(args, stub._orb());

                    // invoke the servant
                    Object result = null;
                    try {
                        result = method.invoke(servantObject.servant, argsCopy);
                    } catch (InvocationTargetException e) {
                        if (e.getCause() != null) {
                            throw e.getCause();
                        }
                        throw e;
                    }

                    // copy the result
                    result = Util.copyObject(result, stub._orb());

                    return result;
                } catch (Throwable throwable) {
                    // copy the exception
                    Throwable throwableCopy = (Throwable) Util.copyObject(throwable, stub._orb());

                    // if it is one of my exception rethrow it
                    Class[] exceptionTypes = method.getExceptionTypes();
                    for (int i = 0; i < exceptionTypes.length; i++) {
                        Class exceptionType = exceptionTypes[i];
                        if (exceptionType.isInstance(throwableCopy)) {
                            throw throwableCopy;
                        }
                    }

                    throw Util.wrapException(throwableCopy);
                } finally {
                    stub._servant_postinvoke(servantObject);
                }
            }
        }
    }
}


text:
package com.keekan.action;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import com.keekan.tool.BaseTools;

public class IndexAction extends  BaseAction{

	private static final long serialVersionUID = 1L;
	private String password;				//密码

	/**
	 * 验证首页
	 * @return
	 * @throws Exception
	 */
	public String checkIndex() throws Exception {
		HttpServletRequest request = BaseTools.getRequest();
		//session验证
		keeno = (Integer) BaseTools.getSessionAttribute("keeno");
		password = (String) BaseTools.getSessionAttribute("password");
		if (keeno != null) {
			if (password != null) {
				//查询数据库
				int userId = indexServe.checkKeeno(keeno, password);
				if (userId > 0 ) {
					//登录成功
					return SUCCESS;
				}else {
					return "login";
				}
			}
		}else {
			//cookies验证
			if (request.getCookies() != null) {
				for (Cookie cookie : request.getCookies()) {
					if (cookie.getName().equals("keeNumber")) {
						keeno = cookie.getVersion();
						BaseTools.getSession().setAttribute("keeno", keeno);
					}
					if (cookie.getName().equals("password")) {
						password = cookie.getValue();
						BaseTools.getSession().setAttribute("password", password);
					}
				}
				if (keeno != null) {
					if (password != null) {
						//查询数据库
						int userId = indexServe.checkKeeno(keeno, password);
						if (userId > 0 ) {
							//登录成功
							return SUCCESS;
						}else {
							return "login";
						}
					}
				}else {
					return "login";
				}
			}else {
				return "login";
			}
		}
		return "login";
	}

	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}


text:
package org.grails.core.util;

import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;

/**
 * Accesses class "properties": static fields, static getters, instance fields
 * or instance getters.
 *
 * Method and Field instances are cached for fast access.

 * @author Lari Hotari, Sagire Software Oy
 * @author Graeme Rocher
 * @deprecated Use {@link org.grails.datastore.mapping.reflect.ClassPropertyFetcher} instead
 */
@Deprecated
public class ClassPropertyFetcher {

    private final org.grails.datastore.mapping.reflect.ClassPropertyFetcher fetcher;

    public static void clearClassPropertyFetcherCache() {
        // no-op
    }

    public static ClassPropertyFetcher forClass(Class<?> c) {
        return new ClassPropertyFetcher(c);
    }

    protected ClassPropertyFetcher(Class<?> clazz) {
        this.fetcher = org.grails.datastore.mapping.reflect.ClassPropertyFetcher.forClass(clazz);
    }

    public Object getReference() {
        return BeanUtils.instantiate(fetcher.getJavaClass());
    }

    public PropertyDescriptor[] getPropertyDescriptors() {
        return fetcher.getPropertyDescriptors();
    }

    public boolean isReadableProperty(String name) {
        return fetcher.isReadableProperty(name);
    }

    public Object getPropertyValue(String name) {
        return getPropertyValue(name, false);
    }

    public Object getPropertyValue(final Object object,String name) {
        return fetcher.getPropertyValue(object, name);
    }

    public Object getPropertyValue(String name, boolean onlyInstanceProperties) {
        return fetcher.getPropertyValue(name);
    }

    public <T> T getStaticPropertyValue(String name, Class<T> c) {
        return fetcher.getPropertyValue(name,c);
    }

    public <T> T getPropertyValue(String name, Class<T> c) {
        return fetcher.getPropertyValue(name,c);
    }

    public Class<?> getPropertyType(String name) {
        return getPropertyType(name, false);
    }

    public Class<?> getPropertyType(String name, boolean onlyInstanceProperties) {
        return fetcher.getPropertyType(name);
    }

}


text:
package com.xiongbeer.cobweb.zk.task;

import com.xiongbeer.cobweb.conf.ZNodeStaticSetting;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by shaoxiong on 17-5-6.
 */
public class TaskWatcher {
    public static int WAITING_TIME = 2 * 1000;

    private CuratorFramework client;

    private Logger logger = LoggerFactory.getLogger(TaskWatcher.class);

    public TaskWatcher(CuratorFramework client) {
        this.client = client;
    }

    /**
     * 在没有可领取任务时阻塞
     * 刷新频率为WAITING_TIME/次
     */
    public void waitForTask() {
        try {
            while (true) {
                List<String> children = client.getChildren().forPath(ZNodeStaticSetting.TASKS_PATH);
                for (String child : children) {
                    byte[] data = client.getData()
                            .forPath(ZNodeStaticSetting.NEW_TASK_PATH + child);
                    TaskData taskData = new TaskData(data);
                    if (taskData.getStatus() == Task.Status.WAITING) {
                        return;
                    }
                }
                TimeUnit.MILLISECONDS.sleep(WAITING_TIME);
            }
        } catch (Exception e) {
            logger.warn("some thing get wrong when waiting for task.", e);
        }
    }
}


text:
_[www.codever.land/bookmarks/t/key-value-store](https://www.codever.land/bookmarks/t/key-value-store)_
---
#### [etcd home page](https://etcd.io/)
_https://etcd.io/_

**etcd** is a strongly consistent, distributed key-value store that provides a reliable way to store data that needs to be accessed by a distributed system or cluster of machines. It gracefully handle...
* **tags**: [etcd](../tagged/etcd.md), [distributed-storage](../tagged/distributed-storage.md), [distributed-computing](../tagged/distributed-computing.md), [key-value-store](../tagged/key-value-store.md)
* :octocat: **[source code](https://github.com/etcd-io/etcd)**
---


text:
name: Session
publisher: Kong Inc.
version: 2.2.0-x
redirect_from:
  - /hub/kong-in/sessions
  - /hub/kong-inc/sessions

desc: Support sessions for Kong Authentication Plugins.
description: |
  The Kong Session Plugin can be used to manage browser sessions for APIs proxied
  through the Kong API Gateway. It provides configuration and management for
  session data storage, encryption, renewal, expiry, and sending browser cookies.
  It is built using
  lua-resty-session

type: plugin
categories:
  - authentication

source_url: https://github.com/Kong/kong-plugin-session

kong_version_compatibility:
  community_edition:
    compatible:
      - 2.0.x
      - 1.5.x
      - 1.4.x
      - 1.3.x
      - 1.2.x
  enterprise_edition:
    compatible:
      - 1.3.x
      - 0.36-x
      - 0.35-x

params:
  name: session
  service_id: true
  route_id: true
  consumer_id: false
  config:
    - name: secret
      required: false
      default: random number generated from `kong.utils.random_string`
      value_in_examples: opensesame
      description: The secret that is used in keyed HMAC generation.
    - name: cookie_name
      required: false
      default: '`session`'
      description: The name of the cookie
    - name: cookie_lifetime
      required: false
      default: 3600
      description: The duration (in seconds) that the session will remain open
    - name: cookie_renew
      required: false
      default: 600
      description: The duration (in seconds) of a session remaining at which point the Plugin renews the session
    - name: cookie_path
      required: false
      default: '/'
      description: The resource in the host where the cookie is available
    - name: cookie_domain
      required: false
      default: Set using Nginx variable host, but may be overridden
      description: The domain with which the cookie is intended to be exchanged
    - name: cookie_samesite
      required: false
      default: 'Strict'
      description: 'Determines whether and how a cookie may be sent with cross-site requests. "Strict": the browser will send cookies only if the request originated from the website that set the cookie. "Lax": same-site cookies are withheld on cross-domain subrequests, but will be sent when a user navigates to the URL from an external site, for example, by following a link. "off": disables the same-site attribute so that a cookie may be sent with cross-site requests. https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#SameSite_cookies'
    - name: cookie_httponly
      required: false
      default: true
      description: Applies the `HttpOnly` tag so that the cookie is sent only to a server https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies
    - name: cookie_secure
      required: false
      default: true
      description: Applies the Secure directive so that the cookie may be sent to the server only with an encrypted request over the HTTPS protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies
    - name: cookie_discard
      required: false
      default: 10
      description: The duration (in seconds) after which an old session's TTL is updated that an old cookie is discarded.
    - name: storage
      required: false
      default: 'cookie'
      description: "Determines where the session data is stored. `kong`: stores encrypted session data into Kong's current database strategy (e.g. Postgres, Cassandra); the cookie will not contain any session data. `cookie`: stores encrypted session data within the cookie itself."
    - name: logout_methods
      required: false
      default: '[`"POST"`, `"DELETE"`]'
      description: 'The methods that may be used to end sessions: POST, DELETE, GET.'
    - name: logout_query_arg
      required: false
      default: session_logout
      description: The query argument passed to logout requests.
    - name: logout_post_arg
      required: false
      default: session_logout
      description: The post argument passed to logout requests. Do not change this property.
---

## Usage

The Kong Session **Plugin** can be configured globally or per entity (e.g., Service, Route)
and is always used in conjunction with another Kong Authentication **[Plugin]**. This
**Plugin** is intended to work similarly to the [multiple authentication] setup.

Once the Kong Session **Plugin** is enabled in conjunction with an Authentication **Plugin**,
it will run prior to credential verification. If no session is found, then the
authentication **Plugin** will run and credentials will be checked as normal. If the
credential verification is successful, then the session **Plugin** will create a new
session for usage with subsequent requests.

When a new request comes in, and a session is present, then the Kong Session
**Plugin** will attach the `ngx.ctx` variables to let the authentication
**Plugin** know that authentication has already occured via session validation.
Since this configuration is a logical OR scenario, it is desired that anonymous
access be forbidden, then the [Request Termination] **Plugin** should be
configured on an anonymous consumer. Failure to do so will allow unauthorized
requests. For more information please see section on [multiple authentication].

### Setup With a Database

For usage with [Key Auth] **Plugin**

1. Create an example Service and a Route

   Issue the following cURL request to create `example-service` pointing to
   mockbin.org, which will echo the request:

   ```bash
   $ curl -i -X POST \
     --url http://localhost:8001/services/ \
     --data 'name=example-service' \
     --data 'url=http://mockbin.org/request'
   ```

   Add a route to the Service:

   ```bash
   $ curl -i -X POST \
     --url http://localhost:8001/services/example-service/routes \
     --data 'paths[]=/sessions-test'
   ```

   The url `http://localhost:8000/sessions-test` will now echo whatever is being
   requested.

1. Configure the key-auth **Plugin** for the Service

   Issue the following cURL request to add the key-auth **Plugin** to the Service:

   ```bash
   $ curl -i -X POST \
     --url http://localhost:8001/services/example-service/plugins/ \
     --data 'name=key-auth'
   ```

   Be sure to note the created **Plugin** `id` - it will be needed later.

1. Verify that the key-auth **Plugin** is properly configured

   Issue the following cURL request to verify that the [key-auth][key-auth]
   **Plugin** was properly configured on the Service:

   ```bash
   $ curl -i -X GET \
     --url http://localhost:8000/sessions-test
   ```

   Since the required header or parameter `apikey` was not specified, and
   anonymous access was not yet enabled, the response should be `401 Unauthorized`:

1. Create a Consumer and an anonymous Consumer

   Every request proxied and authenticated by Kong must be associated with a
   Consumer. You'll now create a Consumer named `anonymous_users` by issuing
   the following request:

   ```bash
   $ curl -i -X POST \
     --url http://localhost:8001/consumers/ \
     --data "username=anonymous_users"
   ```

   Be sure to note the Consumer `id` - you'll need it in a later step.

   Now create a consumer that will authenticate via sessions

   ```bash
   $ curl -i -X POST \
     --url http://localhost:8001/consumers/ \
     --data "username=fiona"
   ```

1. Provision key-auth credentials for your Consumer

   ```bash
   $ curl -i -X POST \
     --url http://localhost:8001/consumers/fiona/key-auth/ \
     --data 'key=open_sesame'
   ```

1. Enable anonymous access

   You'll now re-configure the key-auth **Plugin** to permit anonymous access by
   issuing the following request (**replace the uuids below by the `id` value
   from previous steps**):

   ```bash
   $ curl -i -X PATCH \
     --url http://localhost:8001/plugins/<your-key-auth-plugin-id> \
     --data "config.anonymous=<anonymous_consumer_id>"
   ```

1. Add the Kong Session **Plugin** to the service

   ```bash
   $ curl -X POST http://localhost:8001/services/example-service/plugins \
       --data "name=session"  \
       --data "config.storage=kong" \
       --data "config.cookie_secure=false"
   ```

   > Note: cookie_secure is true by default, and should always be true, but is set to
   > false for the sake of this demo in order to avoid using HTTPS.

1. Add the Request Termination **Plugin**

   To disable anonymous access to only allow users access via sessions or via
   authentication credentials, enable the Request Termination **Plugin**.

   ```bash
   $ curl -X POST http://localhost:8001/services/example-service/plugins \
       --data "name=request-termination"  \
       --data "config.status_code=403" \
       --data "config.message=So long and thanks for all the fish!" \
       --data "consumer.id=<anonymous_consumer_id>"
   ```

### Setup Without a Database

Add all these to the declarative config file:

```yaml
services:
  - name: example-service
    url: http://mockbin.org/request

routes:
  - service: example-service
    paths: ['/sessions-test']

consumers:
  - username: anonymous_users
    # manually set to fixed uuid in order to use it in key-auth plugin
    id: 81823632-10c0-4098-a4f7-31062520c1e6
  - username: fiona

keyauth_credentials:
  - consumer: fiona
    key: open_sesame

plugins:
  - name: key-auth
    service: example-service
    config:
      # using the anonymous consumer fixed uuid (can't use the username)
      anonymous: 81823632-10c0-4098-a4f7-31062520c1e6
      # cookie_secure is true by default, and should always be true,
      # but is set to false for the sake of this demo in order to avoid using HTTPS.
      cookie_secure: false
  - name: session
    config:
      storage: kong
      cookie_secure: false
  - name: request-termination
    service: example-service
    consumer: anonymous_users
    config:
      status_code: 403
      message: 'So long and thanks for all the fish!'
```

### Verification

1. Check that Anonymous requests are disabled

   ```bash
     $ curl -i -X GET \
       --url http://localhost:8000/sessions-test
   ```

   Should return `403`.

2. Verify that a user can authenticate via sessions

   ```bash
   $ curl -i -X GET \
     --url http://localhost:8000/sessions-test?apikey=open_sesame
   ```

   The response should now have the `Set-Cookie` header. Make sure that this
   cookie works.

   If cookie looks like this:

   ```
   Set-Cookie: session=emjbJ3MdyDsoDUkqmemFqw..|1544654411|4QMKAE3I-jFSgmvjWApDRmZHMB8.; Path=/; SameSite=Strict; HttpOnly
   ```

   Use it like this:

   ```bash
     $ curl -i -X GET \
       --url http://localhost:8000/sessions-test \
       -H "cookie:session=emjbJ3MdyDsoDUkqmemFqw..|1544654411|4QMKAE3I-jFSgmvjWApDRmZHMB8."
   ```

   This request should succeed, and `Set-Cookie` response header will not appear
   until renewal period.

3. You can also now verify cookie is attached to browser session: Navigate to
   http://localhost:8000/sessions-test which should return `403`
   and see the message "So long and thanks for all the fish!"
4. In same browser session, navigate to http://localhost:8000/sessions-test?apikey=open_sesame
   which should return `200`, authenticated via key-auth key query param.
5. In same browser session, navigate to http://localhost:8000/sessions-test,
   which will now use the session cookie that was granted by the Kong Session
   **Plugin**.

### Defaults

By default, the Kong Session **Plugin** favors security using a `Secure`, `HTTPOnly`,
`Samesite=Strict` cookie. `cookie_domain` is automatically set using Nginx
variable host, but can be overridden.

### Session Data Storage

The session data can be stored in the cookie itself (encrypted) `storage=cookie`,
or inside [Kong](#-kong-storage-adapter). The session data stores these context
variables:

```
ngx.ctx.authenticated_consumer.id
ngx.ctx.authenticated_credential.id
ngx.ctx.authenticated_groups
```

The plugin also sets a `ngx.ctx.authenticated_session` for communication between
the `access` and `header_filter` phases in the plugin.

### Groups

Authenticated groups are stored on `ngx.ctx.authenticated_groups` from other
authentication plugins and the session plugin will store them in the data of
the current session. Since the session plugin runs before authentication
plugins, it will also set `authenticated_groups` associated headers.

## Kong Storage Adapter

the Kong Session **Plugin** extends the functionality of [lua-resty-session] with its own
session data storage adapter when `storage=kong`. This will store encrypted
session data into the current database strategy (e.g. postgres, cassandra etc.)
and the cookie will not contain any session data. Data stored in the database is
encrypted and the cookie will contain only the session id, expiration time and
HMAC signature. Sessions will use the built-in Kong DAO `ttl` mechanism which destroys
sessions after specified `cookie_lifetime` unless renewal occurs during normal
browser activity. It is recommended that the application logout via XHR request
(or something similar) to manually handle redirects.

## Logging Out

It is typical to provide users the ability to log out (i.e. to manually destroy) their
current session. Logging out is possible with either query params or `POST` params in
the request URL. The config's `logout_methods` allows the **Plugin** to limit logging
out based on the HTTP verb. When `logout_query_arg` is set, it will check the
presence of the URL query param specified, and likewise when `logout_post_arg`
is set it will check the presence of the specified variable in the request body.
Allowed HTTP verbs are `GET`, `DELETE`, and `POST`. When there is a session
present and the incoming request is a logout request, the Kong Session **Plugin** will
return a 200 before continuing in the **Plugin** run loop, and the request will not
continue to the upstream.

## Known Limitations

Due to limitations of OpenResty, the `header_filter` phase cannot connect to the
database, which poses a problem for initial retrieval of cookie (fresh session).
There is a small window of time where cookie is sent to client, but database
insert has not yet been committed, as database call is in `ngx.timer` thread.
Current workaround is to wait some interval of time (~100-500ms) after
`Set-Cookie` header is sent to client before making subsequent requests. This is
_not_ a problem during session renewal period as renew happens in `access` phase.

[plugin]: https://docs.konghq.com/hub/
[lua-resty-session]: https://github.com/bungle/lua-resty-session
[multiple authentication]: https://docs.konghq.com/0.14.x/auth/#multiple-authentication
[key auth]: https://docs.konghq.com/hub/kong-inc/key-auth/
[request termination]: https://docs.konghq.com/hub/kong-inc/request-termination/


text:
var path = require('path')
var request = require('supertest')
var utils = require('../support/utils')

var FIXTURES_DIR = path.join(__dirname, '..', 'fixtures')

// builtin
var fs = require('fs');
var assert = require('assert');

// local
var hbs = require('../../').create();

hbs.registerHelper('make_error', function () {
  throw new TypeError('oops!')
})

hbs.registerHelper('link_to', function(context) {
  return "" + context.body + "";
});

hbs.registerHelper('link_to2', function(title, context) {
  return "" + title + ""
});

hbs.registerHelper('list', function(items, context) {
  var out = '
'

  for(var i=0; i<items.length; ++i) {
    out = out + "
" + context.fn(items[i]) + "
";
  }
  return out + "
";
});

hbs.registerPartial('link2', '{{name}}');
hbs.registerPartials(path.join(__dirname, 'views', 'partials'))

var app = null

before(function () {
  if (utils.nodeVersionCompare(0.10) < 0) {
    this.skip()
    return
  }

  var express = require('express')

  app = express()

  // manually set render engine, under normal circumstances this
  // would not be needed as hbs would be installed through npm
  app.engine('hbs', hbs.__express)

  // render html files using hbs as well
  // tests detecting the view engine extension
  app.engine('html', hbs.__express)

  // set the view engine to use handlebars
  app.set('view engine', 'hbs')
  app.set('views', [
    path.join(__dirname, 'views'),
    path.join(__dirname, 'views_secondary')
  ])

  app.use(express.static(path.join(__dirname, 'public')))

  // expose app and response locals in views
  hbs.localsAsTemplateData(app)
  app.locals.father = 'Alan'

  app.get('/', function (req, res) {
    res.render('index', {
      title: 'Express Handlebars Test',
      // basic test
      name: 'Alan',
      hometown: 'Somewhere, TX',
      kids: [
        { name: 'Jimmy', age: '12' },
        { name: 'Sally', age: '4' }
      ],
      // path test
      person: { name: 'Alan' },
      company: { name: 'Rad, Inc.' },
      // escapee test
      escapee: '<jail>escaped</jail>',
      // helper test
      listClassName: 'my-list',
      posts: [{ url: '/hello-world', body: 'Hello World!' }],
      // helper with string
      posts2: [{ url: '/hello-world', body: 'Hello World!' }],
      // for block helper test
      people: [
        { firstName: 'Yehuda', lastName: 'Katz' },
        { firstName: 'Carl', lastName: 'Lerche' },
        { firstName: 'Alan', lastName: 'Johnson' }
      ],
      people2: [
        { name: { firstName: 'Yehuda', lastName: 'Katz' } },
        { name: { firstName: 'Carl', lastName: 'Lerche' } },
        { name: { firstName: 'Alan', lastName: 'Johnson' } }
      ],
      // for partial test
      people3: [
        { name: 'Alan', id: 1 },
        { name: 'Yehuda', id: 2 }
      ]
    })
  })

  app.get('/html', function (req, res) {
    res.render('index.html', {
      title: 'Express Handlebars Test',
      // basic test
      name: 'Alan',
      hometown: 'Somewhere, TX',
      kids: [
        { name: 'Jimmy', age: '12' },
        { name: 'Sally', age: '4' }],
      // path test
      person: { name: 'Alan' },
      company: { name: 'Rad, Inc.' },
      // escapee test
      escapee: '<jail>escaped</jail>',
      // helper test
      listClassName: 'my-list',
      posts: [{ url: '/hello-world', body: 'Hello World!' }],
      // helper with string
      posts2: [{ url: '/hello-world', body: 'Hello World!' }],
      // for block helper test
      people: [
        { firstName: 'Yehuda', lastName: 'Katz' },
        { firstName: 'Carl', lastName: 'Lerche' },
        { firstName: 'Alan', lastName: 'Johnson' }
      ],
      people2: [
        { name: { firstName: 'Yehuda', lastName: 'Katz' } },
        { name: { firstName: 'Carl', lastName: 'Lerche' } },
        { name: { firstName: 'Alan', lastName: 'Johnson' } }
      ],
      // for partial test
      people3: [
        { name: 'Alan', id: 1 },
        { name: 'Yehuda', id: 2 }
      ]
    })
  })

  app.get('/helper-error', function (req, res) {
    res.render('error')
  })

  app.get('/syntax-error', function (req, res) {
    res.render('syntax-error', {
      cache: true
    })
  })

  app.get('/syntax-error-layout', function (req, res) {
    res.render('blank', { layout: 'bad_layout' })
  })

  app.get('/partials', function (req, res) {
    res.render('partials', { layout: false })
  })

  app.get('/escape', function (req, res) {
    res.render('escape', { title: 'foobar', layout: false })
  })

  app.get('/locals', function (req, res) {
    res.locals.person = 'Alan'
    res.render('locals', {
      layout: false,
      kids: [{ name: 'Jimmy' }, { name: 'Sally' }]
    })
  })

  app.get('/locals-cached', function (req, res) {
    res.locals.person = 'Alan'
    res.render('locals', {
      layout: false,
      cache: true,
      kids: [{ name: 'Jimmy' }, { name: 'Sally' }]
    })
  })

  app.get('/locals-model', function (req, res) {
    res.locals.person = new Person('Alan', 'Smith')
    res.render('locals', {
      layout: false,
      kids: [new Person('Jimmy', 'Smith'), new Person('Sally', 'Smith')]
    })
  })

  app.get('/globals', function (req, res) {
    res.render('globals', {
      layout: 'layout_globals',
      kids: [{ name: 'Jimmy' }, { name: 'Sally' }]
    })
  })

  app.get('/secondary', function (req, res) {
    res.render('secondary', {
      text: '  index body :)',
      title: 'Express Handlebars Test'
    })
  })

  app.get('/layout-no-exist', function (req, res) {
    res.render('blank', {
      layout: 'noexist_layout'
    })
  })

  app.use(function (err, req, res, next) {
    res.status(500).send(err.stack.toString())
  })
})

test('index', function(done) {
  request(app)
    .get('/')
    .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'index.html'), 'utf8'))
    .end(done)
});

test('helper error', function (done) {
  request(app)
    .get('/helper-error')
    .expect(500)
    .expect(shouldHaveFirstLineEqual('TypeError: ' + path.join(__dirname, 'views', 'error.hbs') + ': oops!'))
    .end(done)
})

test('partials', function(done) {
  request(app)
    .get('/partials')
    .expect(shouldHaveFirstLineEqual('Test Partial 1Test Partial 2Test Partial 3Test Partial 4Test Partial 5'))
    .end(done)
});

test('html extension', function(done) {
  request(app)
    .get('/html')
    .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'index.html'), 'utf8'))
    .end(done)
});

test('syntax error', function(done) {
  request(app)
    .get('/syntax-error')
    .expect(500)
    .expect(shouldHaveFirstLineEqual('Error: ' + path.join(__dirname, 'views', 'syntax-error.hbs') + ': Parse error on line 1:'))
    .end(done)
});

test('syntax error cached', function (done) {
  request(app)
    .get('/syntax-error')
    .expect(500)
    .expect(shouldHaveFirstLineEqual('Error: ' + path.join(__dirname, 'views', 'syntax-error.hbs') + ': Parse error on line 1:'))
    .end(done)
})

test('syntax error layout', function (done) {
  request(app)
    .get('/syntax-error-layout')
    .expect(500)
    .expect(shouldHaveFirstLineEqual('Error: ' + path.join(__dirname, 'views', 'bad_layout.hbs') + ': Parse error on line 3:'))
    .end(done)
})

test('escape for frontend', function(done) {
  request(app)
    .get('/escape')
    .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'escape.html'), 'utf8'))
    .end(done)
});

test('response locals', function(done) {
  request(app)
    .get('/locals')
    .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'locals.html'), 'utf8'))
    .end(done)
});

test('response locals cached', function(done) {
  request(app)
    .get('/locals-cached')
    .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'locals.html'), 'utf8'))
    .end(function (error) {
      if (error) return done(error)
      request(app)
        .get('/locals-cached')
        .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'locals.html'), 'utf8'))
        .end(done)
    })
});

test('response locals model', function(done) {
  request(app)
    .get('/locals-model')
    .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'locals.html'), 'utf8'))
    .end(done)
});

test('response globals', function(done) {
  request(app)
    .get('/globals')
    .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'globals.html'), 'utf8'))
    .end(done)
});

test('multiple views directories', function(done) {
  request(app)
    .get('/secondary')
    .expect(fs.readFileSync(path.join(FIXTURES_DIR, 'index_no_layout.html'), 'utf8'))
    .end(done)
});

test('layout does not exist', function (done) {
  request(app)
    .get('/layout-no-exist')
    .expect(500)
    .expect(/Error: ENOENT.*noexist_layout\.hbs/)
    .end(done)
})

test('app.render', function (done) {
  app.render('blank', function (err, str) {
    if (err) return done(err)
    assert.ok(/  index body :\)/.test(str))
    done()
  })
})

function shouldHaveFirstLineEqual (str) {
  return function (res) {
    assert.strictEqual(res.text.split(/\r?\n/)[0], str)
  }
}

function Person (firstName, lastName) {
  this.firstName = firstName
  this.lastName = lastName
}

Person.prototype.toString = function toString () {
  return this.name()
}

Person.prototype.name = function name () {
  return this.firstName
}


text:
#ifndef __USBD_CDC_H__
#define __USBD_CDC_H__

/*--------------------------- Event handling routines ------------------------*/

extern           void usbd_vcom_serial2usb            (void);
extern           void usbd_vcom_chkserstate           (void);
extern           void usbd_vcom_usb2serial            (void);
extern           void usbd_cdc_ser_flush              (void);

extern           void USBD_CDC_SOF_Event              (void);

extern           void USBD_CDC_EP_INTIN_Event         (U32 event);
extern           void USBD_CDC_EP_BULKIN_Event        (U32 event);
extern           void USBD_CDC_EP_BULKOUT_Event       (U32 event);
extern           void USBD_CDC_EP_BULK_Event          (U32 event);

extern     void USBD_RTX_CDC_EP_INTIN_Event     (void);
extern     void USBD_RTX_CDC_EP_BULKIN_Event    (void);
extern     void USBD_RTX_CDC_EP_BULKOUT_Event   (void);
extern     void USBD_RTX_CDC_EP_BULK_Event      (void);

#endif  /* __USBD_CDC_H__ */


text:
import warnings
import os
from flask import Flask, request
import json
#import psycopg2
from configparser import ConfigParser

#from flask import Flask
#from flask import request
from flask import make_response
from flask import render_template

#import chatbot
#import messenger

app = Flask(__name__)

#PAT = 'EAACVleRe26oBAJverSWgEZB1PKZAwcmBZAJwfowPNoaXWdkL8hS7Dc31VEQ5DeZAMUKxC3V9GFgLpgFZABm3XtCWUAZCqbzsZBQ4WR9itFs9mw2B37XID9Na4k2bcjjFtaCIRR2ZAgWUmkDRMyPIUnWi3dM4thsNpMUphtzOSIRGNQZDZD'
bot = None

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/doschatbot')
def doschatbot():
    return render_template('page.html')

@app.route('/doschatbot2')
def doschatbot2():
    return render_template('page2.html')

@app.route('/aribaticket')
def doschatbot3():
    return render_template('page3.html')

@app.route('/kb')
def doschatbotkb():
    return render_template('page4.html')

@app.route('/ariba')
def doschatbotariba():
    return render_template('page5.html')

@app.route('/webhook', methods=['GET'])
def handle_verification():
  print("Handling Verification.")
  if request.args.get('hub.verify_token', '') == 'hola-mundo':
    print("Verification successful!")
    return request.args.get('hub.challenge', '')
  else:
    print("Verification failed!")
    return 'Error, wrong validation token'

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)
    # connect()
    intent = req["result"]["metadata"]["intentName"]
    print(intent)

    print("Request:")
    print(json.dumps(req))

    res = makeWebhookResult()

    res = json.dumps(res, indent=4)

    print(res)
    r = make_response(res)

    r.headers['Content-Type'] = 'application/json'

    return r

if __name__ == '__main__':
    # Suppress nltk warnings about not enough data
    warnings.filterwarnings('ignore', '.*returning an arbitrary sample.*',)

    app.run(port=3000, debug=True)


text:
package com.microfocus.application.automation.tools.common;

public interface Func<TResult> {

    public TResult execute();
}