def parseDom(xmlText): baos = ByteArrayInputStream(xmlText.getBytes("UTF-8")) dfactory = DocumentBuilderFactory.newInstance() dfactory.setNamespaceAware(true) dfactory.setValidating(false) documentBuilder = dfactory.newDocumentBuilder() return documentBuilder.parse(baos)
def getXMLDoc(self, xmlPath): try: document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath) return document except: self._extender.popup("XML file not found") return
def getAppInfo(self): dbf = DocumentBuilderFactory.newInstance() db = dbf.newDocumentBuilder() dom = db.parse(self.currentEnv.topologyfile) apps = dom.getElementsByTagName('application') for i in range(apps.length): currentAppElement = apps.item(i) if self.earfile.startswith( currentAppElement.getAttribute('earfileptrn')): self.targettype = currentAppElement.parentNode.getTagName() self.targetname = currentAppElement.parentNode.getAttribute( 'name') self.appName = currentAppElement.getAttribute('name') if self.targettype == 'server': self.nodename = currentAppElement.parentNode.getAttribute( 'nodename') self.virtualhost = currentAppElement.getAttribute('vhost') sharedlibs = currentAppElement.getElementsByTagName( 'sharedlib') for j in range(sharedlibs.length): self.sharedLibs.append( sharedlibs.item(j).getAttribute('name')) webservers = currentAppElement.getElementsByTagName( 'webserver') for w in range(webservers.length): self.webservers.append( (webservers.item(w).getAttribute('name'), webservers.item(w).getAttribute('nodename')))
def authorizeFortress(self, user_name): responseData = self.getFortressResponse(user_name) print responseData dbf = DocumentBuilderFactory.newInstance() fortressAuthenticated = False db = None try: db = dbf.newDocumentBuilder() print responseData isource = InputSource() isource.setCharacterStream(StringReader(responseData)) try: doc = db.parse(isource) errorCode = doc.getElementsByTagName("errorCode") valueSet = doc.getElementsByTagName("valueSet") if (errorCode.item(0).getTextContent() == "0" and self.roleExists("GLUU_ADMIN", valueSet)): return True else: fortressAuthenticated = False except Exception, ex: print "Exception" except ParserConfigurationException, pce: print pce
def __init__(self, file_name): path = Paths.get(file_name) self.file_name = path.toAbsolutePath().toString() self.file = File(self.file_name) self.db_factory = DocumentBuilderFactory.newInstance() self.db_builder = self.db_factory.newDocumentBuilder() self.doc = self.db_builder.parse(self.file) self.doc.getDocumentElement().normalize()
def createBlankDocument(self): try: import sys, traceback from javax.xml.parsers import DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance() return builderFactory.newDocumentBuilder() except: print "exception: %s" % traceback.format_exception(*sys.exc_info())
def createBlankDocument(self): try: import sys, traceback from javax.xml.parsers import DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance() return builderFactory.newDocumentBuilder() except: print "exception: %s" % traceback.format_exception(*sys.exc_info())
def extractRootElement(self): """Setup an XML parser """ dbf = DocumentBuilderFactory.newInstance() dbf.setNamespaceAware(1) domparser = dbf.newDocumentBuilder() doc = domparser.parse(InputSource(StringReader(self.app.errorsData))) rootElement = doc.getDocumentElement() return rootElement
def dom(filename): try: doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( File(filename)) root = doc.getDocumentElement() root.normalize() traverse(root) except: print '\nError: %s\nvalue: %s' % sys.exc_info()[:2]
def getDoc(self, url): doc = None try: newurl = URL(url) dbf = DocumentBuilderFactory.newInstance() db = dbf.newDocumentBuilder() doc = db.parse(newurl.openStream()) except Exception, e: print 'Failed to reach a server.' print 'Details', str(e)
def __init__(self, inputFile): dbf = DocumentBuilderFactory.newInstance() db = dbf.newDocumentBuilder() myFile = File(inputFile) self.doc = db.parse (myFile) self.doc.getDocumentElement ().normalize () self.reporter = Reporter() self.reporter.report("xml properties file " + inputFile) self.reporter.report("root element " + self.doc.getDocumentElement().getNodeName())
def _buildDocumentForXpath(self, content, namespaceAware = 1): if not content: raise ValueError('Empty content') xmlFact = DocumentBuilderFactory.newInstance() xmlFact.setNamespaceAware(namespaceAware) xmlFact.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", self.__laodExternalDtd) builder = xmlFact.newDocumentBuilder() try: return builder.parse(ByteArrayInputStream(String(content).getBytes())) except JException, e: raise InvalidXmlException(e.getMessage())
def _buildDocumentForXpath(content, namespaceAware=1): r'@types: str, int -> org.w3c.dom.Document' xmlFact = DocumentBuilderFactory.newInstance() xmlFact.setNamespaceAware(namespaceAware) xmlFact.setValidating(0) xmlFact.setFeature("http://xml.org/sax/features/namespaces", 0) xmlFact.setFeature("http://xml.org/sax/features/validation", 0) xmlFact.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", 0) xmlFact.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", 0) builder = xmlFact.newDocumentBuilder() return builder.parse(ByteArrayInputStream(String(content).getBytes()))
def get_file_element_tree(filename): if filename not in deploy_files_element_trees: data = get_file_data(filename) input_stream = ByteArrayInputStream(data) db_factory = DocumentBuilderFactory.newInstance() db = db_factory.newDocumentBuilder() element_tree = db.parse(input_stream) element_tree.getDocumentElement().normalize() deploy_files_element_trees[filename] = element_tree return deploy_files_element_trees[filename]
def validate_moml(moml_str): try: factory = DocumentBuilderFactory.newInstance() factory.setValidating(True) builder = factory.newDocumentBuilder() builder.setErrorHandler(_ErrorHandler()) builder.setEntityResolver(_EntityResolver()) xmlDocument = builder.parse( InputSource(StringReader(moml_str)) ) # ByteArrayInputStream(String(moml_str).getBytes())) return True except: traceback.print_exc() return False
def tiltCallback(self, topic, message): tiltEvent = {'name': 'Motion/Tilt/MotionStatus'} try: builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() topnode = builder.parse(InputSource(StringReader(( message.toString())))).getFirstChild() assert topnode.getNodeName() == 'Payload' nodes1lev = topnode.getChildNodes() for i in xrange(nodes1lev.getLength()): node1 = nodes1lev.item(i) assert node1.getNodeName() == 'Parameter' atts = node1.getAttributes() tiltEvent[atts.item(0).getNodeValue()] = node1.getTextContent() except Exception, e: print "Error in SenSafety/mqtt xml format, " + str(e)
def checkResponseBody(inStream): docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder() source = InputSource() source.setByteStream(inStream) doc = docBuilder.parse(source) tag = "SAIL_Error" nodeList = doc.getElementsByTagName(tag) count = nodeList.getLength() if (count < 1): fatal("response did not contain a '" + tag + "' tag: " + responseBody) if (count > 1): fatal("response contained multiple '" + tag + "' tags: " + responseBody) node = nodeList.item(0) id = node.getAttribute("ID") if (id != "AC_OK"): msg = node.getAttribute("Msg") fatal("from IHS Admin Server: " + msg)
def findXpathNodes(self, xmlAsText, xpathExpr): xmlText = InputSource(ByteArrayInputStream(lang.String(xmlAsText).getBytes())) docBuilderFactory = DocumentBuilderFactory.newInstance() docBuilderFactory.setValidating(0) docBuilderFactory.setNamespaceAware(0) docBuilder = docBuilderFactory.newDocumentBuilder() doc = docBuilder.parse(xmlText) xpathFactory = XPathFactory.newInstance() xPath = xpathFactory.newXPath() expr = xPath.compile(xpathExpr); nodeList = expr.evaluate(doc, XPathConstants.NODESET) nodeCount = nodeList.getLength() count = 0 xpathNodes = [] while count < nodeCount: xpathNodes.append(nodeList.item(count)) count = count + 1 return xpathNodes
def findXpathNodes(self, xmlAsText, xpathExpr): xmlText = InputSource( ByteArrayInputStream(lang.String(xmlAsText).getBytes())) docBuilderFactory = DocumentBuilderFactory.newInstance() docBuilderFactory.setValidating(0) docBuilderFactory.setNamespaceAware(0) docBuilder = docBuilderFactory.newDocumentBuilder() doc = docBuilder.parse(xmlText) xpathFactory = XPathFactory.newInstance() xPath = xpathFactory.newXPath() expr = xPath.compile(xpathExpr) nodeList = expr.evaluate(doc, XPathConstants.NODESET) nodeCount = nodeList.getLength() count = 0 xpathNodes = [] while count < nodeCount: xpathNodes.append(nodeList.item(count)) count = count + 1 return xpathNodes
def _parseOpenPortsFromXml(output): 'str->?' result = [] xpath = XPathFactory.newInstance().newXPath() xmlFactory = DocumentBuilderFactory.newInstance() xmlFactory.setNamespaceAware(True) builder = xmlFactory.newDocumentBuilder() document = builder.parse(ByteArrayInputStream(String(output).getBytes())) ports = xpath.evaluate(r'/nmaprun/host/ports/port/state[@state="open"]/..|/nmaprun/host/ports/port/state[@state="open|filtered"]/..', document, XPathConstants.NODESET) if ports: protocolTypesMap = {'tcp': PortType.TCP.getProtocol(), 'udp': PortType.UDP.getProtocol()} for portIndex in xrange(ports.getLength()): portNode = ports.item(portIndex) protocolStr = portNode.getAttribute('protocol') protocol = protocolTypesMap.get(protocolStr) port = portNode.getAttribute('portid') if port and protocol: result.append((protocol, int(port))) else: logger.debug("Port [%s] or protocol [%s] values are invalid. Skip..." % (port, protocolStr)) return result
def DoXPath (Filename,XPathString): IS = InputSource (FileInputStream (Filename)) df = DocumentBuilderFactory.newInstance() df.setNamespaceAware(1) doc = df.newDocumentBuilder().parse(IS) serializer = TransformerFactory.newInstance().newTransformer() serializer.setOutputProperty (OutputKeys.OMIT_XML_DECLARATION, "yes") nl = XPathAPI.selectNodeIterator (doc,XPathString) n = nl.nextNode() while n: if IsTextNode (n): # Coalesce contiguous text nodes res = [n.getNodeValue()] nn = n.getNextSibling() while (nn): res.append (nn.getNodeValue()) nn = n.getNextSibling() java.lang.System.out (string.join(res,"")) else: serializer.transform (DOMSource(n), StreamResult (OutputStreamWriter (java.lang.System.out))) java.lang.System.out.println() n = nl.nextNode()
# -*- coding: utf-8 -*- import unittest from java.lang import System from java.io import File from java.io import ByteArrayOutputStream from javax.xml.parsers import DocumentBuilderFactory from javax.xml.transform import TransformerFactory from javax.xml.transform.dom import DOMSource from javax.xml.transform.stream import StreamSource from javax.xml.transform.stream import StreamResult dbfac = DocumentBuilderFactory.newInstance() dbfac.namespaceAware = True docfac = dbfac.newDocumentBuilder() print type(dbfac) transfac = TransformerFactory.newInstance() src_dom = docfac.parse('hello.xml') src_source = DOMSource(src_dom) def unsigned_byte(x): if x < 0: return 256 + x return x def Transformer(xsl_source):
def parseXML(self, file): # Initialize XML stuff dbFactory = DocumentBuilderFactory.newInstance() dBuilder = dbFactory.newDocumentBuilder() doc = dBuilder.parse(file) doc.getDocumentElement().normalize() # All entries in Burp's XML Export File have tag <item>...</item> nodeList = doc.getElementsByTagName("item") # for i in reversed(range(0, nodeList.getLength())): for i in range(0, nodeList.getLength()): node = nodeList.item(i) if node.getNodeType() == Node.ELEMENT_NODE: request = node.getElementsByTagName("request").item( 0).getTextContent() response = node.getElementsByTagName("response").item( 0).getTextContent() request_isBase64 = node.getElementsByTagName("request").item( 0).getAttribute("base64") response_isBase64 = node.getElementsByTagName("response").item( 0).getAttribute("base64") if request_isBase64 == "true": request = Base64.getDecoder().decode(request) if response_isBase64 == "true": response = Base64.getDecoder().decode(response) info = { "time": node.getElementsByTagName("time").item(0).getTextContent(), "url": node.getElementsByTagName("url").item(0).getTextContent(), "host": node.getElementsByTagName("host").item(0).getTextContent(), "port": node.getElementsByTagName("port").item(0).getTextContent(), "protocol": node.getElementsByTagName("protocol").item( 0).getTextContent(), "method": node.getElementsByTagName("method").item( 0).getTextContent(), "path": node.getElementsByTagName("path").item(0).getTextContent(), "extension": node.getElementsByTagName("extension").item( 0).getTextContent(), "request": request, "status": node.getElementsByTagName("status").item( 0).getTextContent(), "responselength": node.getElementsByTagName("responselength").item( 0).getTextContent(), "mimetype": node.getElementsByTagName("mimetype").item( 0).getTextContent(), "response": response, "comment": node.getElementsByTagName("comment").item( 0).getTextContent(), "highlight": "" } logEntry = LogEntry(info) # Remove GET parameters from path component # Path component usually looks like this: /some/path/index.html?q=foo&z=faa info["path"] = info["path"].split("?")[0] # Extract GET parameters params = [] for param in self._helpers.analyzeRequest( logEntry).getParameters(): if param.getType() == IParameter.PARAM_URL: params.append("{}={}".format(param.getName(), param.getValue())) info["params"] = "&".join(params) self.addLogEntryToList(logEntry)
import re import sys #from xml.dom import javadom from org.apache.log4j import * from java.io import FileInputStream from javax.xml.transform.stream import StreamSource from javax.xml.transform.stream import StreamResult from javax.xml.parsers import DocumentBuilderFactory from org.xml.sax import InputSource from java.io import StringReader factory = DocumentBuilderFactory.newInstance() builder = factory.newDocumentBuilder() class ProcessConfig: logger = Logger.getLogger("ProcessConfig") def readConfig(self, fh=None, xml=None): self.fh = fh self.xml = xml self.tree = None self.doc = None self.cellTree = None if self.fh != None: self.logger.info("readConfig: processing xml file") self.logger.debug("readConfig: file %s " % fh) input = FileInputStream(self.fh) fhtree = builder.parse(input) self.tree = fhtree.getDocumentElement() self.cellTree = fhtree.getElementById('Cell') elif self.xml != None:
def loadXMLFromFile(xml): db = DocumentBuilderFactory.newInstance().newDocumentBuilder() return(db.parse(xml))
def loadXMLFromString(xml): db = DocumentBuilderFactory.newInstance().newDocumentBuilder() inputSource = InputSource(StringReader(xml)); return(db.parse(inputSource))
def __init__(self, docFile): dbf = DocumentBuilderFactory.newInstance() db = dbf.newDocumentBuilder() myFile = File(docFile) self.doc = db.parse (myFile) self.doc.getDocumentElement().normalize()
def _buildDocumentForXpath(content, namespaceAware=1): r'@types: str, int -> org.w3c.dom.Document' xmlFact = DocumentBuilderFactory.newInstance() xmlFact.setNamespaceAware(namespaceAware) builder = xmlFact.newDocumentBuilder() return builder.parse(ByteArrayInputStream(String(content).getBytes()))
def update(self): """Update information shown by the dialog with those of currently selected error """ from java.net import URL, URLEncoder from javax.xml.parsers import DocumentBuilderFactory error = self.app.selectedError check = error.check view = check.view tool = view.tool #user info if error.user is not None: errorUserName = error.user.getName() errorUserId = str(error.user.getId()) #download user info from OSM API accountDate = None changesetsNumber = None if errorUserId in self.app.users: userInfo = self.app.users[errorUserId] accountDate = userInfo["account date"] changesetsNumber = userInfo["changesets number"] else: docFactory = DocumentBuilderFactory.newInstance() docBuilder = docFactory.newDocumentBuilder() url = URL("http://api.openstreetmap.org/api/0.6/user/" + errorUserId) try: stream = url.openStream() doc = docBuilder.parse(stream) rootElement = doc.getDocumentElement() userNode = rootElement.getElementsByTagName("user").item(0) accountDate = userNode.getAttributes().getNamedItem("account_created").getNodeValue() changesetsNode = rootElement.getElementsByTagName("changesets").item(0) changesetsNumber = changesetsNode.getAttributes().getNamedItem("count").getNodeValue() except: print "I could not download user info from:\n", url pass if accountDate is not None: self.app.users[errorUserId] = {"account date": accountDate, "changesets number": changesetsNumber} #user links encodedErrorUserName = URLEncoder.encode(errorUserName, "UTF-8").replace("+", "%20") userUrl = "http://www.openstreetmap.org/user/%s/" % encodedErrorUserName msgUrl = "http://www.openstreetmap.org/message/new/%s" % encodedErrorUserName #update user info text = "<html><table>" text += "<tr><td>%s</td>" % self.app.strings.getString("User_name") text += "<td><a href='%s'>%s</a></td></tr>" % (userUrl, errorUserName) if accountDate is not None: text += "<tr>" text += "<td>%s</td>" % self.app.strings.getString("Changesets") text += "<td>%s</td>" % changesetsNumber text += "</tr><tr>" text += "<td>%s</td>" % self.app.strings.getString("Mapper_since") text += "<td>%s</td>" % accountDate[:10] text += "</tr>" text += "</table>" text += "<a href='%s'>%s</a>" % (msgUrl, self.app.strings.getString("Send_a_message")) text += "</html>" self.userInfoPanel.setText(text) #error info text = "<html>" #tool text += "%s:<br>%s" % (self.app.strings.getString("Error_reported_by_the_tool"), tool.title) if tool.uri != "": text += "<br>%s" % self.link(tool.uri) #error type if not tool.isLocal: text += "<br><br>%s:" % self.app.strings.getString("Type_of_error") text += "<br>%s --> %s" % (view.title, check.title) #error help, usually a link to a Wiki page describing this errror type #error link, e.g. a link to the error on the tool web page for propName, prop in ((self.app.strings.getString("Error_help"),\ check.helpUrl), (self.app.strings.getString("Error_link"), tool.error_url(error))): if prop != "": text += "<br><br>%s:" % propName text += "<br>%s" % self.link(prop) #error description, usually some info contained in the error file if error.desc != "": text += "<br><br>%s:" % self.app.strings.getString("Description") text += "<br>%s" % error.desc #OSM object if error.osmId != "": osmType = {"n": "node", "w": "way", "r": "relation"} osmLinks = "" osmIds = error.osmId.split("_") for i, osmId in enumerate(osmIds): osmIdUrl = "http://www.openstreetmap.org/%s/%s" % (osmType[osmId[0]], osmId[1:]) osmLinks += self.link(osmIdUrl) if i != len(osmIds) - 1: osmLinks += "<br>" text += "<br><br>%s:" % self.app.strings.getString("OSM_objects") text += "<br>%s" % osmLinks #OSM changeset if error.changeset is not None: changesetUrl = "http://www.openstreetmap.org/changeset/%s" % error.changeset text += "<br><br>%s:" % self.app.strings.getString("OSM_changeset") text += "<br>%s" % self.link(changesetUrl) text += "</html>" #Update error info self.errorInfoPanel.setText(text) self.show()
def getDocument(self, content, namespaceAware=1): xmlFact = DocumentBuilderFactory.newInstance() xmlFact.setNamespaceAware(namespaceAware) builder = xmlFact.newDocumentBuilder() return builder.parse(ByteArrayInputStream(String(content).getBytes()))
#message=zlib.decompress(zipmessage,8) fmessage=gzip.GzipFile(fileobj=zipstore,mode='rb') # the way to gunzip in jython message=fmessage.read() fmessage.close() except: print "Unzip failure %s, %s" % (sys.exc_info()[0],sys.exc_info()[1]) #print>>fout, message fout.write(zipmessage) sys.exit(3) print>>fdump,message try: # process the content # first discern the serialization method if message[0:5] == "<?xml": # XML serialization. xmldoc=(DocumentBuilderFactory.newInstance()).newDocumentBuilder() doc=xmldoc.parse(InputSource(StringReader(message))) main=doc.getElementsByTagName("object"); # firstChild did not work since it returns #text print>>fout,"old,", msgbody=main.item(0).getElementsByTagName("class").item(0).childNodes#getElementsByTagName("object") #msgbody=doc.firstChild.firstChild.childNodes for obj in [msgbody.item(i) for i in range(msgbody.length) if msgbody.item(i).nodeName == "object"]: #msgbody.item(i).nodeType == msgbody.item(i).ELEMENT_NODE]: if obj.getAttribute("class") == "com.ibm.itim.remoteservices.ejb.mediation.ServiceProviderReconciliationMessageObject": header="Recon" so=obj.getElementsByTagName("special-object") serviceDN=[so.item(i).getAttribute("value").strip() for i in range(so.length) if so.item(i).getAttribute("name") == "serviceDN"] serviceName=isimldap.locate(serviceDN[0])["erservicename"][0].encode('ascii') if serviceName == None: print>>fscript,"DELETE FROM SCHEDULED_MESSAGE WHERE SCHEDULED_MESSAGE_ID = %s " % line[1] header = "Bad recon" serviceName = serviceDN[0]
def getDocument(self, content, namespaceAware = 1): xmlFact = DocumentBuilderFactory.newInstance() xmlFact.setNamespaceAware(namespaceAware) builder = xmlFact.newDocumentBuilder() return builder.parse(ByteArrayInputStream(String(content).getBytes()))
# only run if OS discovered as RHEL and cluster.conf file exists if server.hasOSRunning() and server.getOSRunning().hasOSVersion() and server.getOSRunning().getOSVersion().startswith('Red Hat Enterprise Linux') and int(sensorhelper.executeCommand('[ -f ' + cluster_conf_file + ' ] && echo "1" || echo "0"')): # get scoped cman_tool command from collation.properties cmanCommand = ScopedProps.getStringProperty('com.collation.discover.agent.command.cman', 'Linux', os_handle.getSession().getHost()) if cmanCommand is None or len(cmanCommand) == 0: cmanCommand = 'cman_tool' # XML document for cluster.conf doc = None try: # grab cluster configuration file, this will throw exception if file is not readable # Note: don't pipe command to anything or it won't throw an exception cluster_conf = str(sensorhelper.executeCommand('cat ' + cluster_conf_file)) dbFactory = DocumentBuilderFactory.newInstance() dBuilder = dbFactory.newDocumentBuilder() doc = dBuilder.parse(ByteArrayInputStream(String(cluster_conf).getBytes())) doc.getDocumentElement().normalize() except: msg = 'redhat_cluster.py: The following file does not exist or is not readable: ' + cluster_conf_file LogError(msg) # throw up warning on discovery UI result.warning(msg) try: # get cluster name if doc is None: # use command if we can't read cluster.conf clustername = str(sensorhelper.executeCommand(cmanCommand + ' status | grep "Cluster Name" | awk -F: {\'print $2\'}')).strip() if len(clustername) == 0: