示例#1
0
	def saveDoc(self):
		"""
			Save the XML configuration file to disk.
		"""
		f = open(C.CONFIG_FILE,'w')
		PrettyPrint(self.agents,f)
		f.close()
示例#2
0
def convertNodeToString(node):
    """ convert a Domlette tree to a string """

    buf = cStringIO.StringIO()
    PrettyPrint(node, stream=buf, encoding='UTF-8')
    result = buf.getvalue()
    buf.close()
    return result
示例#3
0
 def commitTransaction(self, txnService):
     #write out the dom
     output = file(self._location, 'w+')
     from Ft.Xml.Domlette import Print, PrettyPrint
     if self.prettyPrint:
         PrettyPrint(doc, output)
     else:
         Print(doc, output)
     output.close()
     self._defaultModel = None
示例#4
0
 def writexml(self,
              uri,
              tmpDir='/tmp',
              sha1sum=False,
              compress=None,
              sign=None):
     f = File(uri,
              File.write,
              sha1sum=sha1sum,
              compress=compress,
              sign=sign)
     PrettyPrint(self.rootNode(), stream=f)
     f.close()
    def xml2Peach(self, url):
        factory = InputSourceFactory(resolver=_PeachResolver(),
                                     catalog=GetDefaultCatalog())
        isrc = factory.fromUri(url)
        doc = Ft.Xml.Domlette.NonvalidatingReader.parse(isrc)

        peachDoc = Ft.Xml.Domlette.implementation.createDocument(
            EMPTY_NAMESPACE, None, None)
        child = doc.firstChild
        while (child.nodeName == "#comment"):
            child = child.nextSibling

        self.handleElement(child, peachDoc)

        # Get the string representation
        import cStringIO
        buff = cStringIO.StringIO()
        PrettyPrint(peachDoc.firstChild, stream=buff, encoding="utf8")
        value = buff.getvalue()
        buff.close()

        return self.XmlContainer % value
示例#6
0
def fetch(params, debug=None, nopost=None):
    if (not params.has_key('resultxpath')):
        return None

    xhtml = send(params, debug, nopost)
    if debug: print >> sys.stderr, 'checking results'
    # make it a 4suite document
    doc = NonvalidatingReader.parseString(xhtml, params['action'])
    context = Context(doc, processorNss={"h": XHTML_NS})
    #Compute the XPath against the context
    results = Compile(params['resultxpath'])
    results = results.evaluate(context)
    res = []
    for a in results:
        tf = cStringIO.StringIO()
        PrettyPrint(a, tf)
        t = tf.getvalue()
        res.append(t)
        tf.close()
    results = res
    if debug: print >> sys.stderr, 'done', params['action']
    return (results, xhtml)
示例#7
0
    def editConfig(self,
                   defaultoperation,
                   testoption,
                   erroroption,
                   target,
                   confignode,
                   targetnode=None):
        """
			Apply the request specified in confignode to the targetnode.
			@type defaultoperation: MERGE_OPERATION | REPLACE_OPERATION | NONE_OPERATION 
			@param defaultoperation : as specified in NETCONF protocol
			@type testoption : SET | TEST_AND_SET 
			@param testoption : as specified in NETCONF protocol
			@type erroroption : STOP_ON_ERROR | IGNORE_ERROR | ROLL_BACK_ON_ERROR 
			@param erroroption : as specified in NETCONF protocol
			@type target : RUNNING_TARGET | CANDIDATE_TARGET | STARTUP_TARGET
			@param target : as specified in NETCONF protocol
			@type targetnode : string
			@param targetnode : if the target is RUNNING_TARGET or STARTUP_TARGET it will be ignored otherwise should be the node of the 				CANDIDATE_TARGET that this module should process
			@rtype: ModuleReply
			@return: It should return a success or error message.
			** Relates to the netconf edit-config operation
		"""

        error = None

        if (target in [C.URL, C.RUNNING]):
            xmlreply = ModuleReply(
                error_type=ModuleReply.APPLICATION,
                error_tag=ModuleReply.OPERATION_NOT_SUPPORTED,
                error_severity=ModuleReply.ERROR,
                error_message="OPERATION-NOT-SUPPORTED")
            return xmlreply

        if defaultoperation == "replace":
            f = open(
                C.YENCAP_HOME + '/Modules/VERMONT_Module/' + target + '.xml',
                'w')
            PrettyPrint(confignode, f)
            f.close()
            return ModuleReply()

        # draft-ietf-netconf-prot-11 says: "the default value for the default-operation is merge"
        # in this datamodel merge will replace all nodes with the same type and id it finds in configNodeRoot
        # and adds all it can't find
        elif defaultoperation == "merge":

            if not os.path.exists(C.YENCAP_HOME + '/Modules/VERMONT_Module/' +
                                  target + '.xml'):
                ipfixConfigBase = '<ipfixConfig xmlns="urn:ietf:params:xml:ns:ipfix-config"></ipfixConfig>'
                xmlfile = file(
                    C.YENCAP_HOME + '/Modules/VERMONT_Module/' + target +
                    '.xml', 'w')
                xmlfile.write(ipfixConfigBase)
                xmlfile.close()

            dataFile = C.YENCAP_HOME + '/Modules/VERMONT_Module/' + target + '.xml'
            configDoc = NonvalidatingReader.parseUri("file:" + dataFile)

            configNodeRoot = configDoc.documentElement

            for newProcess in confignode.documentElement.childNodes:
                if newProcess.nodeType == Node.ELEMENT_NODE:
                    processName = newProcess.localName
                    processId = newProcess.getAttributeNS(
                        EMPTY_NAMESPACE, "id")

                    isNew = True

                    for oldProcess in configDoc.documentElement.childNodes:

                        if oldProcess.nodeType == Node.ELEMENT_NODE:

                            if oldProcess.tagName == processName:
                                #oldProcessId = oldProcess.attributes[(None, u'id')].value
                                oldProcessId = oldProcess.getAttributeNS(
                                    EMPTY_NAMESPACE, "id")
                                print "Old ProcessId:" + oldProcessId
                                if oldProcessId == processId:
                                    isNew = False
                                    configNodeRoot.replaceChild(
                                        newProcess, oldProcess)

                    if isNew:
                        print "appending"
                        configNodeRoot.appendChild(newProcess)

        #otherwise, every node has its own operation, create, delete, replace or merge
        #the data model ipfix-config-data-model has to treat merge just as replace, as detailed
        #editing of some parts of the data are impossible, due to possible ambiguities.
        else:
            if not os.path.exists(C.YENCAP_HOME + '/Modules/VERMONT_Module/' +
                                  target + '.xml'):
                ipfixConfigBase = '<ipfixConfig xmlns="urn:ietf:params:xml:ns:ipfix-config"></ipfixConfig>'
                xmlfile = file(
                    C.YENCAP_HOME + '/Modules/VERMONT_Module/' + target +
                    '.xml', 'w')
                xmlfile.write(ipfixConfigBase)
                xmlfile.close()

            dataFile = C.YENCAP_HOME + '/Modules/VERMONT_Module/' + target + '.xml'
            configDoc = NonvalidatingReader.parseUri("file:" + dataFile)

            for newProcess in confignode.documentElement.childNodes:
                if newProcess.nodeType == Node.ELEMENT_NODE:
                    processName = newProcess.localName
                    operation = newProcess.getAttributeNS(
                        'ietf:params:xml:ns:netconf:base:1.0', "operation")
                    processId = newProcess.getAttributeNS(
                        EMPTY_NAMESPACE, "id")

                    print processName
                    print operation
                    print processId

                    if processName == "ipfixConfig":
                        continue
                    if processId == None:
                        error = "Config data to add has errors!"
                        moduleReply = ModuleReply(
                            error_type=ModuleReply.APPLICATION,
                            error_tag=ModuleReply.OPERATION_FAILED,
                            error_severity=ModuleReply.ERROR,
                            error_message=error)
                        return moduleReply

                    if operation == None:
                        error == "If no defaultoperation is chosen, every process has to have its own operation!"
                        moduleReply = ModuleReply(
                            error_type=ModuleReply.APPLICATION,
                            error_tag=ModuleReply.OPERATION_FAILED,
                            error_severity=ModuleReply.ERROR,
                            error_message=error)
                        return moduleReply

                    if operation == "create":
                        configDoc.documentElement.appendChild(newProcess)
                    else:
                        error = processName + " " + "not found!"

                        for oldProcess in configDoc.documentElement.childNodes:

                            if oldProcess.nodeType == Node.ELEMENT_NODE:
                                if oldProcess.tagName == processName:
                                    #oldProcessId = oldProcess.attributes[(None, u'id')].value
                                    oldProcessId = oldProcess.getAttributeNS(
                                        EMPTY_NAMESPACE, "id")
                                    if oldProcessId == processId:

                                        if operation == "delete":
                                            configDoc.documentElement.removeChild(
                                                oldProcess)
                                            error = None
                                        elif operation == "replace" or operation == "merge":
                                            configDoc.documentElement.replaceChild(
                                                newProcess, oldProcess)
                                            error = None
                                        if error != None:
                                            if erroroption == "stop-on-error":
                                                modulereply = ModuleReply(
                                                    error_type=ModuleReply.
                                                    APPLICATION,
                                                    error_tag=ModuleReply.
                                                    OPERATION_FAILED,
                                                    error_severity=ModuleReply.
                                                    ERROR,
                                                    error_message=error)
                                                return modulereply

        xmlFile = open(
            C.YENCAP_HOME + '/Modules/VERMONT_Module/' + target + '.xml', 'w')
        PrettyPrint(configDoc, xmlFile)
        xmlFile.close()

        if error == None:
            modulereply = ModuleReply()
        else:
            modulereply = ModuleReply(error_type=ModuleReply.APPLICATION,
                                      error_tag=ModuleReply.OPERATION_FAILED,
                                      error_severity=ModuleReply.ERROR,
                                      error_message=error)
            return modulereply
        return modulereply
 def writeCTData(self,outputCT):
     conFile = open(outputCT,'w')
     PrettyPrint(self.doc,conFile)
     conFile.close()
示例#9
0
def Test(tester):
    tester.startGroup('Uche finds nested default namespace munging')
    doc = implementation.createDocument(None, None, None)
    elem1 = doc.createElementNS("http://example.com/1", "x:foo")
    doc.appendChild(elem1)
    elem2 = doc.createElementNS(None, "bar")
    elem1.appendChild(elem2)
    tester.startTest('Outer with prefix.  Print')
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED1_PRINTED, result)
    tester.testDone()
    tester.startTest('Outer with prefix.  PrettyPrint')
    stream = cStringIO.StringIO()
    PrettyPrint(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED1_PRETTY, result)
    tester.testDone()

    doc = implementation.createDocument(None, None, None)
    elem1 = doc.createElementNS("http://example.com/1", "foo")
    doc.appendChild(elem1)
    elem2 = doc.createElementNS(None, "bar")
    elem1.appendChild(elem2)
    tester.startTest('Outer without prefix.  Print')
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED2_PRINTED, result)
    tester.testDone()
    tester.startTest('Outer without prefix.  PrettyPrint')
    stream = cStringIO.StringIO()
    PrettyPrint(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED2_PRETTY, result)
    tester.testDone()

    doc = implementation.createDocument(None, None, None)
    elem1 = doc.createElementNS(None, "foo")
    doc.appendChild(elem1)
    elem2 = doc.createElementNS("http://example.com/1", "bar")
    elem1.appendChild(elem2)
    tester.startTest('outer no prefix or ns, inner ns no prefix.  Print')
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED3_PRINTED, result)
    tester.testDone()
    tester.startTest('outer no prefix or ns, inner ns no prefix.  PrettyPrint')
    stream = cStringIO.StringIO()
    PrettyPrint(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED3_PRETTY, result)
    tester.testDone()

    doc = implementation.createDocument(None, None, None)
    elem1 = doc.createElementNS(None, "foo")
    doc.appendChild(elem1)
    elem2 = doc.createElementNS("http://example.com/1", "bar")
    elem1.appendChild(elem2)
    elem3 = doc.createElementNS(None, "baz")
    elem2.appendChild(elem3)
    tester.startTest(
        'outer no prefix or ns, then ns no prefix then no prefix no ns.  Print'
    )
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED4_PRINTED, result)
    tester.testDone()
    tester.startTest(
        'outer no prefix or ns, then ns no prefix then no prefix no ns.  PrettyPrint'
    )
    stream = cStringIO.StringIO()
    PrettyPrint(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED4_PRETTY, result)
    tester.testDone()
    tester.groupDone()
    return
示例#10
0
		<parameters>eth0</parameters>
	</observationPoint>
</ipfixConfig>	
"""
#print "Die neue Konfiguration:"
#print testconfig
#confignode = NonvalidatingReader.parseString(testconfig, 'urn:ietf:params:xml:ns:ipfix-config')

defaultoperation = "replace"
testoption = None
erroroption = "stop-on-error"
target = "startup"

#m = moduleInstanz.validate("startup")
#PrettyPrint(m.getXMLNodeReply())
#m = moduleInstanz.editConfig(defaultoperation, testoption, erroroption, target, confignode, targetnode=None)

#PrettyPrint(m.getXMLNodeReply())
#print "Nochmal ausgeben:"
#m = moduleInstanz.getConfig('startup')

#PrettyPrint(m.getXMLNodeReply())

#m = moduleInstanz.deleteConfig('candidate')
#PrettyPrint(m.getXMLNodeReply())
#m = moduleInstanz.restart()
#PrettyPrint(m.getXMLNodeReply())

m = moduleInstanz.restart()
PrettyPrint(m.getXMLNodeReply())
示例#11
0
    xbel1_top_level = \
        [ n for n in xbel1.documentElement.childNodes \
            if n.nodeType == Node.ELEMENT_NODE ]
    xbel1_top_level_folders = \
        [ n for n in xbel1_top_level if n.nodeName == 'folder' ]
    xbel1_top_level_bookmarks = \
        [ n for n in xbel1_top_level if n.nodeName == 'bookmark' ]
    xbel2_top_level = \
        [ n for n in xbel2.documentElement.childNodes \
            if n.nodeType == Node.ELEMENT_NODE ]
    for elem in xbel2_top_level:
        if elem.nodeName == 'folder':
            title = get_title(elem)
            for a_folder in xbel1_top_level_folders:
                if title == get_title(a_folder):
                    merge_folders(a_folder, elem)
                    break
            else:
                xbel1.documentElement.appendChild(elem)
        elif elem.nodeName == 'bookmark':
            xbel1.documentElement.appendChild(elem)
    return xbel1


if __name__ == "__main__":
    import sys
    xbel1 = NonvalidatingReader.parseUri(sys.argv[1])
    xbel2 = NonvalidatingReader.parseUri(sys.argv[2])
    new_xbel = xbel_merge(xbel1, xbel2)
    PrettyPrint(new_xbel)
        return blob


if __name__ == "__main__":

    import Ft.Xml.Domlette
    from Ft.Xml.Domlette import Print, PrettyPrint

    fd = open("sample.bin", "rb+")
    data = fd.read()
    fd.close()

    b = Binary()
    dom = b.analyzeBlob(data)
    data2 = dom.getValue()

    if data2 == data:
        print "THEY MATCH"
    else:
        print repr(data2)
        print repr(data)

    dict = {}
    doc = Ft.Xml.Domlette.NonvalidatingReader.parseString(
        "<Peach/>", "http://phed.org")
    xml = dom.toXmlDom(doc.rootNode.firstChild, dict)
    PrettyPrint(doc, asHtml=1)

# end
示例#13
0
    try:
        doc = reader.parse(source_isrc)
        CloseStream(source_isrc, quiet=True)

        if rng_isrc is not None:
            validator = RelaxNgValidator(rng_isrc)
            CloseStream(rng_isrc, quiet=True)
            result = validator.validateNode(doc)
            if not result.nullable():
                raise RngInvalid(result)

        if not noserialize:
            from Ft.Xml.Domlette import Print, PrettyPrint
            if pretty:
                PrettyPrint(doc, out_file, encoding, as_html)
            else:
                Print(doc, out_file, encoding, as_html)

    except Exception, e:
        import traceback
        traceback.print_exc(1000, sys.stderr)
        raise

    try:
        if out_file.isatty():
            out_file.flush()
            sys.stderr.write('\n')
        else:
            out_file.close()
    except (IOError, ValueError):
def test_writer(tester, domMod):
    tester.startGroup('Domlette serialization')

    tester.startTest('minimal document with DOCTYPE')
    doc = domMod.implementation.createDocument(EMPTY_NAMESPACE, u'foo', None)
    doc.publicId = u'myPub'
    doc.systemId = u'mySys'
    buf = cStringIO.StringIO()
    Print(doc, buf)
    result = buf.getvalue()
    tester.compare(doctype_expected_1, result)
    tester.testDone()

    tester.startGroup('namespace-free XHTML')
    tester.startTest('create document')
    doc = domMod.implementation.createDocument(EMPTY_NAMESPACE, None, None)
    html = doc.createElementNS(EMPTY_NAMESPACE, u'html')
    head = doc.createElementNS(EMPTY_NAMESPACE, u'head')
    title = doc.createElementNS(EMPTY_NAMESPACE, u'title')
    titletext = doc.createTextNode(u'test')
    body = doc.createElementNS(EMPTY_NAMESPACE, u'body')
    h1 = doc.createElementNS(EMPTY_NAMESPACE, u'h1')
    h1text = doc.createTextNode(u'xhtml test')
    hr = doc.createElementNS(EMPTY_NAMESPACE, u'hr')
    hr.setAttributeNS(EMPTY_NAMESPACE, u'noshade', u'noshade')
    pre = doc.createElementNS(EMPTY_NAMESPACE, u'pre')
    pretext = doc.createTextNode(JABBERWOCKY)
    pre.appendChild(pretext)
    h1.appendChild(h1text)
    body.appendChild(h1)
    body.appendChild(hr)
    body.appendChild(pre)
    title.appendChild(titletext)
    head.appendChild(title)
    html.appendChild(head)
    html.appendChild(body)
    doc.appendChild(html)
    tester.testDone()

    tester.startTest('as XML with Print')
    buf = cStringIO.StringIO()
    Print(doc, buf)
    result = buf.getvalue()
    tester.compare(xhtml_expected_1, result)
    tester.testDone()

    tester.startTest('as HTML with Print')
    buf = cStringIO.StringIO()
    Print(doc, buf, asHtml=1)
    result = buf.getvalue()
    tester.compare(xhtml_expected_2, result)
    tester.testDone()

    tester.startTest('as XML with PrettyPrint')
    buf = cStringIO.StringIO()
    PrettyPrint(doc, buf)
    result = buf.getvalue()
    tester.compare(xhtml_expected_3, result)
    tester.testDone()

    tester.startTest('as HTML with PrettyPrint')
    buf = cStringIO.StringIO()
    PrettyPrint(doc, buf, asHtml=1)
    result = buf.getvalue()
    tester.compare(xhtml_expected_4, result)
    tester.testDone()

    tester.groupDone()

    tester.groupDone()
    return
示例#15
0
def printNodeToFile(node, filePath):
    """ print a Domlette tree to a file """

    f = open(filePath, 'w')
    PrettyPrint(node, f)
    f.close()
# -------------------

os.popen4("mv " + dirName + " ../Modules")

print "The module (" + name + ") was successfully created in \"server/Modules\" directory."

# Update modules.xml
# -------------------

path = "file:../conf/modules.xml"

doc = NonvalidatingReader.parseUri(path)

moduleNode = doc.createElementNS(None, 'module')
doc.documentElement.appendChild(moduleNode)

moduleNode.appendChild(createNode(doc, 'name', name))
moduleNode.appendChild(createNode(doc, 'mainFileName', mainFileName))
moduleNode.appendChild(createNode(doc, 'className', className))
moduleNode.appendChild(createNode(doc, 'xpath', xpathExpression))
moduleNode.appendChild(createNode(doc, 'xsdfile', moduleName + ".xsd"))

# Print modules document to modules.conf
# -------------------

f = open("../conf/modules.xml", 'w')
PrettyPrint(doc, f)
f.close()

print "\"modules.xml\" file update succeeded."
示例#17
0
    def editConfig(self,
                   defaultoperation,
                   testoption,
                   erroroption,
                   target,
                   confignode,
                   targetnode=None):
        """
        Apply a edit-config request from the confignode to the targetnode.
        @type defaultoperation: MERGE_OPERATION | REPLACE_OPERATION | NONE_OPERATION 
        @param defaultoperation : as specified in NETCONF protocol
        @type testoption : SET | TEST_AND_SET 
        @param testoption : as specified in NETCONF protocol
        @type erroroption : STOP_ON_ERROR | IGNORE_ERROR | ROLL_BACK_ON_ERROR 
        @param erroroption : as specified in NETCONF protocol
        @type target : RUNNING_TARGET | CANDIDATE_TARGET | STARTUP_TARGET
        @param target : as specified in NETCONF protocol
        @type targetnode : string
        @param targetnode : if the target is RUNNING_TARGET or STARTUP_TARGET it will be ignored otherwise should be the node of the CANDIDATE_TARGET that this module should procees
        @rtype: ModuleReply
        @return: It returns a success or error message.
        ** Relates to the netconf edit-config operation
        """

        try:
            # Generate a stylesheet equivalent to the edit-config
            df = InputSource.DefaultFactory
            editXMLRequest = df.fromString(
                util.convertNodeToString(confignode), 'urn:dummy')
            stylesheet = df.fromUri("file:" + metaFile, 'urn:sty')
            p = Processor.Processor()
            p.appendStylesheet(stylesheet)
            wr = DomWriter.DomWriter()
            p.run(editXMLRequest, writer=wr)
            generatedStyleSheet = wr.getResult()

            # Apply the generated stylesheet to the source document
            inputStyleSheet = df.fromString(
                util.convertNodeToString(generatedStyleSheet), 'urn:sty')
            oldXMLDocument = self.getConfig(target).getXMLNodeReply()
            inputDocument = df.fromString(
                util.convertNodeToString(oldXMLDocument), 'urn:dummy')
            p = Processor.Processor()
            p.appendStylesheet(inputStyleSheet)
            wr = DomWriter.DomWriter()
            p.run(inputDocument, writer=wr)
            newXMLDoc = wr.getResult()
            newOLSRRootNode = newXMLDoc.childNodes[0]

            # Copy the data to the olsr config file
            file_generator = Generator(self.namespace)
            file_generator.transform(newOLSRRootNode)

            print "new OLSR config is \n"
            PrettyPrint(newXMLDoc.childNodes[0])

            if (newOLSRRootNode != None):
                xmlreply = ModuleReply(replynode=newOLSRRootNode)

            else:
                xmlreply = ModuleReply(
                    error_type=ModuleReply.APPLICATION,
                    error_tag=ModuleReply.OPERATION_NOT_SUPPORTED,
                    error_severity=ModuleReply.ERROR,
                    error_message=
                    "Config generator from Module %s replied with None." %
                    self.name)

            return xmlreply

            # (Re)start the olsr process on the device, if it is running
#            p = OLSR_System()
#            p.start_new_olsr_instance()

#            xmlReply = self.copyConfig("config", target, sourceNode = newXMLDoc)
#            return xmlReply

        except Exception, exp:
            print str(exp)
            moduleReply = ModuleReply(error_type=ModuleReply.APPLICATION,
                                      error_tag=ModuleReply.OPERATION_FAILED,
                                      error_severity=ModuleReply.ERROR,
                                      error_message=str(exp))
            return moduleReply
示例#18
0
	def _runAction(self, action, mutator):
		
		Debug(1, "\nStateEngine._runAction: %s" % action.name)
				
		mutator.onActionStarting(action.parent, action)
		
		# If publisher property has been given, use referenced Publisher; otherwise the first one
		if action.publisher != None:
			pub = self._getPublisherByName(action.publisher)
			
			if pub == None:
				raise PeachException("Publisher '%s' not found!" % action.publisher)
		else:
			pub = self.publishers[0]
		
		# EVENT: when
		if action.when != None:
			environment = {
				'Peach' : self.engine.peach,
				'Action' : action,
				'State' : action.parent,
				'StateModel' : action.parent.parent,
				'Mutator' : mutator,
				'peachPrint' : self.f,
				'sleep' : time.sleep,
				'getXml' : self.getXml,
				'random' : random
				}
			
			if not evalEvent(action.when, environment, self.engine.peach):
				Debug(1, "Action when failed: " + action.when)
				return
			else:
				Debug(1, "Action when passed: " + action.when)
		
		Engine.context.watcher.OnActionStart(action)
		
		# EVENT: onStart
		if action.onStart != None:
			environment = {
				'Peach' : self.engine.peach,
				'Action' : action,
				'State' : action.parent,
				'StateModel' : action.parent.parent,
				'Mutator' : mutator,
				'peachPrint' : self.f,
				'sleep' : time.sleep
				}
			
			evalEvent(action.onStart, environment, self.engine.peach)
		
		if action.type == 'input':
			action.value = None
			
			if pub.hasBeenStarted == False:
				pub.start()
				pub.hasBeenStarted = True
			if not pub.hasBeenConnected:
				pub.connect()
				pub.hasBeenConnected = True
			
			# Make a fresh copy of the template
			action.__delitem__(action.template.name)
			action.template = action.origionalTemplate.copy(action)
			action.append(action.template)
			
			# Create buffer
			buff = PublisherBuffer(pub)
			self.dirtyXmlCache()
			
			# Crack data
			cracker = DataCracker(self.engine.peach)
			(rating, pos) = cracker.crackData(action.template, buff, "setDefaultValue")
			
			if rating > 2:
				raise SoftException("Was unble to crack incoming data into %s data model." % action.template.name)
			
			action.value = action.template.getValue()
			
		elif action.type == 'output':
			
			if not pub.hasBeenStarted:
				pub.start()
				pub.hasBeenStarted = True
			if not pub.hasBeenConnected:
				pub.connect()
				pub.hasBeenConnected = True
			
			# Run mutator
			mutator.onDataModelGetValue(action, action.template)
			
			# Get value
			if action.template.modelHasOffsetRelation:
				stringBuffer = StreamBuffer()
				action.template.getValue(stringBuffer)
				
				stringBuffer.setValue("")
				stringBuffer.seekFromStart(0)
				action.template.getValue(stringBuffer)
				
				action.value = stringBuffer.getValue()
				
			else:
				action.value = action.template.getValue()
			
			Debug(1, "Actiong output sending %d bytes" % len(action.value))
			
			if not pub.withNode:
				pub.send(action.value)
			else:
				pub.sendWithNode(action.value, action.template)
			
			# Save the data filename used for later matching
			if action.data != None and action.data.fileName != None:
				self.actionValues.append( [ action.name, 'output', action.value, action.data.fileName ] )
			
			else:
				self.actionValues.append( [ action.name, 'output', action.value ] )
			
			obj = Element(action.name, None)
			obj.elementType = 'dom'
			obj.defaultValue = action.value
			action.value = obj
		
		elif action.type == 'call':
			action.value = None
			
			actionParams = []
			
			if not pub.hasBeenStarted:
				pub.start()
				pub.hasBeenStarted = True
			
			# build up our call
			method = action.method
			if method == None:
				raise PeachException("StateEngine: Action of type \"call\" does not have method name!")
			
			params = []
			for c in action:
				if c.elementType == 'actionparam':
					params.append(c)
			
			argNodes = []
			argValues = []
			for p in params:
				if p.type == 'out' or p.type == 'inout':
					raise PeachException("StateEngine: Action of type \"call\" does not yet support out or inout parameters (bug in comtypes)!")
				
				# Run mutator
				mutator.onDataModelGetValue(action, p.template)
				
				# Get value
				if p.template.modelHasOffsetRelation:
					stringBuffer = StreamBuffer()
					p.template.getValue(stringBuffer)
					stringBuffer.setValue("")
					stringBuffer.seekFromStart(0)
					p.template.getValue(stringBuffer)
					
					p.value = stringBuffer.getValue()
					
				else:
					p.value = p.template.getValue()

				argValues.append(p.value)
				argNodes.append(p.template)
				
				actionParams.append([p.name, 'param', p.value])
			
			if not pub.withNode:
				ret = pub.call(method, argValues)
			else:
				ret = pub.callWithNode(method, argValues, argNodes)
			
			# look for and set return
			for c in action:
				if c.elementType == 'actionresult':
					self.dirtyXmlCache()
					
					print "RET:",ret,type(ret)
					
					data = None
					if type(ret) == int:
						data = struct.pack("i", ret)
					elif type(ret) == long:
						data = struct.pack("q", ret)
					elif type(ret) == str:
						data = ret
					
					if c.template.isPointer:
						print "Found ctypes pointer...trying to cast..."
						retCtype = c.template.asCTypeType()
						retCast = ctypes.cast(ret, retCtype)
						
						for i in range(len(retCast.contents._fields_)):
							(key, value) = retCast.contents._fields_[i]
							value = eval("retCast.contents.%s" % key)
							c.template[key].defaultValue = value
							print "Set [%s=%s]" % (key, value)
					
					else:
						cracker = DataCracker(self.engine.peach)
						cracker.haveAllData = True
						(rating, pos) = cracker.crackData(c.template, PublisherBuffer(None, data, True))
						if rating > 2:
							raise SoftException("Was unble to crack result data into %s data model." % c.template.name)
			
			self.actionValues.append( [ action.name, 'call', method, actionParams ] )
		
		elif action.type == 'getprop':
			action.value = None
			
			if not pub.hasBeenStarted:
				pub.start()
				pub.hasBeenStarted = True
			
			# build up our call
			property = action.property
			if property == None:
				raise Exception("StateEngine._runAction(): getprop type does not have property name!")
			
			data = pub.property(property)
			
			self.actionValues.append( [ action.name, 'getprop', property, data ] )
			
			self.dirtyXmlCache()
			
			cracker = DataCracker(self.engine.peach)
			(rating, pos) = cracker.crackData(action.template, PublisherBuffer(None,data))
			if rating > 2:
				raise SoftException("Was unble to crack getprop data into %s data model." % action.template.name)
			
			# If no exception, it worked
			
			action.value = action.template.getValue()
			
			if Peach.Engine.engine.Engine.debug:
				print "*******POST GETPROP***********"
				doc = self.getXml()
				PrettyPrint(doc, asHtml=1)
				print "******************"
			
		elif action.type == 'setprop':
			action.value = None
			
			if not pub.hasBeenStarted:
				pub.start()
				pub.hasBeenStarted = True
				
			# build up our call
			property = action.property
			if property == None:
				raise Exception("StateEngine: setprop type does not have property name!")
			
			value = None
			valueNode = None
			for c in action:
				if c.elementType == 'actionparam' and c.type == "in":
					# Run mutator
					mutator.onDataModelGetValue(action, c.template)
					
					# Get value
					if c.template.modelHasOffsetRelation:
						stringBuffer = StreamBuffer()
						c.template.getValue(stringBuffer)
						stringBuffer.setValue("")
						stringBuffer.seekFromStart(0)
						c.template.getValue(stringBuffer)
						
						value = c.value = stringBuffer.getValue()
						
					else:
						value = c.value = c.template.getValue()
					
					valueNode = c.template
					break
			
			if not pub.withNode:
				pub.property(property, value)
			else:
				pub.propertyWithNode(property, value, valueNode)
			
			self.actionValues.append( [ action.name, 'setprop', property, value ] )
		
		elif action.type == 'changeState':
			action.value = None
			self.actionValues.append( [ action.name, 'changeState', action.ref ] )
			mutator.onActionFinished(action.parent, action)
			raise StateChangeStateException(self._getStateByName(action.ref))
			
		elif action.type == 'slurp':
			action.value = None
			
			startTime = time.time()
			
			doc = self.getXml()
			setNodes = doc.xpath(action.setXpath)
			if len(setNodes) == 0:
				PrettyPrint(doc, asHtml=1)
				raise PeachException("Slurp [%s] setXpath [%s] did not return a node" % (action.name,action.setXpath))
			
			# Only do this once :)
			valueElement = None
			if action.valueXpath != None:
				valueNodes = doc.xpath(action.valueXpath)
				if len(valueNodes) == 0:
					print "Warning: valueXpath did not return a node"
					raise SoftException("StateEngine._runAction(xpath): valueXpath did not return a node")
				
				valueNode = valueNodes[0]
				try:
					valueElement = action.getRoot().getByName(str(valueNode.getAttributeNS(None, "fullName")))
					
				except:
					print "valueNode:", valueNode
					print "valueNode.nodeName:", valueNode.nodeName
					print "valueXpath:", action.valueXpath
					print "results:", len(valueNodes)
					raise PeachException("Slurp AttributeError: [%s]" % str(valueNode.getAttributeNS(None, "fullName")))
				
			for node in setNodes:
				
				setElement = action.getRoot().getByName(str(node.getAttributeNS(None, "fullName")))
				
				if valueElement != None:
					
					Debug(1, "Action-Slurp: 1 Setting %s from %s" % (
						str(node.getAttributeNS(None, "fullName")),
						str(valueNode.getAttributeNS(None, "fullName"))
						))
					
					valueElement = action.getRoot().getByName(str(valueNode.getAttributeNS(None, "fullName")))
					
					# Some elements like Block do not have a current or default value
					if valueElement.currentValue == None and valueElement.defaultValue == None:
						setElement.currentValue = None
						setElement.defaultValue = valueElement.getValue()
					
					else:
						setElement.currentValue = valueElement.getValue()
						setElement.defaultValue = valueElement.defaultValue
					
					setElement.value = None
					
					#print " --- valueElement --- "
					#pub.send(valueElement.getValue())
					#print " --- setElement --- "
					#pub.send(setElement.getValue())
					#print " --------------------"
					
				else:
					
					Debug(1, "Action-Slurp: 2 Setting %s to %s" % (
						str(node.getAttributeNS(None, "fullName")),
						repr(action.valueLiteral)
						))
					
					setElement.defaultValue = action.valueLiteral
					setElement.currentValue = None
					setElement.value = None
			
			#print " - Total time to slurp data: %.2f" % (time.time() - startTime)
		
		elif action.type == 'connect':
			if not pub.hasBeenStarted:
				pub.start()
				pub.hasBeenStarted = True
				
			pub.connect()
			pub.hasBeenConnected = True
		
		elif action.type == 'accept':
			if not pub.hasBeenStarted:
				pub.start()
				pub.hasBeenStarted = True
			
			pub.accept()
			pub.hasBeenConnected = True
		
		elif action.type == 'close':
			if not pub.hasBeenConnected:
				# If we haven't been opened lets ignore
				# this close.
				return
				
			pub.close()
			pub.hasBeenConnected = False
		
		elif action.type == 'start':
			pub.start()
			pub.hasBeenStarted = True
		
		elif action.type == 'stop':
			if pub.hasBeenStarted:
				pub.stop()
				pub.hasBeenStarted = False
		
		elif action.type == 'wait':
			time.sleep(float(action.valueLiteral))
		
		else:
			raise Exception("StateEngine._runAction(): Unknown action.type of [%s]" % str(action.type))
		
		# EVENT: onComplete
		if action.onComplete != None:
			environment = {
				'Peach' : self.engine.peach,
				'Action' : action,
				'State' : action.parent,
				'Mutator' : mutator,
				'StateModel' : action.parent.parent,
				'sleep' : time.sleep
				}
			
			evalEvent(action.onComplete, environment, self.engine.peach)
		
		mutator.onActionFinished(action.parent, action)
		Engine.context.watcher.OnActionComplete(action)
                                                sourceNode=sourceNode)

                # Update the cache according to the new config.
                module.resetConfigTime(self.target)

                if moduleReply.isError():
                    self.operationReply.setError()

                self.operationReply.setNode(moduleReply.getXMLNodeReply())

            return self.operationReply

        elif self.target == C.URL:
            # WARNING : THIS HAS NEVER BEEN TESTED
            buf = cStringIO.StringIO()
            PrettyPrint(sourceDoc, stream=buf, encoding='UTF-8')
            # connect to host, default port
            ftp = FTP(self.urlTarget)
            # user anonymous, passwd anonymous@
            ftp.login()
            ftp.storbinary('STOR ' + self.urlTarget, buf.read)
            buf.close()
            ftp.quit()

    def setParameters(self, operation, NSS=None):
        """
		Set the source and target parameters

		@type  operation: Node
		@param operation: The operation node of the current Netconf request.
		"""
示例#20
0
###################################################################
# Here will be the content of edit-config() method of RIP_Module: #
###################################################################

# First, instantiate a RIP manager
ripManager = RIP_Manager("urn:loria:madynes:ensuite:yencap:module:RIP:1.0")

# The table of commands that will have to be executed:
commands = []

# Build an XML document which is a sub part of an edit-config:
doc = NonvalidatingReader.parseString(m6, "madynes")

# Print the edit-config, just for fun:
PrettyPrint(doc)

# Look for XML nodes having "operation" attribute:
d = findEditOp()

# Parse the running configure commands, building the RIP command objects:
ec = ripManager.readCommands()

for item in d:
    NS_RIP_Module = "urn:loria:madynes:ensuite:yencap:module:RIP:1.0"
    name = item.tagName
    operation = d[item]

    if name == "redistribute":

        if operation == "create":
示例#21
0
	def dump(self):
		
		PrettyPrint(self.serialize())