def _readFoundationCoreClass(self, coreClass): """ Read one Foundation.Core.Class @param coreClass : Foundation.Core.Class element @author C.Dutoit """ # Get class name className = self._readFoundationCoreClassName(coreClass) self.logger.info("Reading class ", className, end=' ') # Get class ID classID = str(coreClass.getAttribute("xmi.id")) self.logger.info("id = ", classID, end=' ') # Save class pyutClass = PyutClass(className) # Get class abstract status isAbstract = self._readFoundationCoreClassIsAbstract(coreClass) self.logger.info("isAbstract = ", isAbstract) if isAbstract: pyutClass.setStereotype("Abstract") # Get class features self._readFoundationCoreClassifierFeature(coreClass, pyutClass) # Make the PyutClass visible oglClass = OglClass(pyutClass) x = (len(self._dicOglClasses) % 10) * 100 y = len(self._dicOglClasses) / 10 * 100 self._umlFrame.addShape(oglClass, x, y) oglClass.autoResize() self._dicOglClasses[classID] = oglClass
def _getOglClasses(self, xmlOglClasses, dicoOglObjects, umlFrame, oldData): """ Parse the XMI elements given and build data layer for PyUT classes. If file is version 1.0, the dictionary given will contain, for key, the name of the OGL object. Otherwise, it will be the ID (multi-same-name support from version 1.1). Everything is fixed later. @param Element[] xmlOglClasses : XMI 'GraphicClass' elements @param {id / srcName, OglObject} dicoOglObjects : OGL objects loaded @param UmlFrame umlFrame : Where to draw @param int oldData : If old data (v1.0), 1 else 0 @since 2.0 @author Philippe Waelti <*****@*****.**> """ pyutClass = PyutClass() # adding name for this class className = xmlOglClasses.getElementsByTagName("Foundation.Core.ModelElement.name") self.logger.debug(f'Ogl class name: {className}') if len(className) > 0: name = className[0].firstChild if name.nodeType == name.TEXT_NODE: pyutClass.setName(name.data) oglClass = OglClass(pyutClass, 50, 50) # adding methods for this class pyutClass.setMethods(self._getMethods(xmlOglClasses)) # adding fields for this class pyutClass.fields = self._getFields(xmlOglClasses) # for class id classId = xmlOglClasses.getAttribute("xmi.id") self.logger.debug(f"Class ID: {classId}") # for all the classes who are an inheritance link for fathers in xmlOglClasses.getElementsByTagName("Foundation.Core.Generalization"): linkId = fathers.getAttribute("xmi.idref") self.logger.debug(f"parent: {linkId}") if linkId not in self.dicoFather: self.dicoFather[linkId] = {} self.dicoFather[linkId][classId] = oglClass # for all class whos are link for links in xmlOglClasses.getElementsByTagName("Foundation.Core.Classifier.associationEnd"): for link in links.getElementsByTagName("Foundation.Core.AssociationEnd"): linkId = link.getAttribute("xmi.idref") self.logger.debug(f"linkId: {linkId}") if linkId not in self.dicoLinks: self.dicoLinks[linkId] = oglClass pyutClassId = pyutClass.getId() self.logger.debug(f'pyutClassId: {pyutClassId}') dicoOglObjects[pyutClassId] = oglClass umlFrame.addShape(oglClass, 100, 100)
def _writeClass(self, pyutClass: PyutClass): """ Writing a class to a file. Args: pyutClass: The PyutClass object to write """ className = pyutClass.getName() # Opening a file for each class fqn: str = f'{self._dir}{osSep}{className}.java' flags: int = O_WRONLY | O_CREAT javaFileFD: int = open(fqn, flags) # Extract the data from the class fields = pyutClass.fields methods = pyutClass.methods parents = pyutClass.getParents() allLinks: PyutLinks = pyutClass.getLinks() stereotype: PyutStereotype = pyutClass.getStereotype() # List of links interfaces: PyutLinks = PyutLinks([]) # List of interfaces implemented by the class links: PyutLinks = PyutLinks([]) # Aggregation and compositions self._separateLinks(allLinks, interfaces, links) # Is it an interface classInterface = "class" if stereotype is not None: stereotypeName: str = stereotype.getStereotype() if stereotypeName.lower() == "interface": classInterface = "interface" self._writeClassComment(javaFileFD, className, classInterface) write(javaFileFD, f'public {classInterface} {className}'.encode()) self._writeParent(javaFileFD, parents) self._writeInterfaces(javaFileFD, interfaces) write(javaFileFD, ' {\n\n'.encode()) self._writeFields(javaFileFD, fields) # Aggregation and Composition self._writeLinks(javaFileFD, links) self._writeMethods(javaFileFD, methods) write(javaFileFD, '}\n'.encode())
def __init__(self, pyutClass: PyutClass = None, w: int = 0, h: int = 0): """ Args: pyutClass: a PyutClass object w: Width of the shape h: Height of the shape """ if pyutClass is None: pyutObject = PyutClass() else: pyutObject = pyutClass width: int = w height: int = h # Use preferences to get initial size if not specified # Note: auto_resize_shape_on_edit must be False for this size to actually stick preferences: PyutPreferences = PyutPreferences() if w == 0: width = preferences.classDimensions.width if h == 0: height = preferences.classDimensions.height super().__init__(pyutObject, width=width, height=height) self._nameFont: Font = Font(DEFAULT_FONT_SIZE, FONTFAMILY_SWISS, FONTSTYLE_NORMAL, FONTWEIGHT_BOLD) self.logger: Logger = getLogger(__name__)
def _createNewClass(self, x, y): """ Add a new class at (x, y). @return PyutClass : the newly created PyutClass @since 1.4 @author L. Burgbacher <*****@*****.**> """ from org.pyut.general.Mediator import getMediator from org.pyut.model.PyutClass import PyutClass from org.pyut.ogl.OglClass import OglClass med = getMediator() umlFrame = med.getFileHandling().getCurrentFrame() pyutClass = PyutClass(_("NoName")) oglClass = OglClass(pyutClass) med.classEditor(pyutClass) # med.autoResize(pyutClass) umlFrame.addShape(oglClass, x, y, withModelUpdate=True) med.autoResize(pyutClass) umlFrame.Refresh() return oglClass
def generateClassStanza(self, pyutClass: PyutClass) -> str: """ Generates something like this ```python class Car: ``` or with inheritance ```python class ElectricCar(BaseVehicle, Car): ``` ` Args: pyutClass: The data model class Returns: The Python class start stanza """ generatedCode: str = f'class {pyutClass.getName()}' parentPyutClasses: List[PyutClass] = cast(List[PyutClass], pyutClass.getParents()) if len(parentPyutClasses) > 0: # Add parents generatedCode = f'{generatedCode}(' for i in range(len(parentPyutClasses)): generatedCode = f'{generatedCode}{parentPyutClasses[i].getName()}' if i < len(parentPyutClasses) - 1: generatedCode = f'{generatedCode},' generatedCode = f'{generatedCode})' generatedCode = f'{generatedCode}:\n' generatedCode = f'{generatedCode}{self.__indentStr(PyutToPython.CLASS_COMMENTS_START)}\n' generatedCode = f'{generatedCode}{self.__indentStr(pyutClass.description)}\n' # TODO need to split lines according to MAX_WIDTH generatedCode = f'{generatedCode}{self.__indentStr(PyutToPython.CLASS_COMMENTS_END)}\n' return generatedCode
def _generatePyutClasses(self): for className in self._classNames(): pyutClass: PyutClass = PyutClass(name=className) pyutClass = self._addFields(pyutClass) for methodName in self._methodNames(className): pyutMethod: PyutMethod = PyutMethod(name=methodName) if methodName[0:2] == "__": pyutMethod.setVisibility(PyutVisibilityEnum.PRIVATE) elif methodName[0] == "_": pyutMethod.setVisibility(PyutVisibilityEnum.PROTECTED) else: pyutMethod.setVisibility(PyutVisibilityEnum.PUBLIC) pyutMethod = self._addParameters(pyutMethod) pyutMethod.sourceCode = self.visitor.methodCode[methodName] pyutClass.addMethod(pyutMethod) setterProperties: Parameters = self.visitor.setterProperties getterProperties: Parameters = self.visitor.getterProperties pyutClass = self._generatePropertiesAsMethods( pyutClass, getterProperties, setterProperties) if className in self.visitor.dataClassNames: self._createDataClassPropertiesAsFields( pyutClass, self.visitor.dataClassProperties) self._pyutClasses[className] = pyutClass self.logger.info(f'Generated {len(self._pyutClasses)} classes')
def _generatePyutClasses(self): for className in self._classNames(): pyutClass: PyutClass = PyutClass(name=className) pyutClass = self._addFields(pyutClass) for methodName in self._methodNames(className): pyutMethod: PyutMethod = PyutMethod(name=methodName) if methodName[0:2] == "__": pyutMethod.setVisibility(PyutVisibilityEnum.PRIVATE) elif methodName[0] == "_": pyutMethod.setVisibility(PyutVisibilityEnum.PROTECTED) else: pyutMethod.setVisibility(PyutVisibilityEnum.PUBLIC) pyutMethod = self._addParameters(pyutMethod) pyutMethod.sourceCode = self.visitor.methodCode[methodName] pyutClass.addMethod(pyutMethod) setterProperties: PyutPythonVisitor.Parameters = self.visitor.setterProperties getterProperties: PyutPythonVisitor.Parameters = self.visitor.getterProperties for propName in self.visitor.propertyNames: setterParams: List[str] = setterProperties[propName] getterParams: List[str] = getterProperties[propName] self.logger.info(f'Processing - {propName=} {setterParams=} {getterParams=}') setter, getter = self._createProperties(propName=propName, setterParams=setterParams) pyutClass.addMethod(setter) pyutClass.addMethod(getter) self._pyutClasses[className] = pyutClass self.logger.info(f'Generated {len(self._pyutClasses)} classes')
def _pyutClassToXml(self, pyutClass: PyutClass, xmlDoc: Document) -> Element: """ Exporting a PyutClass to a miniDom Element. Args: pyutClass: The pyut class to save xmlDoc: The xml document to update Returns: The new updated element """ root = xmlDoc.createElement(PyutXmlConstants.ELEMENT_MODEL_CLASS) classId: int = self._idFactory.getID(pyutClass) root.setAttribute(PyutXmlConstants.ATTR_ID, str(classId)) root.setAttribute(PyutXmlConstants.ATTR_NAME, pyutClass.name) stereotype = pyutClass.getStereotype() if stereotype is not None: root.setAttribute(PyutXmlConstants.ATTR_STEREOTYPE, stereotype.getStereotype()) root.setAttribute(PyutXmlConstants.ATTR_FILENAME, pyutClass.fileName) root = self._pyutClassCommonToXml(pyutClass, root) root.setAttribute(PyutXmlConstants.ATTR_SHOW_METHODS, str(pyutClass.showMethods)) root.setAttribute(PyutXmlConstants.ATTR_SHOW_FIELDS, str(pyutClass.showFields)) root.setAttribute(PyutXmlConstants.ATTR_SHOW_STEREOTYPE, str(pyutClass.getShowStereotype())) root.setAttribute(PyutXmlConstants.ATTR_DISPLAY_PARAMETERS, pyutClass.displayParameters.value) # methods for method in pyutClass.methods: root.appendChild(self._pyutMethodToXml(method, xmlDoc)) # fields for field in pyutClass.fields: root.appendChild(self._pyutFieldToXml(field, xmlDoc)) return root
def _PyutClass2xml(self, pyutClass: PyutClass, xmlDoc: Document): """ Exporting an PyutClass to an miniDom Element. Args: pyutClass: Class to save xmlDoc: xml Document instance Returns: XML Node """ root = xmlDoc.createElement('Class') # ID root.setAttribute('id', str(pyutClass.getId())) # class name root.setAttribute('name', pyutClass.getName()) # class stereotype stereotype = pyutClass.getStereotype() if stereotype is not None: root.setAttribute('stereotype', stereotype.getStereotype()) # description ([email protected]) root.setAttribute('description', pyutClass.description) # methods for method in pyutClass.methods: root.appendChild(self._PyutMethod2xml(method, xmlDoc)) # fields for field in pyutClass.fields: root.appendChild(self._PyutField2xml(field, xmlDoc)) # Append fathers self._appendFathers(pyutLinkedObject=pyutClass, root=root, xmlDoc=xmlDoc) # Append links self._appendLinks(pyutLinkedObject=pyutClass, root=root, xmlDoc=xmlDoc) return root
def _addFields(self, pyutClass: PyutClass) -> PyutClass: """ Can look like this: fieldData: x:int=0 fieldData = 0 Args: pyutClass: Where to add the fields Returns: The updated input class """ for fieldData in self.visitor.fields: self.logger.debug(f'fieldData: {fieldData}') pyutField: PyutField = self._parseFieldToPyut(fieldData) pyutClass.addField(pyutField) return pyutClass
def _pyutClassToXml(self, pyutClass: PyutClass) -> Element: """ Exporting a PyutClass to a miniDom Element Args: pyutClass: The Pyut class Returns: The XML element """ root = Element('Class') # class name root.setAttribute('name', pyutClass.getName()) # class stereotype stereotype = pyutClass.getStereotype() if stereotype is not None: root.setAttribute('stereotype', stereotype.getStereotype()) # methods methods for method in pyutClass.methods: root.appendChild(self._PyutMethod2xml(method)) # for all the field for field in pyutClass.fields: root.appendChild(self._PyutField2xml(field)) # for fathers fathers = pyutClass.getParents() if len(fathers) > 0: for i in fathers: father = Element('Father') father.setAttribute('name', i.getName()) root.appendChild(father) # for all links links = pyutClass.getLinks() for link in links: res = self._PyutLink2xml(link) if res is not None: root.appendChild(res) return root
def createNewClass(self, x, y): """ Add a new class at (x, y). @return PyutClass : the newly created PyutClass """ pyutClass: PyutClass = PyutClass(_("NoName")) oglClass: OglClass = OglClass(pyutClass) self.addShape(oglClass, x, y) self.Refresh() return pyutClass
def _createDataClassPropertiesAsFields( self, pyutClass: PyutClass, dataClassProperties: DataClassProperties) -> PyutClass: """ Args: pyutClass: The PyutClass to update dataClassProperties: The dataclass properties to parse Returns: Updated PyutClass with new fields """ className: str = pyutClass.name for dPropertyTuple in dataClassProperties: if dPropertyTuple[0] == className: pyutField: PyutField = self._parseFieldToPyut( fieldData=dPropertyTuple[1]) pyutClass.addField(pyutField) return pyutClass
def addHierarchy(self, display): """ Hardcoded example of a class diagram, for test purposes. Classes come from self introspection !!! OK, it's too big, but it's not a feature, just a toy. @author L. Burgbacher <*****@*****.**> @since 1.4 """ # BeginBusyCursor() from org.pyut.experimental.PythonMetaClassDataHandler import PythonMetaClassDataHandler cg: PythonMetaClassDataHandler = PythonMetaClassDataHandler() classes: List[type] = cg.getClassListFromNames(display) classNameToOglClass: Dict[str, OglClass] = {} # create the Pyut Class objects & associate Ogl graphical classes for cl in classes: # create objects pyutClassDef: PyutClass = PyutClass(cl.__name__) klassMethods: List[classmethod] = cg.getMethodsFromClass(cl) # add the methods methods: List[PyutMethod] = cg.generatePyutMethods(klassMethods) methods = sorted(methods, key=PyutMethod.getName) pyutClassDef.setMethods(methods) oglClassDef = self.addToDiagram(pyutClassDef) classNameToOglClass[cl.__name__] = oglClassDef # now, search for parent links for oglClassDef in classNameToOglClass.values(): pyutClassDef = oglClassDef.getPyutObject() # skip object, it has no parent if pyutClassDef.getName() == "object": continue parentNames = cg.getParentClassNames(classes, pyutClassDef) for parent in parentNames: dest = classNameToOglClass.get(parent) if dest is not None: # maybe we don't have the parent loaded self.createInheritanceLink(oglClassDef, dest) oglClassDefinitions: List[OglClass] = list( classNameToOglClass.values()) self.positionClassHierarchy(oglClassDefinitions)
def testCreateDataClassPropertiesAsFields(self): sampleDataClassProperties: DataClassProperties = [ DataClassProperty(('DataTestClass', 'w="A String"')), DataClassProperty(('DataTestClass', 'x:float=0.0')), DataClassProperty(('DataTestClass', 'y:float=42.0')), DataClassProperty(('DataTestClass', 'z:int')) ] pyutClass: PyutClass = PyutClass(name='DataTestClass') self.reverseEngineer._createDataClassPropertiesAsFields( pyutClass=pyutClass, dataClassProperties=sampleDataClassProperties)
def setUp(self): self.logger: Logger = TestIDFactory.clsLogger self.app: App = TestIDFactory.clsApp self._idFactory: IDFactory = IDFactory() self._pyutInterface: PyutInterface = PyutInterface() self._destinationAnchor: SelectAnchorPoint = SelectAnchorPoint( 250, 250, AttachmentPoint.NORTH) self._pyutClass: PyutClass = PyutClass(name='UnitTestClass')
def getOglClasses(self, xmlOglClasses: NodeList) -> OglClasses: """ Loads to OGL objects Parse the XML elements given and build data model for the Pyut classes. Args: xmlOglClasses: XML 'GraphicClass' elements Returns: The built dictionary uses an ID for the key and an OglClass for the value """ oglObjects: OglClasses = cast(OglClasses, {}) for xmlOglClass in xmlOglClasses: xmlOglClass: Element = cast(Element, xmlOglClass) pyutClass: PyutClass = PyutClass() height: float = float(xmlOglClass.getAttribute(PyutXmlConstants.ATTR_HEIGHT)) width: float = float(xmlOglClass.getAttribute(PyutXmlConstants.ATTR_WIDTH)) oglClass: OglClass = OglClass(pyutClass, width, height) xmlClass: Element = xmlOglClass.getElementsByTagName(PyutXmlConstants.ELEMENT_MODEL_CLASS)[0] pyutClass.setId(int(xmlClass.getAttribute(PyutXmlConstants.ATTR_ID))) pyutClass.setName(xmlClass.getAttribute(PyutXmlConstants.ATTR_NAME)) pyutClass.description = xmlClass.getAttribute(PyutXmlConstants.ATTR_DESCRIPTION) if xmlClass.hasAttribute(PyutXmlConstants.ATTR_STEREOTYPE): pyutClass.setStereotype(getPyutStereotype(xmlClass.getAttribute(PyutXmlConstants.ATTR_STEREOTYPE))) # adding display properties (cd) value = PyutUtils.secureBoolean(xmlClass.getAttribute(PyutXmlConstants.ATTR_SHOW_STEREOTYPE)) pyutClass.setShowStereotype(value) value = PyutUtils.secureBoolean(xmlClass.getAttribute(PyutXmlConstants.ATTR_SHOW_METHODS)) pyutClass.showMethods = value value = PyutUtils.secureBoolean(xmlClass.getAttribute(PyutXmlConstants.ATTR_SHOW_FIELDS)) pyutClass.showFields = value pyutClass.setFilename(xmlClass.getAttribute(PyutXmlConstants.ATTR_FILENAME)) pyutClass.methods = self._getMethods(xmlClass) pyutClass.fields = self._getFields(xmlClass) # Adding properties necessary to place shape on a diagram frame x = float(xmlOglClass.getAttribute(PyutXmlConstants.ATTR_X)) y = float(xmlOglClass.getAttribute(PyutXmlConstants.ATTR_Y)) oglClass.SetPosition(x, y) oglObjects[pyutClass.getId()] = oglClass return oglObjects
def _PyutClass2xml(self, pyutClass: PyutClass, xmlDoc: Document): """ Exporting an PyutClass to an miniDom Element. @param pyutClass : Class to save @param xmlDoc : xml document @return Element : XML Node """ root = xmlDoc.createElement('Class') # ID classId = self._idFactory.getID(pyutClass) root.setAttribute('id', str(classId)) # class name root.setAttribute('name', pyutClass.getName()) # class stereotype stereotype = pyutClass.getStereotype() if stereotype is not None: root.setAttribute('stereotype', stereotype.getStereotype()) root.setAttribute('description', pyutClass.description) root.setAttribute('filename', pyutClass.getFilename()) root.setAttribute('showMethods', str(pyutClass.showMethods)) root.setAttribute('showFields', str(pyutClass.showFields)) root.setAttribute('showStereotype', str(pyutClass.getShowStereotype())) # methods for method in pyutClass.methods: root.appendChild(self._PyutMethod2xml(method, xmlDoc)) # fields for field in pyutClass.fields: root.appendChild(self._PyutField2xml(field, xmlDoc)) return root
def _createNewClass(self) -> OglClass: """ Create a new class Returns: the newly created OglClass """ className: str = f'{self._prefs.className}{CreateOglClassCommand.clsCounter}' pyutClass: PyutClass = PyutClass(className) oglClass: OglClass = OglClass(pyutClass) CreateOglClassCommand.clsCounter += 1 return oglClass
def _generatePropertiesAsMethods(self, pyutClass: PyutClass, getterProperties, setterProperties) -> PyutClass: for propName in self.visitor.propertyNames: # Might be a read-only property try: setterParams: List[str] = setterProperties[propName] except KeyError: setterParams = [] getterParams: List[str] = getterProperties[propName] self.logger.info( f'Processing - {propName=} {setterParams=} {getterParams=}') setter, getter = self._createProperties(propName=propName, setterParams=setterParams) if setter is not None: setter.isProperty = True pyutClass.addMethod(setter) getter.isProperty = True pyutClass.addMethod(getter) return pyutClass
def _createNewClass(self) -> OglClass: """ Create a new class Returns: the newly created OglClass """ className: str = f'{self._preferences.className}{TestOglToMiniDomV10.clsCounter}' pyutClass: PyutClass = PyutClass(className) pyutClass.addMethod(self._generateAMethod()) pyutClass.fileName = '/Users/humberto.a.sanchez.ii/PycharmProjects/PyUt/src/UnitTest.py' oglClass: OglClass = OglClass(pyutClass) TestOglToMiniDomV10.clsCounter += 1 return oglClass
def __init__(self, pyutClass: PyutClass = None, w: float = DEFAULT_CLASS_WIDTH, h: float = DEFAULT_CLASS_HEIGHT): """ Args: pyutClass: a PyutClass object w: Width of the shape h: Height of the shape """ if pyutClass is None: pyutObject = PyutClass() else: pyutObject = pyutClass super().__init__(pyutObject, w, h) self.logger: Logger = getLogger(__name__) self._nameFont: Font = Font(DEFAULT_FONT_SIZE, FONTFAMILY_SWISS, FONTSTYLE_NORMAL, FONTWEIGHT_BOLD)
def _generateReadOnlyMethods(self): # Note the missing setter for fontSize getterProperties: Dict[str, List] = { 'fontSize': [''], 'verticalGap': [''] } setterProperties: Dict[str, List] = {'verticalGap': ['newValue']} pyutClass: PyutClass = PyutClass(name='NormalPropertiesClass') self.__setMockVisitorPropertyNames() pyutClass = self.reverseEngineer._generatePropertiesAsMethods( pyutClass=pyutClass, getterProperties=getterProperties, setterProperties=setterProperties) return pyutClass
def testSerialize(self): pyutClass: PyutClass = PyutClass(name='Implementor') implementor: OglClass = OglClass(pyutClass=pyutClass) attachmentAnchor: SelectAnchorPoint = SelectAnchorPoint( x=100, y=100, attachmentPoint=AttachmentPoint.NORTH) cOglXFaceCmd: CreateOglInterfaceCommand = CreateOglInterfaceCommand( implementor=implementor, attachmentAnchor=attachmentAnchor) # # Override the created OglInterface2 # oglInterface: OglInterface2 = cOglXFaceCmd._shape pyutInterface: PyutInterface = cOglXFaceCmd._pyutInterface floatMethod: PyutMethod = TestCommandCommon.createTestMethod( 'floatMethod', PyutVisibilityEnum.PRIVATE, PyutType('float')) intMethod: PyutMethod = TestCommandCommon.createTestMethod( 'intMethod', PyutVisibilityEnum.PROTECTED, PyutType('int')) pyutInterface.methods = [intMethod, floatMethod] oglInterface.pyutInterface = pyutInterface cOglXFaceCmd._shape = oglInterface serializedShape: str = cOglXFaceCmd.serialize() self.logger.debug(f'{serializedShape=}') self.assertIsNotNone(serializedShape, 'Something must come back') self.maxDiff = None self.logger.debug( f'{len(self._serializedCommand)=} {len(serializedShape)=}') import re fixedSerializedShape = re.sub('shapeId=[0-9]*', 'shapeId=2', serializedShape) self.logger.debug(f'{fixedSerializedShape=}') expectedValue: str = self._serializedCommand actualValue: str = fixedSerializedShape self.assertEqual(expectedValue, actualValue, 'Oops, something changed')
def getParentClassNames(self, classes, pyutClassDef: PyutClass) -> List[str]: import org.pyut.experimental.PyutDataClasses as pdc currentClass = pdc.__dict__.get(pyutClassDef.getName()) parentClasses = [ cl for cl in classes if cl.__name__ in map(lambda z: z.__name__, currentClass.__bases__) ] self.logger.debug(f'parentClasses: `{parentClasses}`') def getClassesNames(theList): return [item.__name__ for item in theList] parentNames: List[str] = getClassesNames(parentClasses) return parentNames
def getParentClassNames(self, classes: List[type], classDefinition: PyutClass) -> List[str]: from org.pyut.experimental import PyutModelClasses # I do not like 'magic' currentClass = PyutModelClasses.__dict__[classDefinition.getName()] parentClasses = [ cl for cl in classes if cl.__name__ in map(lambda z: z.__name__, currentClass.__bases__) ] self.logger.debug(f'parentClasses: `{parentClasses}`') def getClassesNames(theList): return [item.__name__ for item in theList] parentNames: List[str] = getClassesNames(parentClasses) return parentNames
def __addClass(self, className: str) -> OglClass: """ Add a class to the dictionary of classes Args: className: Name of the class to be added Returns: OglClass instance for the class """ # If the class name exists already, return the instance if className in self._classes: return self._classes[className] # Create the class pc: PyutClass = PyutClass(className) # A new PyutClass po: OglClass = OglClass(pc) # A new OglClass self._classes[className] = po return po
def _createEnumerationFields(self, pyutClass: PyutClass, enumValues: List[str]): """ TODO: Create a PyutEnumeration at some point For now simulate with a bunch of fields in a class that is `Stereotyped` as Enumeration """ pyutClass.setStereotype(stereotype=XSDParser.ENUMERATION_STEREOTYPE) pyutClass.setShowStereotype(theNewValue=True) for val in enumValues: pyutField: PyutField = PyutField( name=val.upper(), defaultValue=val, visibility=PyutVisibilityEnum.PUBLIC) pyutClass.addField(pyutField)
def createClasses(self, name: str, x: int, y: int) -> CreatedClassesType: """ Create a pair of classes (pyutClass and oglClass) Args: name: Class Name x: x-coordinate on the uml frame oglClass y: y coordinate on the uml frame oglClass Returns: A named tuple with attributes: pyutClass and oglClass """ pyutClass: PyutClass = PyutClass() pyutClass.setName(name) oglClass: OglClass = OglClass(pyutClass, 50, 50) # To make this code capable of being debugged oglClass.SetPosition(x=x, y=y) self.addShape(oglClass, x, y) createdClasses: CreatedClassesType = CreatedClassesType( pyutClass=pyutClass, oglClass=oglClass) return createdClasses