def __renderClassDiagram(self, documentNode: Element, toOgl: MiniDomToOglV10, umlFrame: UmlDiagramsFrame): """ Args: documentNode: A minidom document element toOgl: The converter class umlFrame: Where to render """ oglClasses: OglClasses = toOgl.getOglClasses( documentNode.getElementsByTagName( PyutXmlConstants.ELEMENT_GRAPHIC_CLASS)) oglNotes: OglNotes = toOgl.getOglNotes( documentNode.getElementsByTagName( PyutXmlConstants.ELEMENT_GRAPHIC_NOTE)) oglInterfaces: OglInterfaces = toOgl.getOglInterfaces( documentNode.getElementsByTagName( PyutXmlConstants.ELEMENT_GRAPHIC_LOLLIPOP), oglClasses) oglTextShapes: OglTextShapes = toOgl.getOglTextShapes( documentNode.getElementsByTagName( PyutXmlConstants.ELEMENT_GRAPHIC_TEXT)) mergedOglObjects: OglObjects = cast(OglObjects, oglClasses.copy()) mergedOglObjects.update(oglNotes) self.__displayTheClasses(oglClasses, umlFrame) oglLinks: OglLinks = toOgl.getOglLinks( documentNode.getElementsByTagName( PyutXmlConstants.ELEMENT_GRAPHIC_LINK), mergedOglObjects) self.__displayTheLinks(oglLinks, umlFrame) self.__displayTheNotes(oglNotes, umlFrame) self.__displayTheTextShapes(oglTextShapes, umlFrame) self.__displayTheInterfaces(oglInterfaces, umlFrame)
def __renderUseCaseDiagram(self, documentNode: Element, toOgl: MiniDomToOglV10, umlFrame: UmlDiagramsFrame): """ Args: documentNode: A minidom document element toOgl: The converter class umlFrame: Where to render """ oglObjects: OglObjects = cast(OglObjects, {}) oglActors: OglActors = toOgl.getOglActors( documentNode.getElementsByTagName('GraphicActor')) oglUseCases: OglUseCases = toOgl.getOglUseCases( documentNode.getElementsByTagName('GraphicUseCase')) oglNotes: OglNotes = toOgl.getOglNotes( documentNode.getElementsByTagName('GraphicNote')) self.__displayTheActors(oglActors, umlFrame) self.__displayTheUseCases(oglUseCases, umlFrame) self.__displayTheNotes(oglNotes, umlFrame) mergedOglObjects: OglObjects = cast(OglObjects, oglObjects.copy()) mergedOglObjects.update(oglActors) mergedOglObjects.update(oglNotes) mergedOglObjects.update(oglUseCases) oglLinks: OglLinks = toOgl.getOglLinks( documentNode.getElementsByTagName("GraphicLink"), mergedOglObjects) self.__displayTheLinks(oglLinks, umlFrame)
def getStorageSize(nodeParam: minidom.Element, unit: str) -> str: addr = nodeParam.getElementsByTagName('address') if addr and addr[0]: addrLength = addr[0].getAttribute('length') if addrLength: return 8 * int(addrLength) for item in nodeParam.getElementsByTagName('conversion'): if unit == item.getAttribute('units'): storagetype = item.getAttribute('storagetype') if storagetype == 'uint16': return 16 return None
def parseParty(self, xmlParty: Element) -> InvoiceParty: party = InvoiceParty() xml_ident = xmlParty.getElementsByTagName("cac:PartyIdentification")[0] party.taxId = xmlExtractText(xml_ident, 'cbc:ID') party.accountNumber = "" xml_party_name = xmlParty.getElementsByTagName("cac:PartyName")[0] party.name = xmlExtractText(xml_party_name, 'cbc:Name') xml_address = xmlParty.getElementsByTagName("cac:PostalAddress")[0] party.streetAndNumber = xmlExtractText(xml_address, 'cbc:StreetName') party.cityName = xmlExtractText(xml_address, 'cbc:CityName') party.postalCode = xmlExtractText(xml_address, 'cbc:PostalZone') party.country = xmlExtractText(xml_address, 'cbc:IdentificationCode') return party
def _parse_element_to_list_of_dict(root: minidom.Element, component: Dict[str, Any], tag: str) -> List[Any]: """ Parse the complex application elements (i.e. parse also the "meta-data" and "intent-filter" information). :param root: The XML element. :param component: The XML element (dictionary of tag and attributes). :param tag: The root element tag (e.g. 'activity', 'service' or 'receiver'). :return: The list of attribute values. """ res = [] for element in root.getElementsByTagName(tag): data = {} for key, value in component.items(): if type(value) is dict: tmp = AndroidManifest._parse_element_to_list_of_dict(element, component[key], key) if len(tmp) > 0: data[key] = tmp elif type(value) is list: tmp = AndroidManifest._parse_element_to_simple_list(element, key, value[0]) if len(tmp) > 0: tmp.sort() data[key] = tmp else: # type(value) is str (in Python 2.7 this will be unicode) if element.hasAttribute(component[key]): data[key] = element.getAttribute(component[key]) res.append(data) return res
def _getFields(self, xmlClass: Element) -> PyutFields: """ Extracts fields from a DOM element that represents a UML class Args: xmlClass: The DOM version of a UML class Returns: PyutFields """ pyutFields: PyutFields = cast(PyutFields, []) for element in xmlClass.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_FIELD): xmlField: Element = cast(Element, element) pyutField: PyutField = PyutField() strVis: str = xmlField.getAttribute(PyutXmlConstants.ATTR_VISIBILITY) vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(strVis) pyutField.setVisibility(vis) xmlParam: Element = xmlField.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_PARAM)[0] if xmlParam.hasAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE): pyutField.setDefaultValue(xmlParam.getAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE)) pyutField.setName(xmlParam.getAttribute(PyutXmlConstants.ATTR_NAME)) pyutType: PyutType = PyutType(xmlParam.getAttribute(PyutXmlConstants.ATTR_TYPE)) pyutField.setType(pyutType) pyutFields.append(pyutField) return pyutFields
def _parse_element_to_list_of_dict(root: minidom.Element, component: Dict[str, Any], tag: str) -> List[Any]: """ Parse the complex application elements (i.e. parse also the "meta-data" and "intent-filter" information). :param root: The XML element. :param component: The XML element (dictionary of tag and attributes). :param tag: The root element tag (e.g. 'activity', 'service' or 'receiver'). :return: The list of attribute values. """ res = [] for element in root.getElementsByTagName(tag): data = {} for key, value in component.items(): if type(value) is dict: tmp = AndroidManifest._parse_element_to_list_of_dict( element, component[key], key) if len(tmp) > 0: data[key] = tmp elif type(value) is list: tmp = AndroidManifest._parse_element_to_simple_list( element, key, value[0]) if len(tmp) > 0: tmp.sort() data[key] = tmp else: # type(value) is str (in Python 2.7 this will be unicode) if element.hasAttribute(component[key]): data[key] = element.getAttribute(component[key]) res.append(data) return res
def _getParam(self, Param: Element, pyutMethod: PyutMethod): """ Extract param from Xmi file from Class part. Args: Param: pyutMethod: Returns: PyutParam """ aParam = PyutParam() # param's name name = Param.getElementsByTagName( "Foundation.Core.ModelElement.name")[0].firstChild if name.nodeType == name.TEXT_NODE: self.logger.debug(f'Parameter name: {name.data}') if name.data[-6:] == "Return" or name.data[-6:] == "return": self._getTypeId(Param, pyutMethod, self.dicoReturn) return None else: aParam.setName(name.data) # default value self._getDefaultValue(Param, aParam) # for type self._getTypeId(Param, aParam, self.dicoType) return aParam
def __init__(self, dom_element: Element) -> None: self._dom_element = dom_element message_cdata = dom_element.getElementsByTagName('log4j:message')[0].firstChild message_cdata_string = '' if message_cdata is not None: message_cdata_string = message_cdata.data throwable_list = self._dom_element.getElementsByTagName('log4j:throwable') if len(throwable_list) == 1: throwable_element = throwable_list[0] else: throwable_element = dom_element.ownerDocument.createElementNS('log4j', 'throwable') location_info_list = self._dom_element.getElementsByTagName('log4j:locationInfo') if len(location_info_list) == 1: location_info_element = location_info_list[0] else: location_info_element = self._dom_element.ownerDocument.createElementNS('log4j', 'locationInfo') location_info = DomLocationInfo(location_info_element) Event.__init__( self, dom_element.getAttribute("logger"), dom_element.getAttribute("timestamp"), dom_element.getAttribute("level"), dom_element.getAttribute("thread"), message_cdata_string, throwable_element, location_info )
def _getPyutLink(self, obj: Element): """ Args: obj: The GraphicLink DOM element Returns: A tuple of a source ID, destination ID, and a PyutLink object """ link: Element = obj.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_LINK)[0] pyutLink: PyutLink = PyutLink() pyutLink.setBidir( bool(link.getAttribute(PyutXmlConstants.ATTR_BIDIRECTIONAL))) pyutLink.destinationCardinality = link.getAttribute( PyutXmlConstants.ATTR_CARDINALITY_DESTINATION) pyutLink.sourceCardinality = link.getAttribute( PyutXmlConstants.ATTR_CARDINALITY_SOURCE) pyutLink.setName(link.getAttribute(PyutXmlConstants.ATTR_NAME)) strLinkType: str = link.getAttribute(PyutXmlConstants.ATTR_TYPE) strLinkType = strLinkType.replace(PyutXmlConstants.V9_LINK_PREFIX, '') linkType: LinkType = LinkType.toEnum(strValue=strLinkType) pyutLink.setType(linkType) # source and destination will be reconstructed by _getOglLinks sourceId = int(link.getAttribute(PyutXmlConstants.ATTR_SOURCE_ID)) destId = int(link.getAttribute(PyutXmlConstants.ATTR_DESTINATION_ID)) return sourceId, destId, pyutLink
def build_manifest_from_dom(file: File, extended_processing: bool, dom: Element) -> AndroidManifest: if extended_processing: application = dom.getElementsByTagName("application")[0] activities = AndroidManifestParser.parse_activities_from_dom(application) services = AndroidManifestParser.parse_services_from_dom(application) receivers = AndroidManifestParser.parse_broadcast_receivers_from_dom(application) else: activities = [] services = [] receivers = [] return AndroidManifest( filename=file.get_file_name(), size=file.get_size(), md5hash=file.get_md5(), sha1hash=file.get_sha1(), sha256hash=file.get_sha256(), sha512hash=file.get_sha512(), package_name=dom.getAttribute("package"), version=AndroidManifestParser.parse_version_from_dom(dom), sdk=AndroidManifestParser.parse_sdk_from_dom(dom), permissions=AndroidManifestParser.__parse_list_from_dom( dom, tag="uses-permission", attribute="android:name" ), activities=activities, services=services, receivers=receivers )
def __init__(self, testcase: Element): self.__properties_tag_name = 'property' self.__properties_iter = iter( testcase.getElementsByTagName(self.__properties_tag_name)) self.__current = None print(f"INFO: Successfully extracted properties from test case")
def _get_descendant(element: Element, path: str): path = path.split('.') if len(path) > 1: childs = element.getElementsByTagName(path[0]) if len(childs) != 1: msg = "Only the deepest descendant in selection query can be non-unique. Perhaps break the filter into multiple selections?" logger.error(msg) raise NotImplementedError(msg) child = childs[0] return _get_descendant(child, '.'.join(path[1:])) else: rel = element.getElementsByTagName(path[0]) return rel
def extract_properties(xml_node: minidom.Element) -> dict: """Extract properties in the <ns2:properties> tag of the provided node :param xml_node: minidom.Element, parsed XML node :return: dict, with the extracted properties. """ properties = {} for property_node in xml_node.getElementsByTagName("ns2:properties"): for child_node in property_node.childNodes: try: property_name = child_node.attributes[ "propertyDefinitionId"].value except KeyError: continue node_values = child_node.getElementsByTagName("ns2:value") if len(node_values) == 0 or len( node_values[0].childNodes) == 0: properties[property_name] = {"value": None} else: properties[property_name] = { "value": parsePropValue(node_values[0].childNodes[0].data, child_node.localName) } return properties
def __init__(self, testsuite: Element): self.__test_case_tag_name = 'testcase' self.all = testsuite.getElementsByTagName(self.__test_case_tag_name) print(f'INFO: Successfully extracted test cases in test suite')
def get_objects(root: minidom.Element): object_list = [] for object in root.getElementsByTagName(name='object'): box = get_bound_boxes(object) name = get_name(object) object_list.append(','.join(box) + ',' + name) return object_list
def get_bound_boxes(root: minidom.Element): bound_box = root.getElementsByTagName(name="bndbox") assert len(bound_box) == 1 bound_box: minidom.Element = bound_box[0] return [str(bound_box.getElementsByTagName(name="xmin")[0].childNodes[0].data), str(bound_box.getElementsByTagName(name="ymin")[0].childNodes[0].data), str(bound_box.getElementsByTagName(name="xmax")[0].childNodes[0].data), str(bound_box.getElementsByTagName(name="ymax")[0].childNodes[0].data)]
def _getImplementors(self, xmlClass: Element) -> Implementors: implementors: Implementors = Implementors([]) for xmlImplementor in xmlClass.getElementsByTagName(PyutXmlConstants.ELEMENT_IMPLEMENTOR): className: ClassName = xmlImplementor.getAttribute(PyutXmlConstants.ATTR_IMPLEMENTING_CLASS_NAME) implementors.append(className) return implementors
def __renderClassDiagram(self, documentNode: Element, toOgl: MiniDomToOgl, umlFrame: UmlFrame): """ Args: documentNode: A minidom document element toOgl: The converter class umlFrame: Where to render """ oglClasses: OglClasses = toOgl.getOglClasses(documentNode.getElementsByTagName(PyutXmlConstants.ELEMENT_GRAPHIC_CLASS)) oglNotes: OglNotes = toOgl.getOglNotes(documentNode.getElementsByTagName('GraphicNote')) mergedOglObjects: OglObjects = cast(OglObjects, oglClasses.copy()) mergedOglObjects.update(oglNotes) self.__displayTheClasses(oglClasses, umlFrame) oglLinks: OglLinks = toOgl.getOglLinks(documentNode.getElementsByTagName("GraphicLink"), mergedOglObjects) self.__displayTheLinks(oglLinks, umlFrame) self.__displayTheNotes(oglNotes, umlFrame)
def value_from_xml_element(self, xml: minidom.Element, registry: ObjectRegistry): if xml.tagName != self.tag_name: raise ValueError("Wrong value type (%s instead of %s)" % (xml.tagName, self.tag_name)) guid = xml.getAttribute("guid") if guid and guid in registry.registry: value = registry.registry[guid] elif self.typename == "vector": value = NVector( float(xml_text(xml.getElementsByTagName("x")[0])), float(xml_text(xml.getElementsByTagName("y")[0])) ) if xml.getAttribute("guid"): value.guid = xml.getAttribute("guid") registry.register(value) elif self.typename == "color": value = NVector( float(xml_text(xml.getElementsByTagName("r")[0])), float(xml_text(xml.getElementsByTagName("g")[0])), float(xml_text(xml.getElementsByTagName("b")[0])), float(xml_text(xml.getElementsByTagName("a")[0])) ) elif self.typename == "gradient": value = [ GradientPoint.from_dom(sub, registry) for sub in xml_child_elements(xml, GradientPoint.type.typename) ] elif self.typename == "real" or self.typename == "angle": value = float(xml.getAttribute("value")) elif self.typename == "integer": value = int(xml.getAttribute("value")) elif self.typename == "time": value = FrameTime.parse_string(xml.getAttribute("value"), registry) elif self.typename == "bool": value = str_to_bool(xml.getAttribute("value")) elif self.typename == "string": return xml_text(xml) elif self.typename == "bone_object": # Already done above but this forces the guid to be present return registry.get_object(xml.getAttribute("guid")) else: raise ValueError("Unsupported type %s" % self.typename) return self.type_wrapper(value)
def _parse_patterns(self, xdom: Element) -> Dict[str, str]: result: Dict[str, str] = dict() patterns = xdom.getElementsByTagName("patterns") for pattern in patterns: for node in pattern.childNodes: if not isinstance(node, Text): result[node.tagName] = self._to_text(node) return result
def _generateControlPoints(self, link: Element) -> ControlPoints: controlPoints: ControlPoints = cast(ControlPoints, []) for controlPoint in link.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_CONTROL_POINT): x = PyutUtils.strFloatToInt(controlPoint.getAttribute(PyutXmlConstants.ATTR_X)) y = PyutUtils.strFloatToInt(controlPoint.getAttribute(PyutXmlConstants.ATTR_Y)) controlPoints.append(ControlPoint(x, y)) return controlPoints
def _parse_labels(self, xdom: Element) -> Dict[str, str]: result: Dict[str, str] = dict() labels = xdom.getElementsByTagName("labels") for label in labels: for node in label.childNodes: if not isinstance(node, Text): result[self._to_text(node)] = node.tagName return result
def parseHeader(self, xmlHeader: Element) -> InvoiceHeader: header = InvoiceHeader() header.number = xmlExtractText(xmlHeader, 'NUMER_PELNY') header.invoiceDate = xmlExtractDate(xmlHeader, 'DATA_WYSTAWIENIA') header.salesDate = xmlExtractDate(xmlHeader, 'DATA_OPERACJI') header.currency = xmlExtractText(xmlHeader, 'SYMBOL') payment_xml = xmlHeader.getElementsByTagName("PLATNOSC")[0] header.paymentDueDate = xmlExtractDate(payment_xml, 'TERMIN') header.paymentTerms = xmlExtractText(payment_xml, 'FORMA') header.documentFunctionCode = "" return header
def _parse_mappings(self, xdom: Element) -> Dict[str, str]: result: Dict[str, str] = dict() mappings = xdom.getElementsByTagName("mappings") for mapping in mappings: for node in mapping.childNodes: if not isinstance(node, Text): result[node.getAttribute("inbound")] = node.getAttribute( "outbound") return result
def _generateMethodParameters( self, xmlMethod: Element, methodDef: MethodDefinition) -> MethodDefinition: parameters: Parameters = [] for xmlParam in xmlMethod.getElementsByTagName(ELEMENT_MODEL_PARAM): paramDef: ParameterDefinition = self._getParam(xmlParam=xmlParam) parameters.append(paramDef) methodDef.parameters = parameters return methodDef
def __parse_metadata_from_dom(dom: Element) -> List[Dict]: metadata = [] for element in dom.getElementsByTagName("meta-data"): data = AndroidManifestParser.__parse_dict_from_dom( element, attributes={ "name": "android:name", "value": "android:value" } ) metadata.append(data) return metadata
def parse_broadcast_receivers_from_dom(dom: Element) -> List[Dict]: receivers = [] for element in dom.getElementsByTagName("receiver"): receiver = AppBroadcastReceiver( name=element.getAttribute("android:name"), metadata=AndroidManifestParser.__parse_metadata_from_dom(element), intent_filters=AndroidManifestParser.__parse_intent_filters_from_dom(element), enabled=AndroidManifestParser.__parse_bool_from_dom(element, "android:enabled"), exported=AndroidManifestParser.__parse_bool_from_dom(element, "android:exported") ) receivers.append(receiver) return receivers
def parse_activities_from_dom(dom: Element) -> List[AppActivity]: activities = [] for element in dom.getElementsByTagName("activity"): activity = AppActivity( name=element.getAttribute("android:name"), metadata=AndroidManifestParser.__parse_metadata_from_dom(element), intent_filters=AndroidManifestParser.__parse_intent_filters_from_dom(element), parent_name=AndroidManifestParser.__parse_str_from_dom(element, "android:parentActivityName"), launch_mode=AndroidManifestParser.__parse_str_from_dom(element, "android:launchMode"), no_history=AndroidManifestParser.__parse_str_from_dom(element, "android:noHistory") ) activities.append(activity) return activities
def _getMethods(self, xmlClass: Element) -> PyutMethods: """ Converts XML methods to `PyutMethod`s Args: xmlClass: A DOM element that is a UML Class Returns: A list of `PyutMethod`s associated with the class """ allMethods: PyutMethods = cast(PyutMethods, []) for xmlMethod in xmlClass.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_METHOD): pyutMethod: PyutMethod = PyutMethod( xmlMethod.getAttribute(PyutXmlConstants.ATTR_NAME)) strVis: str = xmlMethod.getAttribute( PyutXmlConstants.ATTR_VISIBILITY) vis: PyutVisibilityEnum = PyutVisibilityEnum.toEnum(strVis) pyutMethod.setVisibility(visibility=vis) returnElt: Element = xmlMethod.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_RETURN)[0] retTypeStr: str = returnElt.getAttribute( PyutXmlConstants.ATTR_TYPE) retType: PyutType = PyutType(retTypeStr) pyutMethod.setReturns(retType) # # Code supports multiple modifiers, but the dialog allows input of only one # modifiers: NodeList = xmlMethod.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_MODIFIER) for xmlModifier in modifiers: xmlModifier: Element = cast(Element, xmlModifier) modName: str = xmlModifier.getAttribute( PyutXmlConstants.ATTR_NAME) pyutModifier: PyutModifier = PyutModifier(modName) pyutMethod.addModifier(pyutModifier) methodParameters = [] for xmlParam in xmlMethod.getElementsByTagName( PyutXmlConstants.ELEMENT_MODEL_PARAM): methodParameters.append(self._getParam(xmlParam)) pyutMethod.setParams(methodParameters) allMethods.append(pyutMethod) return allMethods
def parseSummary(self, xmlSummary: Element) -> InvoiceSummary: summary = InvoiceSummary() summary.totalLines = xmlExtractText(xmlSummary, 'TotalLines') summary.totalNetAmount = xmlExtractText(xmlSummary, 'TotalNetAmount') summary.totalTaxableBasis = xmlExtractText(xmlSummary, 'TotalTaxableBasis') summary.totalTaxAmount = xmlExtractText(xmlSummary, 'TotalTaxAmount') summary.totalGrossAmount = xmlExtractText(xmlSummary, 'TotalGrossAmount') summary.grossAmountInWords = xmlExtractText(xmlSummary, 'GrossAmountInWords') summary.taxSummary = self.parseTaxSummary( xmlSummary.getElementsByTagName("Tax-Summary-Line")[0]) return summary
def _parse_element_to_simple_list(root: minidom.Element, tag: str, attribute: str) -> List[Any]: """ Parse the simple application elements (i.e. only the "android:name"). :param root: The XML element. :param tag: The root element tag to look for (e.g. "uses-permission", "action", "category", ...). :param attribute: The unique tag attribute name (e.g. "android:name"). :return: The list of attribute values. """ res = [] for element in root.getElementsByTagName(tag): res.append(element.getAttribute(attribute)) if len(res) > 0: res.sort() return res