Home
View/Download - No Magic, Inc
Contents
1. override some visit methods Element it next accept myVisitor InheritanceVisitor InheritanceVisitor is an enhanced implementation of Visitor pattern and a subclass of Visitor used for visiting model elements and presentation elements Every visit method calls visit method for super type For example you can put some code into visitClassifier and it will be executed for all subclasses of a Classi fier Model elements visit methods has additional context parameter of type VisitorContext Visitor context is used to track what super type visit methods were already visited to avoid multiple visits because some model ele 46 Copyright 2003 2011 No Magic Inc A Changing UML model ments have multiple inheritance Open API users should not work with visitor context All tracking is done in InheritanceVisitor and Visitor classes Changing UML model SessionManager SessionManager is the singleton manager used for editing model Elements All modifications to model elements should be performed between createSession sessionName and closeSes sion method calls To edit some Element a session with this manager must be created After editing model element a session must be closed After that all changes will be applied to the model and registered in command history for undo redo as one command with a session name Only one session can be active The following code can be use
2. create new session SessionManager getInstance createSession Create and add diagram try class diagram is created and added to parent model element Diagram diagram ModelElementsManager getInstance createDiagram DiagramTypeConstants UML CLASS DIAGRAM parent open diagram project getDiagram diagram open catch ReadOnlyElementException e Changing UML model apply changes and add command into command history SessionManager getInstance closeSession Creating new Relationship object Model element is relationship if it implements one of the following interfaces Relationship ActivityEdge Transi tion ExceptionHandler Connector For checking if model element is relationship call ModelHelper isRelationship element method For getting supplier and client elements of relationship use ModelHelper getSupplierElement Model Helper getClientElement methods Use ModelHelper setSupplierElement ModelHelper setClientElement methods to set supplier and client elements of relationship Steps to create a new Relationship 1 Create a new relationship model element 2 Set client and supplier ModelElements by using ModelHelper setSupplierElement Model Helper setClientElement methods 3 Add new relationship into some parent by using ModelElementsManager addElement NEW Copying elements and symbols You can copy model elements and symbols either to another location in
3. Implementation of this method should return a map of classes derived from com nomagic uml2 ext magicdraw classes mdkernel Element class to collection s of com nomagic uml2 ext jmi smartlistener SmartListenerConfig objects Another way would be to extend com nomagic magicdraw validation DefaultValidation RuleImp1 class and override the following method Map lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt getListenerConfigurations NOTES In the Constraint Specification dialog box Constrained Element property should be specified Constrained element is element for which validation rule is created Validation rule that is interested in model class and interface names changes example public Map lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt getListenerConfigurations Map lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt configMap new HashMap lt Class lt extends Elements Collection lt SmartListenerConfig gt gt Collection lt SmartListenerConfig gt configs new ArrayList lt SmartListenerConfigs configs add SmartListenerConfig NAME CONFIG configMap put com nomagic uml2 ext magicdraw classes mdkernel Class class configs configMap put com nomagic uml2 ext magicdraw classes mdinterfaces Interface class configs return configMap NOTE In the Constraint Specification dialog box the Constrained Element proper
4. returns flag indicating if this diagram type will be creatable e getLargelcon returns a large icon for this type of the diagram see Chapter Adding New Functionality e getSmalllconURL returns a small icon URL for this type of the diagram see Chapter Adding New Functionality e getDiagramActions returns manager of actions used in the diagram e getDiagramToolbarConfigurator returns action manager configurator which configures described diagram toolbar see Chapter Adding New Functionality e getDiagramShortcutsConfigurator returns action manager configurator which configures described diagram shortcuts see Chapter Adding New Functionality e getDiagramContextConfigurator returns action manager configurator which configures described diagram context menu actions see Chapter Adding New Functionality Example 1 example diagram descriptor see OpenAPI examples for the full source code Kk p Descriptor of specific diagram nT class SpecificDiagramDescriptor extends DiagramDescriptor public static final String SPECIFIC DIAGRAM Specific Diagram Let this diagram type be a sub type of class diagram type public String getSuperType This is creatable diagram public boolean isCreatable Actions used in this diagram public MDActionsManager getDiagramActions Configurator for diagram toolbar
5. get stereotype Stereotype stereotype StereotypesHelper getStereotype project HyperlinkOwner apply stereotype StereotypesHelper addStereotype element stereotype add hyperlinks StereotypesHelper setStereotypePropertyValue element stereotype hyperlinkModel linkedElement true StereotypesHelper setStereotypePropertyValue element stereotype hyperlinkModel activeLinkedElement true String activeHttpLink http www magicdraw com StereotypesHelper setStereotypePropertyValue element stereotype hyperlinkText http www nomagic com true StereotypesHelper setStereotypePropertyValue element stereotype hyperlinkText activeHttpLink true add active hyperlink only one hyperlink can be active if modelActive StereotypesHelper setStereotypePropertyValue element stereotype hyperlinkModelActive activeLinkedElement false else StereotypesHelper setStereotypePropertyValue element stereotype hyperlinkTextActive activeHttpLink false PRESENTATION ELEMENTS Presentation Element UML semantic defines only UML metamodel MagicDraw application has its own structure of classes for UML elements representation in the diagram Base class of this structure is PresentationElement A presentation element is a textual or graphical presentation of one or more model elements In the metamodel a PresentationElement is the BaseElement that pre
6. Step 1 Creating a CodeEngineeringSet Project project Application getInstance getProject String name sample CE project String workingDir OPENAPI_ DATA DIRECTORY_PATH create working package ElementsFactory ef project getElementsFactory Package workingPackage ef createPackageInstance workingPackage setName my working package workingPackage setOwner project getModel creating code engineering set CodeEngineeringSet javaGenerationSet CodeEngineeringManager createCodeEngineeringSet CodeEngineeringConstants Languages JAVA null name project workingPackage workingDir Step 2 Adding model elements to the CodeEngineeringSet Project project Application getInstance getProject Samples of the forward and reverse engineering create new element ElementsFactory ef project getElementsFactory Class classA ef createClassInstance classA setName ClassA classA setOwner project getModel List lt BaseElement gt modelsForSample new ArrayList lt BaseElement gt modelsForSample add classA javaGenerationSet addElementsToCodeEngineeringSet modelsForSample Step 3 Performing CodeEngineeringSet generation CodeEngineeringManager generate javaGenerationSet Performing the reverse engineering This example shows how to perform simple java code reverse Step 1 Creating the CodeEngineeringSet Project project Application getInstance
7. Project can be imported if project s file name is known ProjectsManager projectsManager Application getInstance getProjectsManager File file new File projectFilePath create project descriptor ProjectDescriptor projectDescriptor ProjectDescriptorsFactory createProjectDescriptor file toURI projectsManager importProject projectDescriptor Example Loading teamwork project Project can be loaded if project s qualified name is known ProjectsManager projectsManager Application getInstance getProjectsManager create project descriptor ProjectDescriptor projectDescriptor TeamworkUtils getRemoteProjectDescriptorByQualifiedName remoteProjectQualifiedName if projectDescriptor null projectsManager loadProject projectDescriptor true Module management ProjectsManager also provides module management module usage export import reload and package shar ing methods Example Exporting local module Collection of project packages can be exported as module ProjectsManager projectsManager Application getInstance getProjectsManager File file new File moduleFilePath ProjectDescriptor projectDescriptor ProjectDescriptorsFactory createProjectDescriptor file toURI export collection of packages as module projectsManager exportModule project packages My local module projectDescriptor ProjectDescriptor Example Exporting teamwork module
8. Testing plug in Testing plug in 1 Restart MagicDraw On startup message should appear TT x My Plugin init e Another way to check plug in is to look at md og file This file is located in the lt User home directory gt magicdraw lt version gt directory Also all plugins and their status are listed in MagicDraw EnvironmentOptions Plugins tab After startup this file end should contain such information LOAD PLUGINS com nomagic magicdraw plugins PluginDescriptor edf730 id my first plugin name My First Plugin provider Coder version 1 0 class myplugin MyPlugin requires api 1 0 runtime Ljava net URL ff94b1 INIT PLUGINS com nomagic magicdraw plugins PluginDescriptor edf730 id my first plugin name My First Plugin provider Coder version 1 0 class myplugin MyPlugin requires api 1 0 runtime Ljava net URL ff94b1 TIP Looking at file is the best way to find problems when plug in does not work Detail information Plug in descriptor Plug in descriptor is a file written in XML and named plugin xml Each descriptor contains properties of one plug in Descriptor file should contain one plugin element definition In the table below you will find the structure of plugin xml 13 Copyright 2003 2011 No Magic Inc Detail information Element plugin requires api Description Name Description Attributes id Plug in ID should be unique Used to identify plug
9. the pattern is applied for How to create my own pattern param prop the pattern properties 7 public void applyPattern Target target AbstractPatternProperties prop throws ReadOnlyElementException PropertyManager propManager prop getPropertyManager String methodName propManager getProperty MyPatternProperties METHOD NAME getValue toString ElementsFactory ef Application getInstance getProject getElementsFactory Operation op ef createOperationInstance op setName methodName PatternHelper addDistinctOperation target getTargetClassifier op Step 4 Create Description html Every pattern may provide some html file with pattern description We will provide such Description htmI lt h2 gt MyPatern lt h2 gt lt h3 gt Intent lt h3 gt Add method into a classifier Description html file must be in the same package as MyPattern class Step 5 Create plug in Create class MyPatternPlugin package com nomagic magicdraw plugins impl examples mypatterns import com nomagic magicdraw plugins Plugin import com nomagic magicdraw plugins impl patterns impl common PatternPropertiesPanel import com nomagic magicdraw plugins impl patterns PatterniInfo import com nomagic magicdraw plugins impl patterns PatternsManager public class MyPatternPlugin extends Plugin Init this plugin Register MyPlugin in PluginsManager here public void init PatternsManager
10. Application getInstance getProject getElementsFactory Package packageA f createPackageInstance apply changes and add command into command history SessionManager getInstance closeSession Editing model element To edit some ModelElement a session with SessionManager must be created All changes in UML model will be registered and on session closing will be added into command history creating new session SessionManager getInstance createSession Edit class A if classA isEditable classA setName newName apply changes and add command into command history SessionManager getInstance closeSession It is programmer responsibility to ensure that modified model element is not read only To check if model ele ment is read only use Element isEditable method Adding new model element or moving it to another parent For adding new model Element into a model use addModelElement child parent method provided by Mod elElementsManager This manager can be used only if some session was created with SessionManager ElementsFactory f Application getInstance getProject getElementsFactory Class classA f createClassInstance Changing UML model create new session SessionManager getInstance createSession Add class into package try add class into package ModelElement sManager getInstance addElement classA package catch ReadOnlyElementException
11. Architecture Made Simple OPEN API version 17 0 1 user guide No Magic Inc 2011 All material contained herein is considered proprietary information owned by No Magic Inc and is not to be shared copied or reproduced by any means All information copyright 2003 2011 by No Magic Inc All Rights Reserved CONTENTS INTRODUCTION 8 PLUG INS 10 How plug ins work 10 Writing plug in 11 Testing plug in 13 Detail information 13 Plug in descriptor 13 Plug in classes 15 Plug In class loading 16 Important notes for Unix systems 17 Resource dependent plug in 17 Implementing ResourceDependentPlugin example 17 NEW MagicDraw Plugin Integration with Eclipse 18 Extending Eclipse Main Menu with Plugin Command 18 PLUGINS MIGRATION TO MAGICDRAW 15 0 AND LATER OPEN API 20 UML metamodel changes 20 UML specification changes 20 UML metamodel API implementation changes 20 Removed deprecated methods 21 Libraries jars changes 21 Package name change for build in plug ins 21 DISTRIBUTING RESOURCES 22 How to distribute resources 22 Creating required files and folders structure 22 Resource Manager descriptor file 28 JYTHON SCRIPTING 31 Creating script 31 Step 1 Create directory 31 Step 2 Write script descriptor 31 Step 3 Write script code 32 Variables passed to script 32 Jython 33 ADDING NEW FUNCTIONALITY 34 Invoking Actions 34 Creating a new action for MagicDraw 35 Step 1 Create new action class 35 Step 2 Specify ac
12. For more details about methods of this class see javadoc Abstract Pattern Every implementation of specific pattern must provide e Pattern properties e Pattern panels e Pattern implementation 68 Copyright 2003 2011 No Magic Inc PATTERNS Target concept This information is encapsulated in PatternInfo class PatternInfo is used only for pattern registration in the PatternsManager Other usages are internal and do not impact specific patterns Every pattern must provide main properties and optionally can have extended properties Main properties are used for user input from the first pattern wizard page Extended properties may be used for storing user input from other wizard pages Specific pattern must provide implementation of this abstract class and override AbstractPatternProperties con figurePropertyManager method If specific pattern has some extended properties it must override AbstractPat ternProperties configureExtendedPropertyManager method Both these methods must configure some property manager add or remove properties from it Every pattern must provide one or more panels for the patterns wizard First wizard page is always used for dis playing main pattern properties Other pages are optional and may be pattern specific AbstractPanelContainer class is used for providing the following information Specific pattern must provide pattern implementation class This class must extend AbsitractP
13. null public void actionPerformed ActionEvent e Tree tree getTree String text Selected elements for int i 0 i lt tree getSelectedNodes length i Node node tree getSelectedNodes i Object userObject node getUserObject if userObject instanceof BaseElement BaseElement element BaseElement userObject text n element getHumanName JOptionPane showMessageDialog MDDialogParent Provider getProvider getDialogParent Q text Creating a new action for MagicDraw Step 2 Specify action properties Property ID Name Shortcut and mnemonic Icon Description Function ID is a unique String for identifying action If action ID will be set to null new ID will be generated Action name can be used as ID All MagicDraw default actions IDs are defined in ActionsID class for more details see JavaDoc You can use these constants for accessing actions Do not use it as new actions ID Actions name will be visible in all GUI elements Every action can have assigned keyboard shortcut Shortcuts can be customized from the Environment Options dialog box see MagicDraw User Manual Section Environment Options NOTE Action must have some ID not null in other case shortcuts cannot be restored after restarting an application Every action can have a small and large icon Small icon is described as javax swing Action SMALL_ICON and can be used in menu item
14. presentationElement if presentationElement instanceof SlotView presentationElement instanceof SlotListElementView slot renderer return mSlotRenderer if presentationElement instanceof DependencyView dependency renderer return mDependencyRenderer if presentationElement instanceof PackageView package renderer return mPackageRenderer return null i Step 2 Registering RendererProvider PresentationElementRendererManager getInstance addProvider new RendererProvider DIAGRAM EVENTS NEW Diagram Listener Adapter MagicDraw provides an API to listen to all diagram changes in a single adapter which works in the following order 1 Receives events from all opened diagrams 2 Delegates these events to your own listener NOTE The adapter works in a project scope To listen to diagram change events you need to create the DiagramListenerAdapter object i e pass the prop erty change listener as a delegator which will receive all events To create the DiagramListenerAdapter object call new DiagramListenerAdapter propertyChangeListener The DiagramListenerAdapter object is registered for a project on its creation To start using the adapter install it Uninstall it when it is no longer necessary i e you do not need to receive any events about diagram changes anymore Example Listening to symbol creation removal DiagramListenerAdapter adapter new Diagra
15. public AMConfigurator getDiagramToolbarConfigurator Configurator for diagram shortcuts public AMConfigurator getDiagramShortcutsConfigurator return DiagramType UML_ CLASS DIAGRAM return true return SpecificDiagramActions ACTIONS return new SpecificDiagramToolbarConfigurator return new ClassDiagramShortcutsConfigurator Configurator for diagram context menu public DiagramContextAMConfigurator getDiagramContextConfigurator Id of the diagram type public String getDiagramTypeId Diagram type human name public String getSingularDiagramTypeHumanName Diagram type human name in plural form 7 public String getPluralDiagramTypeHumanName Large icon for diagram 7 public ImageIcon getLargeIcon return new ImageIconProxy new VectorImageIconControler getClass icons specificdiagram svg VectorImageIconControler SVG return new BaseDiagramContextAMConfigurator return SPECIFIC DIAGRAM return Specific Diagram return Specific Diagrams URL to small icon for diagram public URL getSmallIconURL return getClass getResource icons specificdiagram svg Step 2 Register new diagram type in the application The new diagram descriptor should be registered in MagicDraw using addNewDiagramType DiagramDescrip tor method of the Application This
16. 27 Copyright 2003 2011 No Magic Inc lt older gt gt Magici aw lt folder gt gt an E T lt lt folder gt gt defeuts T lt lt folder gt gt data A lt lt folderm gt diagame lt lt folder gt gt T lt folder gt gt QustomOagram gin 2 001_deseriptor mil lt ctoker gt gt plugins lt lt folder gt gt customPlugin Figure 7 Structure of directories and files that could be distributed through the Resource Manager Resource Manager descriptor file If you are planning to import and export your resources with the Resource Manager you should read this sec tion For importing resources to MagicDraw the resource manager descriptor file should be created In this sec tion you will find information about descriptor file naming location and a sample of this file For more information about importing resources with Resource Manager see MagicDraw UserManual pdf Resource Manager descriptor file naming The resource Manager descriptor file has specific naming See the structure of the name 28 Copyright 2003 2011 No Magic Inc MDR_ lt type gt _ lt plugin name gt _ lt plugin id gt _descriptor xml For example MDR_ Plugin CustomPlugin_ 3001 descriptor xml NOTE All spaces are replaced with the underscore symbo Resource Manager descriptor file location The file location is lt MagicDraw installation directory gt data resourcemanager Resource Manager descriptor file content
17. OCL2 0 Validation Rule OCL2 0 validation rule describes validation logic using OCL2 0 How to create OCL2 0 validation rule Create a constraint Set stereotype UML Standard Profile Validation Profile validationRule for the validation rule Set severity level error message and abbreviation Specify constrained element s Specify specification language OCL2 0 Enter OCL2 0 expression as a body of specification Add import the created validation rule to a validation suite NO oO FP WYN 107 Copyright 2003 2011 No Magic Inc Binary Validation Rule OCL2 0 validation rule can be used in an active validation suite In this case validation rule will be executed on any change of constrained elements that are from the validation scope Executing of the validation rule might be triggered even if no properties important to the validation rule actually changed and this can slow down active validating speed In order to avoid degradation of performance you can create a binary validation rule that uses OCL2 0 expression to validate model elements but also provides additional information for the MagicDraw that allows to optimize triggering of executing after model elements change E g we want to check whether all classes have names This can be done by creating OCL2 0 validation rule and specifying OLC2 0 expression name lt gt The problem is that such a validation rule actually is interested in a class property na
18. Only the diagrams of creat able type can be created instantiated Not creatable diagram serves as the base for other types of diagrams MagicDraw has 13 predefined types of diagrams 9 creatable and 4 not Creatable diagrams are e Class e Use Case e Communication e Sequence State Machine Protocol State Machine Activity Implementation Composite Structure Not creatable diagram e Interaction e Behavior e Any e Static Communication and Sequence diagrams are subdiagrams of the Interaction diagram Activity Interaction State Machine and Protocol State Machine diagram are subdiagram of the Behavior diagram NEW DIAGRAM TYPES Diagram Types hierarchy The only way to add a new diagram type in MagicDraw is to extend one of the already existing diagram types and register it This mechanism is described below Adding a new diagram type for MagicDraw Step 1 Override abstract DiagramDescriptor class Override abstract class DiagramDescriptor and implement abstract methods e getDiagramTypeld this method must return a diagram type id which is used to identify the diagram e getSingularDiagramTypeHumanName method returns diagram type human name e getPluralDiagramTypeHumanName method returns diagram type human name in plural form e getSuperType this method must return a super type Super diagram of this diagram type 77 Copyright 2003 2011 No Magic Inc e isCreatable
19. ProjectsManager projectsManager Application getInstance getProjectsManager SessionManager getInstance createSession Create shared package create package to share Package aPackage project getElementsFactory createPackageInstance aPackage setOwner project getModel aPackage setName myShare SessionManager getInstance closeSession share package projectsManager sharePackage project Arrays asList aPackage my module save project ProjectDescriptor projectDescriptor ProjectDescriptorsFactory getDescriptorForProject project projectsManager saveProject projectDescriptor true ProjectDescriptor NOTE ModuleDescriptor allows to access change some module properties like accessibility load mode Example Editing module within project ProjectsManager projectsManager Application getInstance getProjectsManager File file new File moduleFilePath ProjectDescriptor projectDescriptor ProjectDescriptorsFactory createProjectDescriptor file toURI find module ModuleDescriptor moduleDescriptor projectsManager findModule project projectDescriptor if moduleDescriptor null boolean editable moduleDescriptor isEditable if editable make module editable read write accessibility mode moduleDescriptor setEditable true get first shared module package MountInfo mountInfo MountInfo moduleDescriptor getMounts ite
20. and sample In this section you will see a basic sample of the Resource Manager descriptor file structure This sample rep resents a plug in distribution which also includes custom diagram profile template sample and documentation You can also distribute custom diagrams profiles templates or samples separately you only need to change the type value lt resourceDescriptor ecritical false date 2007 12 24 21 01 description My Plug in homePage http www magicdraw com id 3001 mdVersionMax higher mdVersionMin 15 0 name CustomPlugin type Plugin gt lt version human 1 0 beta internal 1 gt lt provider name No Magic gt lt edition gt Enterprise lt edition gt lt edition gt Architect lt edition gt lt edition gt Standard lt edition gt lt edition gt Professional Java lt edition gt lt edition gt Professional C lt edition gt lt edition gt Professional C lt edition gt lt edition gt Professional ArcStyler lt edition gt lt edition gt Reader lt edition gt lt edition gt Optimald lt edition gt lt installation gt lt file from data defaults data diagrams CustomDiagram descriptor xml to data defaults data diagrams CustomDiagram descriptor xml gt lt file from profiles CustomProfile xml zip to profiles CustomProfile xml zip gt lt file from templates CustomTemplate xml zip to templates CustomTemplate xml zip gt lt file from samples CustomPluginSampl
21. binary validation cases and will not be repeated in each case descrip tion See MyBinaryValidationRuleImp1l java example in lt MagicDraw install dir gt openapi exam ples validation directory NOTE the implementation class must be in the classpath of the MagicDraw application or if the imple mentation class is in a plugin then the plugin s classloader must be registered to the validation system see Binary validation rule in plugin Create Binary Validation Rule Case A If you want to control when validation rule has to be executed and you want to control what must be validated and how then you have to create Java class and implement interface com nomagic magicdraw valida tion ValidationRule The class must have public no arg constructor Value of implementation property of the validation rule must be qualified name of the implemented class This case is not recommended for validating model elements because validation rule provider must implement not only validating of model elements but also other details that are provided by MagicDraw validation engine In this case validation rule provider must correctly implement validating of model elements that are from valida tion scope defined in project options should take care that implementation would respect project property Exclude element from read only modules and is responsible for implementing when validation has to be exe cuted Create Binary Validation Rule Case B If you
22. configs add argumentConfig configMap put Activity class configs return configMap See JavaConstantNameValidationRuleImpl java example in lt MagicDraw_ install dir gt openapi examples validation directory Create Binary Validation Rule Case D If you want to create a validation rule that will not be used in active validation and you do not need to provide solving actions then you can create a Java class that contains static method with signature public static Boolean lt method_name gt lt Element_type gt param and specify lt qualifiedClassName gt lt method_name gt as a body value of validation rule s specification The referred java method must be a static method and it must take exactly one parameter Several validating methods can be placed into one Java class or use one class per validating method this is irrelevant The type of the parameter MUST match the type of the constrained element of the validation rule For validation rules on metaclasses use the appropriate class from the com nomagic uml2 ext magicdraw package For example to write the rule for metaclass DataType use com nomagic um12 ext magicdraw classes mdkernel DataType as a type of the parameter For the validation rules on stereotypes use the same class as you would use when specifying the validation rule for metaclass of that stereotype For validation rules on the classifiers of the model use the com nomagic uml2 ext magicdraw classes
23. e apply changes and add command into command history SessionManager getInstance closeSession If given model element cannot be added into a given parent legalArgumentException is thrown For example Operation cannot be added into Package or Operation cannot be added into not locked for editing Class in the teamwork project If element or parent is null egalArgumentException also is thrown If given element is not editable read only ReadOnlyElementException is thrown Alternative way to add new model element without using ModelElementsManager Element parent ElementsFactory f Application getInstance getProject getElementsFactory Class classA f createClassInstance create new session SessionManager getInstance createSession Add class into parent if parent canAdd classA apply changes and add command into command history SessionManager getInstance closeSession classA setOwner parent Removing model element Class classA create new session SessionManager getInstance createSession Remove class try remove class ModelElementsManager getInstance removeElement classA catch ReadOnlyElementException e apply changes and add command into command history SessionManager getInstance closeSession Alternative way to remove model element without using ModelElementsManager Class classA
24. element PropertyChangeEvent getOldValue will be null Listening to Property Change Events The PropertyChangeEvents support provides the ability to listen to the event by different scopes The scope depends on how the listener is registered e If the listener is registered at the whole repository it receives events about the changes in all the elements e If the listener is registered at the specific element it receives events about the changes in any property of this element e If the listener registered with the specific property at the element it receives events about the changes in this property e If the listener is registered with the specific property for the element type it receives events about the changes in all the elements of the specific type The PropertyChangeListener should be registered to receive these events There are several different ways to register a listener To listen for the whole repository use project getRepositoryListenerRegistry addPropertyChangeListener listener RefObject null This listener will get all the property change events from any element To listen for any delete operation in the repository and get notified before the delete action is performed use project getRepositoryListenerRegistry addPropertyChangeListener listener UML2MetamodelConstants BEFORE DELETE This listener will be notified when any model elemet is set to be deleted To list
25. for project correct load To become resource dependent plug in your plug in class must implement com nomagic magicdraw plu gins ResourceDependentPlugin interface Figure 1 on page 17 ResourceDependentPlugin tisPluginRequired project Project Boolean getPluginName String getPlugin ersion String Figure 1 Interface for resouce dependent plug in ResourceDependentPlugin has three special methods e boolean isPluginRequired Project project method is called on project save Plug in must return true if given project uses resources from plugin e String getPluginName method should return plugin name e String getPluginVersion method should return version of plugin Implementing ResourceDependentPlugin example public String getPluginName return getDescriptor getName public String getPluginVersion return getDescriptor getVersion public boolean isPluginRequired Project project Collection lt ModuleDescriptor gt collection project getMountTable getModules for ModuleDescriptor moduleDescriptor collection NEW MagicDraw Plugin Integration with Eclipse String projectName ProjectDescriptorsFactory getProjectName moduleDescriptor getURI if projectName null amp amp projectName equals my_ profile filename return false return true This plug in will be required for projects if project contains module my_profile_ filename Plug in
26. getInstance addPattern new PatterniInfo new MyPattern new PatternPropertiesPanel new MyPatternProperties Description html Close this plugin always return false always public boolean close return true How to create my own pattern see com nomagic magicdraw plugins Plugin isSupported public boolean isSupported return true Pattern must be registered in the PatternsManager with PatternsManager addPattern method Also we need to provide plugin xml for this plug in lt xml version 1 0 encoding UTF 8 gt lt plugin id mypatterns MyPattern name My Pattern version 1 0 provider name No Magic class com nomagic magicdraw plugins impl examples mypatterns MyPatternPlugin gt lt requires gt lt api version 1 0 gt lt required plugin id com nomagic magicdraw plugins impl patterns gt lt requires gt lt runtime gt lt library name mypatterns jar gt lt runtime gt lt plugin gt Compile all classes and bundle them into mypatterns jar file Also add Description html into this jar file Create subfolder mypatterns in the lt MagicDraw install gt plugins directory and copy mypatterns jar and plugin xml into it For more details how to deploy plug in see Plugins chapter PROPERTIES MagicDraw Open API provides a set of classes used as properties for diagrams symbols and design patterns Ever
27. getMetricB yAbbreviation abbreviation String Metric lt lt getter gt gt getMetricB yID id String Metric lt lt getter gt gt isDirty boolean lt lt setter gt gt setDirty is Dirty boolean void lt lt getter gt gt getSelected Metrics Collection lt lt getter gt gt getld String lt lt setter gt gt setld id String void l MetricsInformation lt lt cons tructor gt gt Metrics Inform ation calculate Metrics void lt lt getter gt gt getMetrics Suite MetricsSuite lt lt s etter gt gt setMetrics Suite metrics Suite Metrics Suite void lt lt getter gt gt getMetrics Results Metrics Results lt lt getter gt gt getMetrics Collection contains element BaseElement boolean Metric lt lt oonstructor gt gt Metric name String abbreviation String type MetricType id String metricValueType int calculate target BaseElement calculator Metrics Calculator MetricResult calculateLocalMetricValue target BaseElement MetricResult acceptModelElement element BaseHlement boolean round number float int addProperty property void addProperties properties Collection void removeProperties properties Collection void removeProperty property void lt lt getter gt gt getMetricsProperties Metrics Properties lt lt setter gt gt s etMetricsProperties metri
28. gt lt part id DIAGRAMS TREE gt lt part id EXTENSIONS TREE gt lt part id SEARCH RESULTS TREE gt lt part id DOCUMENTATION gt lt part id PROPERTIES gt lt part id MESSAGES WINDOW gt lt actionSetPartAssociation gt lt extension gt NOTE This is a general way of adding a command to the Eclipse main menu 3 Pack the command class with the Eclipse bundle descriptor to an Eclipse bundle jar file and save the file in lt MagicDraw installation directory gt plugins eclipse plugins 4 Integrate MagicDraw with Eclipse 5 Start Eclipse The new command will appear on the Eclipse main menu lt MagicDraw installation directory gt plugins eclipse plugins contains MagicDraw plugins that have commands to appear on the Eclipse main menu Their plugin xml files can be used as examples too PLUGINS MIGRATION TO MAGICDRAW 15 0 AND LATER OPEN API Open API in MagicDraw version 15 0 and later versions has changed together with changes in UML 2 1 2 2 2 specification You should read this chapter if you want to migrate your plugin created for earlier MagicDraw ver sion to MagicDraw version 15 0 and later UML specification introduced changes in UML metamodel so we are forced to make these changes in Open API too Also it was a good chance to make cleaner UML metamodel implementation API There are no big changes in Open API so migration will not be a long and complicate task for you UML metamodel ch
29. in by plug ins manager internals and by requirements of other plug ins Example my first plugin 0 name Plug in name No strict rules applied to this attribute Example Example plugin version Plug in version Version can be used to check other plug ins dependencies Allows numbers separated with one dot value provider name_ Plug in provider name Company or author name Example No Magic class Full qualified class name Class must be derived from com nomagic magicdraw plugins Plugin and stored in plug in runtime library This class will be loaded and ini tialized by plug ins manager Example myplugin MyPlugin ownClassload Optional default value false a Indicate if to use plugin own separate from other plu gins classloader All MagicDraw plugins are loaded by one classloader If there are plugins that can not be loaded by the same classloader conflicts plugin librar ies versions or etc their descriptors must define to use own classloaders class lookup Optional possible values LocalFirst GlobalFirst default value GlobalFirst Specifies priority of parent class loader if plugin is using own Classloader LocalFirst forces to load classes from plugin class loader even if such classes exists in MagicDraw core class path This option should be used if you want to use in your plugin different versions of some libraries used in core Nested elements requires M
30. instructions how to write your own plug ins create actions in the menus and toolbars change UML model elements and create new patterns The following chapters are included in this document e Plug Ins on page 10 e Plugins migration to MagicDraw 15 0 and later OPEN API on page 20 e Distributing Resources on page 22 e Jython Scripting on page 31 e Adding New Functionality on page 34 e UML Model on page 43 e Presentation Elements on page 55 e Symbols Rendering on page 62 e Diagram events on page 67 e Patterns on page 68 e Properties on page 74 e New Diagram Types on page 76 e Projects Management on page 81 e Project Options on page 86 e NEW Environment Options on page 88 e Event support on page 89 e Selections Management on page 94 e Creating Images on page 96 e Creating Metrics on page 97 e Configuring Element Specification on page 103 e Custom diagram painters on page 104 e Annotations on page 105 e Validation on page 106 e Teamwork on page 113 e Code Engineering on page 114 e Oracle DDL generation and customization on page 118 e Running MagicDraw in batch mode on page 126 In the generated JavaDoc you will find detailed descriptions of classes their attributes and operations Java Doc is located in lt MagicDraw installation directory gt openapi docs All MagicDraw OpenAP
31. layer Otherwise you need simple change import statement in your java source files For example import com nomagic um 2 omg kernel Element to import com nomagic uml2 ext magicdraw classes mdkernel Element UML metamodel intrefaces uses Java 5 generics so it is much easier to understand types of various collec tions in metamodel Removed deprecated methods Removed deprecated method Substitution BaseElement getProject Project getProject BaseElement MainFrame getDialogParent MDDialogParent Provider getProvider getDialogParent MainFrame setDialogParent Fram MDDialogParent Provider getProvider e setDialogParent Frame ElementListProperty setStereot ElementListProperty ype Stereotype setSelectableRestrictedElements Colle ction Libraries jars changes MagicDraw Open API classes are packaged into md_api jar and md_common_api jar was md jar and md_common ar lf your plugin was using API classes from some MagicDraw build in plugin plugin jar is also renamed with xxxx_api jar pattern Package name change for build in plug ins Some build in plugins in previous MagicDraw version exposed their Open API For exampe patterns transfor mations emf and etc We have changed package name pattern for build in plugins Previous API version used com nomagic magicdraw plugins impl pattern now these plugins are moved to com nomagic magicdraw For example com nomagic magicdraw patterns Simple import stateme
32. some predefined types in MetricType class that can be used MetricType class int 98 Copyright 2003 2011 No Magic Inc CREATING METRICS Adding new metrics to MagicDraw Adding new metrics to MagicDraw You have to create a Plugin for MagicDraw and make sure that your plugin descriptor file has in its requires section the following line lt required plugin id com nomagic magicdraw plugins impl metrics gt In your plugin class you must use then the MetricsManager addMetric Metric metric method to add the new metric to MagicDraw Now your metric will be available for using as any predefined metric 99 Copyright 2003 2011 No Magic Inc Full example source code Full example source code Plugin descriptor file lt xml version 1 0 encoding UTF 8 gt lt plugin id com nomagic magicdraw examples mymetrics name MyMetrics version 1 0 provider name No Magic class com nomagic magicdraw examples mymetrics MyMetricsPlugin gt lt requires gt lt api version 1 0 gt lt required plugin id com nomagic magicdraw metrics gt lt requires gt lt runtime gt lt library name mymetrics jar gt lt runtime gt lt plugin gt MyMetricsPlugin class public class MyMetricsPlugin extends Plugin public void init MyMetric myMetric new MyMetric MetricsManager getInstance addMetric myMetric public boolean close public boolean isSuppor
33. suite is a package with stereotype UML Standard Profile Validation Profile activeValida tionSuite Active validation rules can be checked constantly or on model elements change OCL2 0 or Binary validation rules can be used in the active validation We suggest to prefer binary because they give better per formance Annotation defines validation result It contains information about what is incorrect severity of the problem and possible actions that can be used to solve the problem Validation rule developer s roadmap Validation rule developer s roadmap Validation rule developer s roadmap allows faster understanding of steps required for creating a validation rule The validation rule is designed for active validation The validation rule is not designed for active validation Solution for problems found during validation is required W Solution for the problems found during validation will not be requir want to validate model elements Validation logic can expressed in OCL a Validation logic is complex performed formed Performance of the active validation is important Performance of the active validation is not important Create OCL validation rule Create binary Create binar validation rule validation rule Case C Case D Create binary validation rule Case B Create binary validation rule Case A Each case is described later in detail Create
34. the PropertyChangeE vent In order to understand which property has been changed and how it was done let s review a short explanation of the PropertyChangeEvent The main properties of the PropertyChangeE vent e Property name The changed property name e New value The changed property value e Old value The old property value which was before the property change PropertyChangeEvent getPropertyNamet String getNew Yalue Object getOldValue Object Figure 10 Class of the PropertyChangeEvent Property Names in MagicDraw All UML property names are stored in the com nomagic uml2 impl PropertyNames class Use this class when you need to listen for UML specific elements properties The com nomagic magicdraw uml ExtendedPropertyNames class has additional property names mostly dedicated for diagrams symbols Listening to Property Change Events The events names related with model creation deletion are listed in the com nomagic uml2 ext jmi UML2MetamodelConstants class An example of the element s name change event PropertyChangeEvent getPropertyName PropertyNames NAME PropertyChangeEvent getNewValue will be new name of element PropertyChangeEvent getOldValue will be name of element before change An example of the new element creation event PropertyChangeEvent getPropertyName UML2MetamodelConstants INSTANCE CREATED PropertyChangeEvent getNewValue will be new created
35. want to concentrate on implementation of validating model elements and delegate task of detecting model element chages and project property changes to active validation engine then you have to create Java class and implement com nomagic magicdraw validation ElementValidationRuleImp1 and inter face The class must have public no arg constructor Value of implementation property of the validation rule must be qualified name of the implemented class Create Binary Validation Rule Case C If the a validation rule is designed for active validation then validation performance becomes very important In this case we want that validation rule would be executed only then it is actually required so implementation of validation rule must somehow inform the active validation engine which model element property changes are important to the validation rule In order to create such a validation rule you have implement Create Binary Validation Rule Case C com nomagic magicdraw validation ElementValidationRuleImpl and com nomagic magicdraw validation SmartListenerConfigurationProvider interfaces The class must have public no arg constructor Value of implementation property of the validation rule must be qual ified name of the implemented class The com nomagic magicdraw validation SmartListenerConfigurationProvider interface defines a single method Map lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt getListenerConfigurations
36. 2003 2011 No Magic Inc CONTENTS Creating Custom Renderers 63 Registering Custom Symbol Renderer Provider 65 DIAGRAM EVENTS 67 NEW Diagram Listener Adapter 67 PATTERNS 68 Target concept 68 Using PatternHelper 68 Abstract Pattern 68 How to create my own pattern 70 Step 1 Create pattern properties class 70 Step 2 Create pattern panels class 71 Step 3 Create pattern class 71 Step 4 Create Description html 72 Step 5 Create plug in 72 PROPERTIES 74 NEW DIAGRAM TYPES 76 Diagram Types hierarchy 77 Adding a new diagram type for MagicDraw 77 PROJECTS MANAGEMENT 81 ProjectsManager 81 ProjectDescriptor 82 Project management 82 Module management 83 PROJECT OPTIONS 86 Adding Own Project Options 86 Retrieving Project Option Value 87 NEW ENVIRONMENT OPTIONS 88 Adding Custom Environment Options 88 EVENT SUPPORT 89 Property Change Events 89 Property Names in MagicDraw 89 Listening to Property Change Events 90 Listening to Related Elements in Hierarchy Events 91 Listening to Transaction Commit Events 91 Event Listening Sample 91 Element s Property Change Listening 91 TransactionCommitListener 92 5 Copyright 2003 2011 No Magic Inc CONTENTS SELECTIONS MANAGEMENT 94 Selection in diagrams 94 Selection in model browser 94 CREATING IMAGES 96 CREATING METRICS 97 Creating New Metric 97 Implementing calculateLocalMetricValue ModelElement target 97 Implementing acceptModelElement BaseElement elem
37. ChangeListener createSmartPropertyListener to create and register such lis tener for the particular element which will be notified with events provided by the SmartListenerConfig NOTE If the listener is not needed anymore unregister it using the remove PropertyChangeListener method Listening to Transaction Commit Events The TransactionCommitListener is a special listener which is notified when all changes inside a transaction are done and the transaction is closed Transaction Commit istener iransachonCommitedi propertyChangeEvents Coffection PropertyChangeEvent gt Runnable Figure 11 Interface of TransactionCommitListener The listener contains transactionCommited method which provides a collection of all Property ChangeEvents that were executed in a transaction Event Listening Sample Element s Property Change Listening These examples show how to create the property change listeners to listen to the different kind of properties Listener for listening to the specific element s any property changes Event Listening Sample element addPropertyChangeListener new PropertyChangeListener public void propertyChange PropertyChangeEvent evt evt getPropertyName is Changed Fes Listener for listening to the specifc property NAME of the specifc element element addPropertyChangeListener new PropertyChangeListener public void propertyChange PropertyChangeEv
38. Diagrams Pack ages or Model packages You may check if the element is eligible to be show using the method acceptElement BaseElement ele ment from MetricsManager class MetricsManager class also has a acceptDiagramElement BaseElement element that verifies if the given element is a diagram element Metric class Creating New Metric lt lt construcor gt Metric name String abbreviation String tye MetricType id String m aricValueT ype int calculate target BaseElem ent calculator MetricsC alculator MeticResut oalcu Rie LocalMericl alue target BaseEe ment MetricResult accepiMode Ele me nif element BaseElement boolean round num ber float int addP roperty property void addP roperties properties Collection void removxeP roperties properties Collection void remoxeP roperty property void lt lt getter gt isCounted target BaseElem ent boolean lt lt getter getMetricsP roperties MeticsProperties lt lt setter gt gt setMetricsP roperties metricP roperties MetricsP roperties void s lt lt getter getAbbrevation String lt lt setter gt setAbbrevation abbreviation String void s lt lt getter getD escription String lt lt setter setD escription desctiption String soid s lt getter geth am et String s lt setter setN amel name String wid lt lt getter gt getT yet MetricT ype s lt lt setter setLimits re
39. E supplierPE SessionManager getInstance closeSession The diagram is not passed into createPathElement method A new path element is created in the same diagram as client or supplier presentation elements Reshaping shape element To change bounds for the existing ShapeElement use method PresentationElementsManager reshapeShapeElement ShapeElement element Rectangle newBounds new Rectangle 100 100 80 50 SessionsManager getInstance createSession Test 58 Copyright 2003 2011 No Magic Inc Presentation Elements Manager PresentationsElementsManager getInstance reshapeShapeElement element newBounds SessionsManager getInstance closeSession Every shape element has a preferred size Shape size cannot be smaller than the preferred size If you will try to set smaller bounds these bounds will be increased to the preferred size If shape has Autosize property set to TRUE bounds will be reduced to the preferred size Changing path break points To change a break points list for the given path element use method PresentationElementsManager changeBreakPoints The same method must be used if you want to change client or supplier connection point The following code snippet shows how to do this PathElement element ArrayList points new ArrayList points add new Point 100 100 points add new Point 100 150 SessionsManager getInstance createSession Test Prese
40. For more information see javadoc of StereotypesHelper class Hyperlinks Hyperlinks are implemented using stereotypes and tag values Stereotype HyperlinkOwner and the following its properties tags hyperlinkText all simple hyperlinks hyperlinkTextActive active simple hyperlink hyperlinkModel all hyperlinks to model element hyperlinkModelActive active hyperlink to model element Example Retrieving hyperlinks get stereotype Stereotype stereotype StereotypesHelper getStereotype Project getProject element HyperlinkOwner get hyperlinked elements List modelValues StereotypesHelper getStereotypePropertyValue element stereotype hyperlinkModel for int i modelValues size 1 i gt 0 i active hyperlink Object activeLinkedElement StereotypesHelper getStereotypePropertyFirst element stereotype hyperlinkModelActive Element linkedElement Element modelValues get i get hyperlinked elements List textValues StereotypesHelper getStereotypePropertyValue element stereotype hyperlinkText for int i textValues size 1 i gt 0 i Working with Stereotypes and Tagged Values active hyperlink Object activeLink StereotypesHelper getStereotypePropertyFirst element stereotype hyperlinkTextActive String link String textValues get i Example Setting hyperlinks Project project Project getProject element
41. I classes are packaged in these jar files e lt MagicDraw installation directory gt lib md_api jar e lt MagicDraw installation directory gt lib md_common_api jar MagicDraw plugin s classes are packed in the concrete plugin s jar file s E g classes of Model Transformation plugin lt MagicDraw installation directory gt plugins com nomagic magicdraw modeltransformations modeltransformations_api jar Do not forget to add all jar files recursively except md_commontw jar and md_commontw_api jar from lt MagicDraw installation directory gt lib directory into your IDE classpath and make sure the patch jar is the first in the classpath We provide a set of plug ins samples in lt MagicDraw installation directory gt openapi examples directory Exam ples sometimes is the best way to find out how to use some Open API PLUG INS Plug ins are the only one way to change functionality of MagicDraw The main purpose of plug in architecture is to add new functionality to MagicDraw although there is a limited ability to remove existing functionality using plug ins Plug in must contain the following resources e Directory e Compiled java files packaged into jar file e Plug in descriptor file e Optional files used by plug in Typically plug in creates some GUI components allowing user to use plug in functionality Generally this is not necessary because plug in can listen for some changes in project and activate itself on desired change
42. MetricType REQUIREMENTS MetricType lt lt constructor gt gt VietricType type String description String lt lt getter gt gt getDescription String lt lt setier gt gt setDesciption description String void lt lt getter gt gt getType String lt lt setter gt gt setType type String void lt lt setter gt gt s etValue value int void MetricValue lt lt setter gt gt s etValue value float void mValue lt lt setter gt gt s etMinValue value MetricValue value2 MetricValue void lt lt setter gt gt s etMaxValue value MetricValue value2 MetricValue void INTEGER_ VALUE intffrozen REAL_ VALUE int frozen lt lt getter gt gt tisDifferentFromZero boolean lt lt getter gt gt getValue s Float float lt lt getter gt gt getValueAs Integer int hasValidResult boolean create value float MetricValue create value int MetricValue lt lt setter gt gt t s etCalculatedElements calculatedElements int void lt lt getter gt gt t getCalculatedElements int 02 Copyn 2003 2011 No I A V Ni fe sl ji gi C Inc CONFIGURING ELEMENT SPECIFICATION Adding Configuration Open API provides a way to configure Elements specification windows With your own configurator you can create new Nodes or remove already existing Nodes Node
43. P VIEW statement The following script will be generated DROP VIEW view name CASCADE CONSTRAINTS There are three steps to do this Step 1 Creating a new stereotype and tags We need to create a new stereotype with the Boolean property or extend the default View Stereotype with a new property Name a new property cascade_clause Apply the stereotype to the View object and set value to true We added a new tag to the view stereotype in the default profile Step 2 Changing the template file Add the following lines to the template file set ScascadeOption false this line is required to for setting new variable to false state set ScascadeOption SoracleHelper getBooleanValueFromDefaultProfile Sdata VIEW STEREOTYPE cascade_clause This line retrieves boolean value from the given tag in given stereotype view_stereotype and sets it to a newly created cascadeOption value Then add a new checking clause into the drop statement See the final method bellow macro dropView data Sets value to new variable set ScascadeOption SoracleHelper getBooleanValueFromDefaultProfile Sdata VIEW STEREOTYPE cascade clause writeLine DROP VIEW Sutils getQualifiedName data if S cascadeOption CASCADE CONSTRAINTS end semicolon nospace end RUNNING MAGICDRAW IN BATCH MODE MagicDraw plug ins allows adding some custom action into MagicDraw actions sets This approach works fine providing cus
44. Stereotypes and Tagged Values UML metamodel implementation itself does not provide a way to assign stereotypes and tags directly to Ele ments UML metamodel implementation in MagicDraw provides pretty complex mapping every UML Element can have an Instance of assigned Stereotypes It is stored as Element appliedStereotypelnstance property Slots of this instance are TaggedValues We provide a helper class StereotypesHelper for hiding this mapping complexity It has set of useful methods for assigning unassigning stereotypes and creating TaggedValues Keep in mind that TaggedValues in this helper class are called Slots StereotypesHelper hase a lot methods for working with stereotypes Example Creating stereotype applying to element and then setting tag ElementsFactory elementsFactory project getElementsFactory create profile Profile profile elementsFactory createProfileInstance profile setName myProfile ModelElementsManager getInstance addElement profile project getModel get metaclass Class com nomagic uml2 ext magicdraw classes mdkernel Class metaClass StereotypesHelper getMetaClassByName project Class create stereotype stereotypes will be applicable to classes Stereotype stereotype StereotypesHelper createStereotype profile myStereotype Arrays asList metaClass create tag definition Property property elementsFactory createPropertyInstance ModelElementsManag
45. TeamworkUtils class is used to export teamwork module TeamworkUtils exportTeamworkModule project packages My remote module remoteProjectQualifiedName Example Using module Local and teamwork module usage does not differs Just appropriate project descriptor must be used ProjectsManager projectsManager Application getInstance getProjectsManager File file new File moduleFilePath ProjectDescriptor projectDescriptor ProjectDescriptorsFactory createProjectDescriptor file toURI use module projectsManager useModule project projectDescriptor Example Importing module Local and teamwork module import does not differs Just appropriate project descriptor must be used ProjectsManager projectsManager Application getInstance getProjectsManager File file new File moduleFilePath ProjectDescriptor projectDescriptor ProjectDescriptorsFactory createProjectDescriptor file toURI projectsManager importModule project projectDescriptor Example Reloading module Local and teamwork module reload does not differs Just appropriate project descriptor must be used ProjectsManager projectsManager Application getInstance getProjectsManager File file new File moduleFilePath ProjectDescriptor projectDescriptor ProjectDescriptorsFactory createProjectDescriptor file toURI projectsManager reloadModule project projectDescriptor Example Package sharing
46. agicDraw API version required by plug in Plug ins and their versions required by plug in runtime Runtime libraries needed by plug in Nested elements api Required MagicDraw API version required Required plug in s to run plug in plugin Attributes version Required MagicDraw API version Example 1 0 Detail information Element required plugin runtime library help Description Attributes id ID of required plug in Example my first plugin 0 version Version of required plug in Example 1 1 Nested elements library Runtime library for running plug in Attributes name Name of the required library Example patterns jar Attributes i name Name of a compressed JavaHelp file JAR file TIP Adobe RoboHelp provides support for the Java Help format and automatically creates all Java based Help features and the HTML based features such as HTML content and hypertext links path Relative path to the JavaHelp file _ Plug in classes mDescriptor Plugin is the base abstract class for any MagicDraw plug in User written plug in must be extended from this class Every plug in has its own descriptor set by plug ins manager Plug in has two special methods 15 e public abstract void init method is called on MagicDraw startup Plug in must override this method and implement there its own functionality e public abstract boolean close method is call
47. anges There are two types of changes in UML metamodel API UML specification changes UML 2 1 2 2 2 specification intoduced few changes in UML metamodel itself Some metamodel classes were added some of them were removed some metaclasses properties were changed Most of these changes are not in core UML so they will affect you if your plugin is oriented to complex things in UML Most changes are made in UML Templates Simple Time Interactions We suggest to look at UML 2 1 2 2 2 specification for such changes if you see some compile errors UML metamodel API implementation changes Older UML metamodel API used several interfaces layers for every compatibility level described in UML speci fication All these layers were merged into one using package merge this is why old API had so many inter faces for every metamodel element in different package Such structure was very complicated and hardly understandable for new UML users MagicDraw version 15 0 and later UML metamodel API provides just one final merged layer All intermediate layers were dropped from API This change reduced UML metamodel API size few times Dropped interfaces are from packages e com nomagic uml2 ext omg e com nomagic uml2 magicdraw e com nomagic uml2 omg We left the same package name for merged interfaces like in previous API version com nomagic uml2 ext magicdraw You do not need to make any changes in your code if you was using interfaces from this
48. atiern and imple ment AbstractPattern applyPattern and AbstractPattern getCategorizedName methods 69 Copyright 2003 2011 No Magic Inc How to create my own pattern How to create my own pattern This chapter will give an example of a simple pattern for adding method into the target classifier The pattern will allow to edit method name in the Pattern Wizard Pattern will be added as a plug in into MagicDraw Step 1 Create pattern properties class MyPattern will have only two main properties for displaying not editable target classifier name and for entering the method name package com nomagic magicdraw plugins impl examples mypatterns import com nomagic magicdraw plugins impl patterns AbstractPatternProperties import com nomagic magicdraw properties StringProperty import com nomagic magicdraw properties PropertyManager public class MyPatternProperties extends AbstractPatternProperties public static final String TARGET CLASS TARGET CLASS public static final String METHOD NAME METHOD NAME Add two properties into main properties manager 7 protected void configurePropertyManager StringProperty p new StringProperty TARGET CLASS getTarget getTargetClassifier getName p setResourceProvider MyResourceProvider getInstance p setEditable false PropertyManager properties getPropertyManager properties addProperty p p new StringProperty METHOD NAME me
49. bols get i if o instanceof ShapeElement Rectangle bounds o getBounds bounds grow 5 5 Graphics2D g draw bounds Full running sample is provided in Open API examples with name CustomDiagramPainter ANNOTATIONS Using MagicDraw API you can add an annotation to any base element model element or symbol in a dia gram Annotations are shown in the Containment tree and in the diagrams Annotation has the following properties e severity like error warning info debug fatal e kind string representing annotation short name e text string representing annotation text e target target base element e actions optional list of actions They are shown in a diagram on a symbol s smart manipulator To add or remove annotations use com nomagic magicdraw annotation AnnotationManager IMPORTANT Do not forget to call AnnotationManager update when you are done with adding or removing in order to refresh MagicDraw UI TIP Find the sample plugin named annotations in MagicDraw Open API examples directory VALIDATION Basic conceps Validation rules and validation suites specify what will be validating and how They also specify how problem found by validation rule can be solved Validation rule is a constraint with applied stereotype UML Standard Profile Validation Profile valida tionRule Validation rules can validate model elements and non model elements e g presentation elements as we
50. cProperties Metrics Properties void lt lt getter gt gt getAbbrevation String lt lt setter gt gt s etAbbrevation abbreviation String void lt lt getter gt gt getDescription String lt lt setter gt gt s etDescription desaiption String wid lt lt getter gt gt getName String lt lt setter gt gt s etName name String void lt lt getter gt gt getType MetricType lt lt getter gt gt getPropertyintegerValue property String int lt lt getter gt gt getPropertyFloatValue property String float lt lt getter gt gt is Package element BaseElement boolean lt lt getter gt gt getlD String lt lt setter gt gt s etID id String void lt lt getter gt gt getPackageForElement element BaseElement BaseElement lt lt getter gt gt getMetricValueType int lt lt setter gt gt s etMetricValue Type metricValueType int void mType MetricType BASIC_TYPE MetricType MODEL SIZE MetricType RELATIONSHIPS MetricType DIAGRAWS MetricType CLASS EMPLOYMENT MetricType INHERITANCE MetricType COHESION MetricType CONPLEXITY MetricType MOOD MetricType MetricResult lt lt constructor gt gt HVetricRes ult value MetricValue addValue value MetricValue void lt lt getter gt gt getValue MetricValue lt lt setter gt gt s etValue value MetricValue void OTHER
51. class exists in MagicDraw classpath or if the validation rule implementation class is in plugin classpath then the plugin must register the plugin s classloader to validation system in this way EvaluationConfigurator getInstance registerBinaryImplementers lt PluginClassName gt class getClassLoader How to provide a solution for a problem found during validation Validation rule returns annotations as validation results to the validation engine Each annotation can contain a list of action objects that implements how a particular problem found by validation rule can be solved In order to create an action for solving validation rule s provider must create a Java class that extends com nomagic actions NMAction class and implement public void actionPerformed Action Event e method User will be able to invoke the action from the validation results table or from browser In order to enable performing the action on multiple targets the action class must implement com nomagic magicdraw annotation AnnotationAction interface See MyAction java FixJavaConstantNamesAction java MyBinaryValidationRuleImpl java and JavaConstantNameValidationRuleImpl java examples in lt MagicDraw_install_ dir gt openapi examples validation directory TEAMWORK MagicDraw API provides Teamwork Server accessing methods Code sniplet check logged user if user equals TeamworkUtils getLoggedUserName login to teamwork if TeamworkUt
52. classloader If value of this property is LocalFirst class is loaded from plugin classpath even if such class is already loaded in global MagicDraw core class loader This property is important if you want to use different version of the same classes libraries used in MagicDraw core Resource dependent plug in Important notes for Unix systems e By default plug in directory is placed in the MagicDraw installation directory global plug in directory For example if MagicDraw is installed in c MagicDrawUML plug in directory will be in c MagicDrawUML plugins On Unix systems plug ins manager additionally uses special directory in user home directory magicdraw lt version gt plugins for plug in loading For example for user Bob MagicDraw version 10 0 will use directory home bob magicdraw 10 0 plugins for searching plug in Even on Unix systems global plug in directory is used also This allows to have global and user plug ins e Another issue on Unix systems is related to permissions of a user to write If MagicDraw is installed by root user will not be allowed to write in a global plug in directory if a user has not such permissions Resource dependent plug in Starting with 16 6 version MagicDraw UML has new functionality to require loaded plug ins for particular proj ect This feature was created to avoid incorrect data load because of missing plug ins Every plug in can pro vide name and version of plug in to be required
53. create new session Changing UML model SessionManager getInstance createSession Remove class if classA isEditable apply changes and add command into command history SessionManager getInstance closeSession classA dispose NEW Refactoring model elements To refactor an element in a model use the Refactoring class Example 1 Converting an element to an interface Element elementToConvert SessionManager sessionManager SessionManager getInstance sessionManager createSession Convert Converts the element to an interface ConvertElementInfo info new ConvertElementInfo Interface class Preserves the old element ID for the new element info setPreserveElementID true Element conversionTarget Refactoring Converting convert elementToConvert info sessionManager closeSession Example 2 Replacing an element with another element Element elementToReplace SessionManager sessionManager SessionManager getInstance sessionManager createSession Replace ConvertElementInfo info new ConvertElementInfo elementToReplace getClassType info setConvertOnlyIncomingReferences true Refactoring Replacing replace element elementToReplace info sessionManager closeSession Creating Diagram Example how to create and add to parent element Project project Application getInstance getProject Namespace parent project getModel
54. criptor descriptor boolean silent NOTES Save and Load means Commit and Update for the Teamwork Project A project cannot be saved using descriptor if project isn t specified and a project cannot be loaded if file isn t specified In such cases IllegalStateException is thrown Silent mode means that during save or load process no GUI interruptions for user input will be used e g no Commit Project dialog box while committing a teamwork project or no Save dialog box while saving a new project project will be saved into the last used directory Example Saving active project ProjectsManager projectsManager Application getInstance getProjectsManager active project Project project projectsManager getActiveProject get project descriptor ProjectDescriptor ProjectDescriptor projectDescriptor ProjectDescriptorsFactory getDescriptorForProject project save project projectsManager saveProject projectDescriptor true Example Loading project from file Project can be loaded if project s file name is known ProjectsManager projectsManager Application getInstance getProjectsManager File file new File projectFilePath create project descriptor ProjectDescriptor projectDescriptor ProjectDescriptorsFactory createProjectDescriptor file toURI projectsManager loadProject projectDescriptor true Example Importing another MagicDraw project file
55. d for accessing checking and creating the session access singleton instance by using getInstance only one session can be active so check this if SessionManager getInstance isSessionCreated create new session SessionManager getInstance createSession If other session is already created and not closed createSession method throws Il legalStateException runtime exception ModelElementsManager ModelElementsManager is the singleton utility class for adding and removing model or moving them to other parents 47 Copyright 2003 2011 No Magic Inc Changing UML model Also it helps to create different types of diagrams This manager can be used only if some session was created with SessionManager ModelElementsManager performs additional checks before modification if element is not read only Also check if element can be added to parent is performed If ModelElementsManager is not used programmer must per form these checks in code explicitly Creating new model element For creation of model element instances use ElementsFactory class create lt model element type gt Instance method creates new model element instance To create model element a session with SessionManager must be created All changes in UML model be registered and on session closing will be added into command history creating new session SessionManager getInstance createSession Edit package A ElementsFactory f
56. dkernel Element Return Java lang String description CREATE or CREATE OR REPLACE e SoracleHelper getReturnParameter Soperation createIfNeeded Returns Return type parameter of given Operation Name Type Description Parameters Soperation com nomagic uml2 Operation to check ext magicdraw c lasses mdkernel BehavioralFeatur e ScreateIfNeeded boolean Flag to create return parameter if it is not exists Return com nomagic um12 Return parameter of given Opera ext magicdraw c tion lasses mdkernel Parameter e SoracleHelper getIndexNameDefinition index Returns Name of given Index Name Type Description Parameter Sindex com nomagic uml2 BehavioralFeature as a oracle ext magicdraw index to be checked for name classes mdkernel BehavioralFeatu re Utility class Return java lang String Name of infex e SoracleHelper getTableConstraintDefinition dependency Given a dependency returns table constraint definition Name Type Description Parameters dependency com nomagic uml2 Dependency to be tested ext magicdraw classes ddepende ncies Dependency Return java lang String Definition of table constraint e SoracleHelper isObject Package S element Checks if given element is a Package Name Type Description Parameter Selement com nomagic uml2 Element to be tested ext magicdraw classes mdkernel Element Return boolean true if element is Package e SoracleHelper isPac
57. e is stored in lt MagicDraw install folder gt data DB_engineering Oracle_template folder Template consists of many macros velocity functions Each macro is dedicated for particular object generation This example shows velocity macro for Oracle VIEW object generation macro generateView data set SQUERY_RESTICTION query restriction set Sforce false set S force SoracleHelper getBooleanValueFromDefaultProfile data SVIEW_STEREOTYPE SFORCE_ TAG Customizing template set Ssqlrestriction false set Ssqlrestriction oracleHelper getFirstPropertyValueFromProfile data VIEW_ STEREOTYPE SQUERY RESTICTION set sql false set sql oracleHelper getFirstPropertyValueFromProfile Sdata S VIEW_ STEREOTYPE SQUERY TAG set Scolumns false set Scolumns oracleHelper getViewColumnList data if Scolumns set S columns columns else set Scolumns S nospace end writeDocumentation data nospace writeLine oracleHelper getCreate S data if oracleHelper getPropertiesListFromDefaultProfile data SVIEW_ STEREOTYPE SFORCE TAG size gt 0 if force FORCE else NO FORCE end end VIEW oracleHelper getQualifiedName data columns AS Snospace if sql writeLine sql Stab end writeText sqlrestriction space nospace semicolon end Model element with stereotype view is passed to macro function and then all eleme
58. e mdzip to samples CustomPluginSample mdzip gt lt file from manual CustomPluginManual pdf to manual CustomPluginManual pdf gt lt file from plugins customPlugin to plugins customPlugin gt lt file from data resourcemanager MDR_ Plugin CustomPlugin 3001 descriptor xml to data resourcemanager MDR_Plugin_CustomPlugin_3001 descriptor xml gt lt installation gt lt resourceDescriptor gt See the terms used in the sample description in the table below Element id name type version internal version human edition installation Description Unique plug in id id is used to form a descriptor file name To prevent duplicates use a number starting from 3000 Plug in name Name is used to form a descriptor file name Plug in name must be unique between all MagicDraw resources Type may be one of the following types Custom Diagram Plugin Profile Sample Template version internal is an invisible resource number This version number is not visible to the user and may be used for an internal count version internal may only be a number Human readable version number of the resource This version number is visible to users version human number may use numbers and or words Supported MagicDraw editions installation includes files which will be copied from the custom plug in archive to the MagicDraw folder IMPORTANT Do not use If file name includes when
59. ed on MagicDraw shutdown Plug in must override this method and return to true if plug in is ready to shutdown or false in other case If plug in returns false MagicDraw shutdown will be canceled e public abstract boolean isSupported method is called before plug in init If this method returns false plugin will not be initialized isSupported may be used to check if plugin can be started for example on this OS Copyright 2003 2011 No Magic Inc Detail information PluginDescriptor is the class that provides information loaded from plugin xmI file plug in descriptor to plug in Detail information about these classes can be found in javadoc Plugins Manager MagicDraw Startup 1 for all plugins 2 create descriptor PuginDescriptor 3 create plugin Plugin 4 setDescriptor descriptor 5 for all plugins 6 init MagicDraw Shutdown 7 for all plugins 8 result 9 result cancel shutdown Plug In class loading All MagicDraw plug ins classes and runtime libraries are loaded by one classloader If there are plugins that can not be loaded by the same classloader conflicts plugin libraries versions or etc their descriptors should be defined to use own classloaders In this case the plug in classes are loaded by separate classloader Optional property class lookup controls how classes are loaded if plugin has its own
60. en container properties are modified 44 Copyright 2003 2011 No Magic Inc Collecting all children from all hierarchy levels Containers implement subsets and unions constraints from UML metamodel specification This explains how modification of one container can affect other containers Make sure you understand subsets and unions in UML metamodel Some containers are read only This is true for all DERIVED UML metamodel properties For example Ele ment getOwnedElement is read only If you want to add some inner Element you need to add it into subset of ownedElement for example for Package getOwnedPackageMember It is enough to set one UML meta association property value and opposite property will be setted too For example Class adding into Package can be done in two ways Class myclass Package myPackage myClass setOwner myPackage or myPackage getOwnedPackageMember add myClass Accessing elements in container properties Example retrieving child model elements Element el if el hasOwnedElement for Iterator it el getOwnedElement iterator it hasNext Element ownedElement Element it next NOTE get lt property name gt method call for empty container property instantiates empty collection This leads to increased memory usage So before iterating check if container property is not empty with method has lt property name gt Adding elements in
61. en for any property changes of the specific element use element addPropertyChangeListener listener This listener will be notified when any element property is changed To listen for any property changes of the specific element type use project getSmartEventSupport registerConfig aClass configs listener Listening to Transaction Commit Events This listener will be notified when any property of any element in the project with this type is changed If con figs is NULL the listener will get all property change events NOTE EventSupport could be disabled from event firing To check if it is enabled use project getRepository getEventSupport isEnableEv ent Firing To stop start event firing use project getRepository getEventSupport setEnableE ventFiring Listening to Related Elements in Hierarchy Events There is a posibility to listen for changes of the elements which are somehow related with the given element For example we want to be notified when element s owner name is changed The SmartPropertyChangeLis tener class is dedicated for the situations like this The main idea of the solution is to provide the SmartLis tenerConfig which will provide the chain of the property names to listen to The SmartListenerConfig class provides static methods for default configuration of property chains This is useful when listening for common property change events Use the SmartProperty
62. en stereotype from profile Name Type Description Parameters Selement com nomagic uml2 Element to be tested ext magicdraw c lasses mdkernel Element SprofileName java lang String Profile name where stereotype exists stereotypeName java lang String Stereotype name SpropertyName java lang String Property Tag name which value will be checked Return java lang String First value in property list in String e SoracleHelper getPropertiesListFromProfile Selement profileName SstereotypeName SpropertyName Returns list of given property values that exists on given element with applied stereotype from given profile Name Type Description Utility class Parameters Selement com nomagic uml2 Element to be tested ext magicdraw c lasses mdkernel Element SprofileName java lang String Profile name where stereotype exists stereotypeName java lang String Stereotype name SpropertyName java lang String Property Tag name which value will be checked Return java util List List of property values e SoracleHelper getStringValue Sobject Given an value from Tag returns String representation Name Type Description Parameter Selement com nomagic uml2 Element to be tested ext magicdraw c lasses mdkernel Element Return boolean true if element is the datatype e SoracleHelper isDataType S element Returns true if element is data type Name Type Description Parameter Selement com nomagic um
63. ened before doing layout 56 Copyright 2003 2011 No Magic Inc Shapes are presentation elements created for such model elements as classes packages models subsystems and others Paths Paths are presentation elements created for such model elements as Relationships Path has the following attributes e Supplier the presentation element of Relationship supplier Use method PathElement getSupplier to access this element e Client the presentation element of Relationship client Use method PathElement getClient to access this element e Supplier point the connection point of path and supplier element Use method_ PathElement getSupplierPoint to access this point e Client point the connection point of path and client element Use method PathElement getClientPoint to access this point e Break points a list of path breaking points between supplier and client points This list can be empty if path is straight Use method PathElement getBreakPoints to access this list Presentation Elements Manager Presentation elements classes provides just getters for properties You need to use PresentationElementsManager if you want to change the properties attributes of the presentation element The same manager is used for creating presentation elements and adding them into diagrams PresentationElementsManager can be used only inside the created session with SessionsManager If session is not created IllegalSta
64. ent 97 Constructor 98 Adding new metrics to MagicDraw 99 Full example source code 100 Plugin descriptor file 100 MyMetricsPlugin class 100 MyMetric class 100 Metric framework structure 102 CONFIGURING ELEMENT SPECIFICATION 103 Adding Configuration 103 CUSTOM DIAGRAM PAINTERS 104 ANNOTATIONS 105 VALIDATION 106 Basic conceps 106 Validation rule developer s roadmap 107 Create OCL2 0 Validation Rule 107 Binary Validation Rule 108 Create Binary Validation Rule Case A 109 Create Binary Validation Rule Case B 109 Create Binary Validation Rule Case C 109 Create Binary Validation Rule Case D 111 Binary validation rule in plugin 112 How to provide a solution for a problem found during validation 112 TEAMWORK 113 CODE ENGINEERING 114 Code Engineering Set 114 Forward Engineering 114 Reverse Engineering 115 Managing code engineering sets 115 Language specific options 116 Samples of the forward and reverse engineering 116 6 Copyright 2003 2011 No Magic Inc CONTENTS Performing the forward engineering 116 Performing the reverse engineering 117 ORACLE DDL GENERATION AND CUSTOMIZATION 118 Introduction to Oracle DDL generation in MagicDraw 118 Understanding Oracle DDL Template structure 118 Customizing template 119 Utility class 120 Example 125 RUNNING MAGICDRAW IN BATCH MODE 126 7 Copyright 2003 2011 No Magic Inc INTRODUCTION This document describes MagicDraw Open Java API and provides
65. ent evt if PropertyNames NAME equals evt getPropertyName name is Changed D Listener for listening the specifc property NAME of the specific element type Classifier create smartListenerConfig for Name property SmartListenerConfig cfg new SmartListenerConfig PropertyNames NAME List lt SmartListenerConfig gt configs Collections singletonList cfg create listener which will get notified of events PropertyChangeListener listener new PropertyChangeListener public void propertyChange PropertyChangeEvent evt evt getPropertyName is Changed he register everything into project s event support project getSmartEventSupport registerConfig Classifier class configs listener TransactionCommitListener This example shows how to create a transaction commit listener Create a custom transaction commit listener public class MyTransactionListener implements TransactionCommitListener public Runnable transactionCommited final Collection lt PropertyChangeEvent gt events return new Runnable public void run for PropertyChangeEvent event events if UML2MetamodelConstants INSTANCE CREATED equals event getPropertyName Object source event getSource if source instanceof Property Property property Property source Element owner property getOwner if owner instanceof Classifier Event Listening Sample Cla
66. entationElement PresentationElementColorEnum colorEnum if PresentationElementColorEnum FILL equals colorEnum color to fill Element element presentationElement getElement if element instanceof com nomagic uml2 ext magicdraw classes mdkernel Package amp amp com nomagic uml2 ext magicdraw classes mdkernel Package element hasOwnedElement package has no elements use green color to fill return Color GREEN return super getColor presentationElement colorEnum 63 Copyright 2003 2011 No Magic Inc Custom Renderers Sample The custom slot renderer used in instance specification symbol the slot values are rounded class SlotRenderer extends ShapeRenderer public String getText PresentationElement presentationElement PresentationElementTextEnum textEnum if PresentationElementTextEnum NAME equals textEnum the slot text is shown as name Element element presentationElement getElement if element instanceof Slot Slot slot Slot element if slot hasValue String string List lt ValueSpecification gt values slot getValue for ValueSpecification value values if value instanceof LiteralString LiteralString literalString LiteralString value if string length gt 0 String literalValue string literalString getValue Cry round value double doubleValue Double parseDoub
67. er gt MagicDraw lt lt file gt gt descriptor xml lt lt file gt gt MDR_CustomDiagram_CustomPlugin_3001_deseriptor xml D Figure 2 Folders and files structure required for custom diagram distribution For more information about creating new diagram types see the section New Diagram Types on page 76 or see the UML Profiling and DSL UserGuide pdf custom diagrams creation Distributing Profiles Files for profile distribution are as follows e CustomProfile xml zip required e CustomProfile htm You may choose any name for these files lt lt folder gt MagicDraw Ci gt D ofile xml zip safolder gt lt folder gt resourcemanager Figure 3 Folders and files structure required for profile distribution amp 8file gt gt Custom Plugin_3001_descriptor xml For more information about working with Profiles see MagicDraw UserManual pdf and UML Profiling and DSL UserGuide pdf Distributing Templates Files for template distribution are as follows 24 e CustomTemplate xmi zip required e CustomTemplate html Copyright 2003 2011 No Magic Inc DISTRIBUTING RESOURCES e description html lt folder gt MagicDraw CustomTemplate lt folder gt data lt lt folder gt resourcemanager Figure 4 Folders and files structure required for template distribution 25 Copyright 2003 2011 No Magic Inc Dist
68. er getInstance addElement property stereotype tag name property setName myTag tag type is String Classifier typeString ModelHelper findDataTypeFor project String property setType typeString if StereotypesHelper canApplyStereotype element stereotype apply stereotype StereotypesHelper addStereotype element stereotype set tag value StereotypesHelper setStereotypePropertyValue element stereotype myTag myTagValue Example Retrieving tag values find profile Working with Stereotypes and Tagged Values Profile profile StereotypesHelper getProfile project myProfile find stereotype Stereotype stereotype StereotypesHelper getStereotype project myStereotype profile get stereotyped elements List stereotypedElements StereotypesHelper getExtendedElements stereotype for int i stereotypedElements size 1 i gt 0 i stereotyped element Element element Element stereotypedElements get i if stereotype hasOwnedAttribute get tags stereotype attributes List lt Property gt attributes stereotype getOwnedAttribute for int j 0 j lt attributes size j Property tagDef attributes get j get tag value List value StereotypesHelper getStereotypePropertyValue element stereotype tagDef getName for int k 0 k lt value size k tag value Object tagValue Object value get j
69. etMetrics SuiteB yID id String MetricsSuite contains metrics SuitelD String boolean calculate info MetricsInform ation MetricsResults lt lt s etter gt gt setMetrics SuiteC ontainer container MetricsSuiteContainer void lt lt getter gt gt getMetrics InformationSession project Project Metrics Information MetricsCalculator lt lt cons tructor gt gt Metrics C alculator metrics Information MetricsInform ation calculate MetricsRes ults calculate element BaseElement metric Metric MetricResult lt lt cons tructor gt gt MetricsSuite lt lt getter gt gt isSelected metric Metric boolean selectMetric metric Metric void unselectMetric metric Metric void selectMetric id String void unselectMetric id String void addMetric metric Metric void rem oveMetric id String void rem ove Metric metric Metric void lt lt getter gt gt getDescription String lt lt setter gt gt setDescription description String void lt lt getter gt gt getNam e String lt lt setter gt gt t setNam e name String void lt lt getter gt gt getMetrics Collection addMetrics metrics Collection addClone boolean wid rem oveAllMetrics void update source Metrics Suite Metrics Suite updateName boolea lt lt getter gt gt getMetricByName name String Metric lt lt getter gt gt
70. getProject String name sample CE project String workingDir OPENAPI_ DATA DIRECTORY _PATH e g C myworkingPackage create working package ElementsFactory ef project getElementsFactory Package workingPackage ef createPackageInstance workingPackage setName my working package workingPackage setOwner project getModel creating code engineering set CodeEngineeringSet set CodeEngineeringManager createCodeEngineeringSet CodeEngineeringConstants Languages JAVA null name project workingPackage workingDir Here null dialect is used for java language because java doesn t have any dialect Step 2 Adding source code to the CodeEngineeringSet ces addAllFilesRecursivelyToCES new File workingDir File separator test directory starting from C myworkingPackage test directory This sets given instance of code engineering set working directory and adds all files from that directory Set java classpaths for project String claspath new String pathl path2 path3 path4 JavaCodeEngineeringManager setJavaClasspath mTestProject2 project Step 3 Performing reverse of the CodeEngineeringSet CodeEngineeringManager reverse ces false ORACLE DDL GENERATION AND CUSTOMIZATION MagicDraw Oracle DDL script generation is based on the Velocity engine It provides ability to change gener ated DDL script by changing velocity template In this chapter we will introduce how O
71. if does not exist property new StringProperty TEST PROPERTY _ID description group property setGroup MY_GROUP custom resource provider property setResourceProvider new PropertyResourceProvider public String getString String string Property property if TEST PROPERTY _ID equals string translate ID return Test Property if TEST PROPERTY _ID_ DESCRIPTION equals string translate description return Test Property in My Group if MY _ GROUP equals string translate group return My Group return string add property projectOptions addProperty ProjectOptions PROJECT GENERAL PROPERTIES property pD Retrieving Project Option Value Retrieving Project Option Value The following example shows how to access project option s value Property property project getOptions getProperty ProjectOptions PROJECT GENERAL PROPERTIES TEST PROPERTY ID if property null Object value property getValue 87 Copyright 2003 2011 No Magic Inc NEW ENVIRONMENT OPTIONS Adding Custom Environment Options Application related options are referred to as environment options They are saved in the g obal opt file that is located in lt user home directory gt magicdraw lt version number gt data You can add custom environment options for MagicDraw To add your own environment options 1 Extend the Abst
72. igurator configurator Example Add new configurator for CONTAINMENT _BROWSER_CONTEXT configuration see examples above how to create configurator for browser actions add configurator into ActionsConfiguratorsManager ActionsConfiguratorsManager getInstance addContainmentBrowserContextConfigurator brCfg ADDING NEW FUNCTIONALITY Actions hierarchy Actions hierarchy 41 Copyright 2003 2011 No Magic Inc Actions hierarchy Predefined actions configurations MAIN_MENU MAIN_TOOLBAR MAIN_SHORTCUTS CUSTOMIZABLE_SHORTCUTS CONTAINMENT_BROWSER_CONTEXT CONTAINMENT_BROWSER_SHORTCUTS CONTAINMENT_BROWSER_TOOLBAR INHERITANCE_BROWSER_CONTEXT INHERITANCE_BROWSER_SHORTCUTS INHERITANCE_BROWSER_TOOLBAR DIAGRAMS_BROWSER_SHORTCUTS DIAGRAMS_BROWSER_TOOLBAR EXTENSIONS_BROWSER_CONTEXT EXTENSIONS_BROWSER_SHORTCUTS EXTENSIONS_BROWSER_TOOLBAR SEARCH_BROWSER_CONTEXT SEARCH_BROWSER_SHORTCUTS SEARCH_BROWSER_TOOLBAR NEW Selecting elements via element Selection dialog Use ElementSelectionDlgFactory create methods to create element selection dialog Frame dialogParent MDDialogParentProvider getProvider getDialogParent ElementSelectionDlg dlg ElementSelectionDlgFactory create dialogParent Use ElementSelectionDlgFactory initSingle methods to initialize the dialog with single element selection mode ElementSelectionDlgFactory initSingle Use ElementSelectionDlgFactory initMultip
73. ils login server 1 user password login failed return load teamwork project ProjectDescriptor projectDescriptor TeamworkUtils getRemoteProjectDescriptorByQualifiedName projectName ProjectsManager projectsManager Application getInstance get ProjectsManager projectsManager loadProject projectDescriptor true Project project Application getInstance getProject Model model project getModel get locked by user Collection userLockedElements TeamworkUtils getLockedElement project user if userLockedElements contains model1 model is not locked by user get all locked Collection allLockedElements TeamworkUtils getLockedElement project null if allLockedElements contains model model is not locked lock TeamworkUtils lockElement project model false SessionManager getInstance createSession Rename Model change name model setName MyModel SessionManager getInstance closeSession unlcok and commit because do not discard TeamworkUtils unlockElement project model false false projectsManager closeProject logout TeamworkUtils logout Check the com nomagic magicdraw teamwork application TeamworkUtils class JavaDoc for method descrip tions CODE ENGINEERING Since MagicDraw 16 0 you can perform Code Engineering using OpenAPI Code engineering allows generation of source code from specific model and sou
74. info setDepthLimit 3 PresentationElement view A symbol for which you need to invoke the displaying related symbols action DisplayRelatedSymbols displayRelatedSymbols view info sessionManager closeSession SYMBOLS RENDERING The custom symbol rendering API allows modifying the default symbol view This API includes 1 Renderer provider API which allows to provide a custom renderer for the specific symbol 2 Renderers which can modify the default symbol appearance In this chapter we will review how to register the specific symbol views provider and give the example covering the custom renderers for the package slots and dependency link symbols TIP You can find the code examples in lt MagicDraw installation direc tory gt openapi examples symbolrendering folder Custom Renderer Provider A PresentationElementRendererProvider class is an object which provides custom symbol renderer for a given presentation element This provider must be registered into the PresentationElementRendererManager PresentationElementRendererProvider Figure 8 Abstract interface of the PresentationElementRendererProvider The main method of the PresentationElementRendererProvider is getRenderer presentationElement This method provides a specific renderer for the given presentationElement Symbol or null Registering Provider To make your provider start working you must register it into the Presentati
75. kageDatabase Spackage Returns true if given package is Database Name Type Description Parameter Spackage com nomagic uml2 Package to be tested ext magicdraw classes mdkernel Package Return boolean true if package is database e SoracleHelper isPublic Selement Returns true if given element has public visibility Name Type Description Parameter Selement com nomagic uml2 Element to be tested ext magicdraw classes mdkernel Element Return boolean true if element has public visibility e SoracleHelper reverseList list Reverses give list Name Type Description Parameter Slist Java util List List to be reversed Return Java util List Reversed list e SoracleHelper getRefName S element Returns reference name description for element with Ref Element tag Name Type Description Example Parameter Selement com nomagic uml2 Element to be tested ext magicdraw classes mdkernel Element Return java lang String Reference element name Example In this sample we will extend current Oracle View DROP statement In the Default template we have Oracle view drop function In this sample the simple macro is presented and it generates the following text DROP VIEW view_name See the sample bellow macro dropView data writeLine DROP VIEW Sutils getQualifiedName data semicolon Snospace end We will add a new tag to identify the CASCADE CONSTRAINTS clause in the DRO
76. l way of connecting to an Eclipse command org eclipse ui actions ActionDelegate that should to be placed on the Eclipse main menu NEW MagicDraw Plugin Integration with Eclipse 2 Create a descriptor p ugin xmi file for the Eclipse bundle to place the command on the Eclipse main menu TIP This is an example of a descriptor that should place the command with id CUSTOM_ACTION_ID under Diagrams gt Diagram Wizards menu lt Define command and attach to category gt lt extension point o0rg eclipse ui commands gt lt command id MyCustomActionWrapper cmd name Command name categoryId MagicDraw gt lt Attach command action to menu gt lt extension point org eclipse ui actionSets gt lt actionSet id Custom action set label Custom action label visible false gt lt action class org my path MyCustomActionWrapper label Custom action label id Custom_action_id menubarPath Diagrams Diagram Wizards group definitionId MyCustomActionWrapper cmd gt lt actionSet gt lt extension gt lt Attach to specific MagicDraw view and editor part gt lt extension name Diagram or View Active point o0rg eclipse ui actionSetPartAssociations gt lt actionSetPartAssociation targetID Custom Action Part gt lt part id com nomagic magicdraw integrations eclipse rcp editors DiagramEditor gt lt part id CONTAINMENT TREE gt lt part id INHERITANCE TREE
77. l2 Element to be tested ext magicdraw c lasses mdkernel Element Return boolean true if element is datatype e SoracleHelper getType type Smodifier Given a type and modifier returns it s description Name Type Description Parameters type com nomagic uml2_ Type of element ext magicdraw c lasses mdkernel Type Smodifier java lang String Modifier of Type Return java lang String Type definition for Oracle DDL e SoracleHelper getTypeModifier element Returns Type modifier for given element Name Type Description Parameter Selement com nomagic uml2 Element to be tested ext magicdraw c lasses mdkernel Element Return java lang String Type modifier description e SoracleHelper getParameters Soperation Utility class Returns list of operation parameters Name Type Description Parameters element com nomagic uml2 Operation to be tested ext magicdraw c lasses mdkernel Operation Return java util List List of operation parameters e SoracleHelper getColumnConstraint column Return given property Constraint Name Type Description Parameter column com nomagic um12 Column to check for constraint ext magicdraw c lasses mdkernel Property Return java lang String Constraint definition e SoracleHelper getCreate element Returns CREATE statement for given element Name Type Description Parameter element com nomagic uml2 Element to be tested ext magicdraw c lasses m
78. le methods to initialize the dialog with multiple element selection mode ElementSelectionDlgFactory initMultiple Display dialog for the user to select elements dlg show Check if the user has clicked Ok if dlg isOkClicked Get selected element in single selection mode BaseElement selected dlg getSelectedElement Get selected elements in multiple selection mode BaseElement selected dlg getSelectedElements UML MODEL MagicDraw UML model is an implementation of OMG UML 2 3 metamodel We do not provide very detail description of all UML metamodel elements and their properties in this documentation or javadoc You can find all this information in UML 2 3 superstructure specification at http www omg org technology documents formal uml htm http www omg org cgi bin doc formal 07 02 05 You should use UML model interfaces from package com nomagic uml2 ext magicdraw The base interface of all model classes is Element implements BaseElement inteface All structure derived from Element you can see in OMG UML2 3 Superstructure Specification All attributes described in UML specification are implemented and accessible through setters and getters Project currentProject Project represents main storage of all project data like main Package Model and all diagrams 43 Copyright 2003 2011 No Magic Inc Accessing Model Element properties Multiple projects can be
79. le see Resource Manager descriptor file on page 28 3 Archive created files to a zip file The zip file should include the required files as well as folders that have structure matching the structure of MagicDraw For information about folders structure for each type of resource and to see the general view of the file structure see Figure 7 Structure of directories and files that could be distributed through the Resource Manager on page 28 4 Import your prepared data to MagicDraw through the Resource Manager For more information about the MagicDraw Resource Manager see MagicDraw UserManual pdf NOTE MagicDraw Resource Manager supports zip archives only The following sections describe the manual resource distribution in details Creating required files and folders structure To distribute resources you must create the required files and folders for a particular resource type Some of the resource file names should match the standard names For each resource files there should be a created folders structure which should match the folders structure of the MagicDraw installation folder To distribute resources you must create a resource manager descriptor file which is described in the section Resource Manager descriptor file on page 28 Distributing Custom Diagrams Required files for custom diagram distribution are as follows e descriptor xml Custom Diagram descriptor provided by this plugin lt lt fold
80. le literalValue double rounded Math round doubleValue 100 100 literalValue Double toString rounded catch NumberFormatException e string literalValue return slot getDefiningFeature getName string return super getText presentationElement textEnum The custom dependency link renderer the dependency link is a blue thicker line with custom line ends class DependencyRenderer extends PathRenderer private PathEndRenderer mClientEndRenderer DependencyRenderer Custom Renderers Sample custom client end renderer use filled circle at the end mClientEndRenderer new PathEndRenderer PathEndAdornment CIRCLE PathEndAdornmentModifier FILLED public Color getColor PresentationElement presentationElement PresentationElementColorEnum colorEnum if PresentationElementColorEnum LINE equals colorEnum use blue color for line return Color BLUE return super getColor presentationElement colorEnum protected PathEndRenderer getClientEndRenderer PathElement pathElement use custom end renderer return mClientEndRenderer public int getLineWidth PresentationElement presentationElement line with is 2 return 2 protected void drawPathAdornment Graphics g PathElement pathElement super drawPathAdornment g pathElement draw circle at the middle of the dependency line Color background Co
81. lement with applied stereotype from Oracle profile Name Type Description Parameters Selement com nomagic uml2 Element to be tested ext magicdraw c lasses mdkernel Element stereotypeName java lang String Stereotype name which should be applied SpropertyName java lang String Property Tag name to get values from Return java util List List of property values Utility class e SoracleHelper getFirstPropertyValueFromProfile Selement SstereotypeName SpropertyName Returns First given Tag property value from given element which has applied given stereotype Name Type Description Parameters Selement com nomagic uml2 Element to be tested ext magicdraw c lasses mdkernel Element stereotypeName java lang String Stereotype name that should be applied to element SpropertyName java lang String Property name where to check for values Return java lang String First property value in String repre sentation e SoracleHelper getDefaultValueAsBoolean property Given an property returns default value as boolean Name Type Description Parameter Sproperty com nomagic um12 Boolean Property to be check for ext magicdraw c default value lasses mdkernel Property Return boolean Default boolean value of property tag e SoracleHelper getFirtPropertyValueFromGivenProfile Selement SprofileName stereotypeName SpropertyName Returns first given tag property value from given element which has applied giv
82. ll UML metaclass specified as a constrained element defines that a validation rule validates elements of the specified metaclass Stereotype specified as a constrained element specifies that a validation rule validates elements that have the stereotype applied Classifier specified as a constrained element specifies that a valida tion rule validates instances of the specified classifier Validation rule s implementation can be OCL2 0 based or binary Binary validation rules can be implemented in Java OCL2 0 based validation rules are described using OCL2 0 language Validation rule can be global or local Global validation rules will be executed only once per validation session Local validation rules will executed for each model element Validation rule will be treated as global if e itis a OCL2 0 based validation rule OCL2 0 specification is valid and OCL2 0 specification does not use self variable explicitly or implicitly by using only a property of constrained element e itis binary based has specified implementation class name and it has no specified constrained elements Local validation rule will be executed on each model element Validation suite is a package with stereotype UML Standard Profile Validation Profile validationSuite Val idation suite organizes several validation rules into a unit that can be used for performing validation Validation rules can be added or imported into validation suite Active validation
83. lor WHITE Property property pathElement getDiagramPresentationElement getProperty PropertyID DIAGRAM BACKGROUND COLOR if property null Object value property getValue if value instanceof Color Point middlePoint pathElement getMiddlePoint int diameter 10 int radius diameter 2 int x middlePoint x radius int y middlePoint y radius background Color value Color color g getColor j g setColor background g fillOval x y diameter diameter g setColor color g drawOval x y diameter diameter Registering Custom Symbol Renderer Provider The example below shows the custom symbol renderer provider which provides the SlotRenderer for slot the PackageRenderer for package and the DependencyRenderer for dependency link symbols The created ren derer provider must be registered into the PresentationElementRendererManager Custom Renderers Sample Step 1 Creating the RendererProvider class Custom renderers provider class RendererProvider implements PresentationElementRendererProvider private SlotRenderer mSlotRenderer private DependencyRenderer mDependencyRenderer private PackageRenderer mPackageRenderer RendererProvider mSlotRenderer new SlotRenderer mDependencyRenderer new DependencyRenderer mPackageRenderer new PackageRenderer public PresentationElementRenderer getRenderer PresentationElement
84. mListenerAdapter new PropertyChangeListener public void propertyChange PropertyChangeEvent evt String propertyName evt getPropertyName if ExtendedPropertyNames VIEW_ADDED equals propertyName ExtendedPropertyNames VIEW_ REMOVED equals propertyName added removed symbol PresentationElement presentationElement PresentationElement evt getNewValue adapter install project When the adapter is no longer needed uninstall it adapter uninstall project PATTERNS MagicDraw provides API for applying some design pattern for the selected classifier pattern s target Pattern can modify a target classifier or even the whole model It also can create presentation elements in the target diagram Pattern s functionality is implemented in a separate MagicDraw plug in ID of this plug in is com nomagic magicdraw plugins impl patterns Usually specific patterns must be added into MagicDraw appli cation as separate plugins Target concept Pattern s target encapsulates information about classifier you want to apply pattern for Target owns e classifier e classifiers presentation element e diagram of presentation element Target is passed to pattern s method AbstractPattern applyPattern It is also accessible from pattern s proper ties AbstractPatternProperties Using PatternHelper Open API provides a helper class PatternHelper with useful methods for patterns
85. mdkernel InstanceSpecification as the type of the parameter The following is an example of a trivial validation rule which always returns true i e all elements are valid Java code package com nomagic magicdraw validation import com nomagic uml2 ext magicdraw classes mdkernel DataType public class TestRule public static Boolean testMeta DataType exp return Boolean TRUE Binary validation rule in plugin Compile such code into Java bytecode and locate it where MagicDraw can load it classpath plugin and then you can use it for validation 1 Create the validation rule in our model 2 Select DataType metaclass as the constrained element of the rule 3 Select Binary language for the expression of the rule 4 Specify com nomagic magicdraw validation TestRule testMeta as the body of the expression of the rule Run the validation suite with included validation rule The method will be invoked for each datatype model ele ment found in the scope of the validation run For each element where this method returns false an entry will be placed in the validation results table For more information about writing Java code which navigates through the model and accesses various data from the model see other sections of current user guide Binary validation rule in plugin MagicDraw validation engine must be able load validation rule implementation class Validation engine is able to load class if the implementation
86. me value change but it will be executed on every property value of a class change How we can fix this problem and inform MagicDraw to execute the validation rule only on class property name change 1 Create a constraint 2 Set stereotype UML Standard Profile Validation Profile validationRule for the validation rule 3 Set severity level error message and abbreviation 4 Specify constrained element s 5 Specify specification language OCL2 0 6 Enter OCL2 0 expression as a body of specification 7 Create a Java class that extends com nomagic magicdraw validation DefaultValidation Rulelmpl class 8 Override method public Map lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt getListenerConfigurations public Map lt Class lt extends Elements Collection lt SmartListenerConfig gt gt getListenerConfigurations Map lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt configs new HashMap lt Class lt extends Elements Collection lt SmartListenerConfig gt gt Collection lt SmartListenerConfig gt configsForClass new ArrayList lt SmartListenerConfig gt configsForClass add SmartListenerConfig NAME CONFIG configs put com nomagic uml2 ext magicdraw classes mdkernel Class class configsForClass return configs 9 Specify the validation rule s implementation property value qualified name of the class 10 Add import the created validation rule to a
87. method can be invoked when plug in is initialized see Chapter Plug Ins Example 1 example diagram descriptor registration see OpenAPI examples for the full source code class SpecificDiagramPlugin extends Plugin Initializing the plugin public void init registering new diagram type Application getInstance addNewDiagramType new SpecificDiagramDescriptor Return true always because this plugin does not have any close specific actions i public boolean close Return true always because this plugin does not have any specific suportability conditions public boolean isSupported return true return true PROJECTS MANAGEMENT ProjectsManager A project is the fundamental MagicDraw data structure Project includes all UML model and diagrams ProjectsManager class is responsible for containment and management of projects ProjectsManager projectsManager Application getInstance getProjectsManager ProjectsManager provides API for Project creating closing saving loading and activating MagicDraw can have multiple opened projects but only one project can be active gets all projects List projects projectsManager getProjects gets active project Project activeProject projectsManager getActiveProject Active project can also be accessed directly from Application gets active project Project project Applica
88. method for all such actions will be invoked after executing any command and after closing opening project or window When some actions need to refresh their state all actions without group can be updated manually ActionsStateUpdater updateActionsState Step 4 Configure actions Every action must be added into some ActionsCategory ActionsCategory is a small group for actions It can be represented as a separator or submenu nested cate gory Categories are added into ActionsManager which is some kind of actions container One ActionsManager represents one GUI element menu bar context menu or toolbar Table below explains how MagicDraw classes maps into GUI elements ActionsManager Category Action Menu Menu bar Menu Menu item Toolbar All toolbars One toolbar Button Context Menu Context menu Submenu Menu item Actions in ActionsManagers are configured by many Configurators Configurator is responsible for adding or removing action into some strictly defined place and position between other actions There are three types of configurators e AMConfiqurator The configurator for general purpose Used for menus toolbars browser and diagrams shortcuts e BrowserContexAMConfiqurator Configurator for configuring managers for browser context popup menu Can access browser tree and nodes e DiagramContextAMConfigurator This configurator for configuring context menus in a diagram Can access diagram selected diagram elemen
89. mplementation of AbstractPanelContainer for patterns without extended properties just with the main properties panel This is the PatternPropertiesPanel class MyPattern will use this class Other patterns may extend AbstractPanelContainer and implement override corresponding methods Step 3 Create pattern class Now we have MyPattern properties and panels We need just pattern implementation package com nomagic magicdraw plugins impl examples mypatterns import import import import import import import import import public com com com com com com com com com nomagic magicdraw nomagic magicdraw nomagic magicdraw nomagic magicdraw nomagic magicdraw nomagic magicdraw nomagic magicdraw core Application openapi plugins plugins plugins plugins uml ReadOnlyElementException impl patterns AbstractPattern impl patterns AbstractPatternProperties impl patterns PatternHelper impl patterns Target properties PropertyManager nomagic uml2 ext magicdraw classes mdkernel Operation nomagic uml2 impl ElementsFactory class MyPattern extends AbstractPattern Returns the categorized name of the pattern return name of the pattern Common MyPattern public String Applies design pattern to the target using properties passed as an argument param target get CategorizedName return new String Common My Pattern Target
90. name and ver sion will be saved into project s XMI file NEW MagicDraw Plugin Integration with Eclipse Extending Eclipse Main Menu with Plugin Command Conventionally you do not need to write any additional code so that the main menu of MagicDraw was extended with some specific commands brought by a plugin after the plugin is installed However this is neces sary when the same plugin is installed on MagicDraw which is integrated with Eclipse If an additional command should appear on the main menu or an additional button should be placed on the main toolbar in MagicDraw after plugin installation you need to create an Eclipse bundle that tells Eclipse where the command or the button should be placed Example Extending the Eclipse main menu with an additional command brought by a MagicDraw plugin Lets say you have already created a MagicDraw plugin that extends the main menu of MagicDraw with a com mand whose id for example is CUSTOM_ACTION_ID To extend the Eclipse main menu with this command 1 Create a class for an Eclipse bundle to extend the com nomagic magicdraw integra tions eclipse rcp actions MDEclipseActionWrapper class TIP This is an example of an Eclipse bundle class that connects to a MagicDraw command by its id CUSTOM_ACTION_ ID public class MyCustomActionWrapper extends MDEclipseActionWrapper public MyCustomActionWrapper super CUSTOM ACTION _ID NOTE This is a genera
91. ngConstants class e Name of the code engineering set e Project where code engineering set will be added e Working package e Working directory a CodeEngineeringManager codeEnqineeringSet CodeEngineeringSet void ets project Project ListeCodeEnqineeringSet gt et project Project language String dialect String name String CodeEngin ption project Project createclassifiersDependencies boolean createPackage ypet project Project language String asAttribute boolean void CreatedFields project Project reset boolean void WodelAndCode_ project Project merqeCode boolean void Pea ineeringSet show OptionDialog boolean void eeringSet void Engineering Seti language String dialect String name String project Project workingP Figure 13 Class for managing Code Engineering Sets e New CodeEngineeringSet can be created directly via CodeEngineeringManager CodeEngineeringManager createCodeEngineeringSet language dialect name project workingPackage workingDirectory Language and dialect can be selected from the CodeEngineeringConstants class Dialect is required for DDL and C languages NOTES e null workingPackage means that code engineering working package will be model Data by default e null workingDirectory means that code engineering working directory will be MagicDraw install root e To remove instance of CodeEngineeringSet u
92. nt change in your java source will solve this migration issue DISTRIBUTING RESOURCES In this section you will find information about how to share your created resources with other users The easi est way to distribute data is to store resources to one zip archive and import the files to MagicDraw with the MagicDraw Resource Manager For more information about Resource Manager see MagicDraw UserMan ual pdf You can distribute the following types of resources e Custom Diagrams e Profiles e Templates e Samples and Documentation e Plug ins You can distribute one resource type or you may distribute the whole resources set How to distribute resources You can distribute custom resources in the following two ways e Using Resource Builder The recourse can be created using Resource Builder To download Resource Builder click Help gt Resource Plugin Manager In the Resource Builder select the package containing all needed files add it to the recourse file and specify several tags The resource file you have created can be distributed to your team members and installed using the Resource Plugin Manager e Distribute manually Manual distribution consists of the following steps 1 Create required files For information about what files are required for each type of resource see Creating required files and folders structure on page 22 2 Create Resource descriptor file For more information about the Resource descriptor fi
93. nt information is retrieved by oracleHelper utility class Oracle View stereotype has 3 properties These tagged values store information about force query restriction and query statements Method SoracleHelper getFirstPropertyValueFromProfile data VIEW STEREOTYPE SQUERY_RESTICTION gets query restriction statement from element data Customizing template To change generation of the particular Oracle Object add new functionality to its macro in velocity template Helper utility class will assist in retrieving model information Read the next chapter to get familiar with available methods We suggest to make a back up of default template Default template is stored in lt MagicDraw install folder gt data DB_engineering Oracle_template folder The template file can be changed in the CG Properties Editor dialog box in the Oracle DDL set shortcut menu choose the Properties command When generating DDL objects are passed from code engineering set to velocity engine Object that are passed to Oracle DDL velocity engine Object name Object type Description SCESList List lt NamedEleme List of model elements that are added to code nt gt engineering set dropRequired boolean Flag to notify if frop objects is required This is a drop setting option which generates Drop state ment SoracleHelper Java lang Class_ This is helper class for retrieving information from model elements Use this class to check element for applied stereoty
94. ntProperties The given PropertyManager can have only few element s properties for example just properties you want to change The following code snippet shows how to change element properties Notification of Presentation Element draw ShapeElement element PropertyManager properties new PropertyManager properties addProperty new BooleanProperty PropertyID AUTOSIZE true SessionsManager getInstance createSession Test PresentationsElementsManager getInstance setPresentationElement Properties elemen t properties SessionsManager getInstance closeSession The properties must be new instances You cannot do something like this ShapeElement element PropertyManager properties element getPropertyManager properties getProperty PropertyID AUTOSIZE setValue new Boolean true SessionsManager getInstance createSession Test PresentationsElementsManager getInstance setPresentationElement Properties elemen t properties SessionsManager getInstance closeSession The Ids of all used properties are defined in class PropertyID Notification of Presentation Element draw SymbolDrawNotification notifies when presentation element is drawn added to diagram element removal listener final PropertyChangeListener removeListener new PropertyChangeListener public void propertyChange PropertyChangeEvent evt if ExtendedPropertyNames REMOVE e
95. ntationElement int File boolean 96 Copyright 2003 2011 No Magic Inc CREATING METRICS Creating New Metric In order to add new metrics you need to extend the Metric class and implement the following methods MetricResult calculateLocalMetricValue ModelElement target boolean acceptModelElement BaseElement element Implementing calculateLocalMetricValue ModelElement target protected MetricResult calculateLocalMetricValue BaseElement target Collection stereotypes StereotypesHelper getStereotypes Element target MetricResult result new MetricResult MetricResult create stereotypes size return result In calculateMetricValue you should put the code that will calculate the local value for your metric In the exam ple it is calculating the number of stereotypes of the elements This value can be used while calculating other modes than Local mode implementing acceptModelElement BaseElement element Example Making the metric be calculated for elements of type Class public boolean acceptModelElement BaseElement element return element instanceof com nomagic uml2 ext magicdraw classes mdkernel Class While implementing acceptModelElement BaseElement element method you have to check the type of ele ments you want your metrics to be calculated for However you should restrict it to types of elements that can be shown in metrics results windows Elements that can be displayed are Class Interfaces
96. ntationsElementsManager getInstance changePathBreakPoints element points SessionsManager getInstance closeSession The order of points in the list must be from the supplier to client connection point The list may or may not include the client and supplier connection points At first the given points list will be adopted for the current path style Rectilinear Bezier or Oblique and only then applied for the path Deleting presentation element To remove the given PresentationElement from the diagram use method PresentationElementsManager deletePresentationElement PresentationElement element SessionsManager getInstance createSession Test PresentationsElementsManager getInstance removePresentationElement element SessionsManager getInstance closeSession All related presentation elements all children and connected paths will be removed too Changing properties of presentation element Most of presentation elements can have properties for example Autosize for shapes or Path Style for paths e To check if element has some properties or uses properties from its parent use method_ PresentationElement useParentProperties e To get all properties of this element use method PresentationElement getPropertyManager e To get property of this element with given ID use method PresentationElement getProperty e To change element properties use method PresentationElementsManager setPresentationEleme
97. onElementRendererManager To add your provider into the custom providers list use the following method PresentationElementRendererManager getInstance addProvider new RendererProvider Custom Symbol Renderer The PresentationElementRenderer class provides API methods which can be customized to a provide custom symbol view for the specific presentation elements Custom Renderers Sample esentationElement void ionElement textEnum PresentationElementTextEnum String tionElement colorEnum PresentationElementColorEnum Color PresentationElement FontProvider PresentationElement Point Figure 9 Abstract class of the Presentation Element Renderer Class by default extended with specific renderers for path symbols PathRenderer and for shape symbols ShapeRenderer Custom Renderers Sample This example will cover e A custom renderer for the package The package without inner elements is filled with green color e A custom renderer for the slot The slot values are rounded e A custom renderer for the dependency link The dependency link is a blue thicker line with custom line ends Creating Custom Renderers This example shows how to create custom renderers for the above described symbols The custom package renderer the empty package i e without inner elements is filled with green color class PackageRenderer extends ShapeRenderer public Color getColor PresentationElement pres
98. opened at the same time Active current project can be accessible in the following way Project project Application getInstance getProject Also Project is accessible for any other Element Project project Project getProject element Project keeps references to root Model also has references to all diagrams Root Model The whole model of one project is contained in a Model instance accessible in the following way Model root Application getInstance getProject getModel Accessing Model Element properties Model element properties can be accessed with simple setters getters com nomagic uml2 ext magicdraw classes mdkernel NamedElement el String name el getName el setName new name Container properties Magicdraw uses composite structure of the model Every model element is a container and contains its own children and knows about its own parent Model element parent can be accessed with Element getOwner method Owned children can be received with method Element getOwnedElement Different types of children are stored in separate container properties You can access these container properties by names that are described in UML specification Method getOwnedElement collects all children from all inner container properties Container properties modification and iteration is straightforward using java util Collection interface Property change events are fired automatically wh
99. pes get tagged values and ele ment s owned information SnewLineBracket boolean Generation Option to generate bracket in new line genDocumentation boolean Language option for documentation generation Utility class Utility class This utility class helps to retrieve information from MagicDraw model elements Use these commands to get particular information e SoracleHelper hasStereotype Selement stereotypeName Returns true if given element has applied given stereotype Name Type Description Parameters Selement com nomagic uml2 Element to check ext magicdraw c lasses mdkernel Element stereotypeName java lang String Stereotype name to be checked Return boolean true if elements has applied stero type with given name e SoracleHelper getBooleanValueFromDefaultProfile Selement SstereotypeName SpropertyName Given an Element Stereotype name and Tag name returns tag value as Boolean from Oracle profile Name Type Description Parameters Selement com nomagic uml2 Element to check ext magicdraw c lasses mdkernel Element stereotypeName java lang String Stereotype name from default pro file that should be applied SpropertyName java lang String Property name which value will be retrieved Return boolean Boolean value of property tag e SoracleHelper getPropertiesListFromDefaultProfile Selement SstereotypeName S propertyName Returns list of given property values that exists on given e
100. quals evt getPropertyName symbol removed element drawing listener SymbolDrawListener symbolDrawListener new SymbolDrawListener public void symbolAdded DiagramPresentationElement diagram PresentationElement symbol String actionID sybmbol added register listener symbol addPropertyChangeListener removeListener 1 register draw listener SymbolDrawNotification symbolDrawNotification SymbolDrawNotification getSymbolDrawNotification project symbolDrawNotification addSymbolDrawListener symbolDrawListener NEW Displaying Related Symbols NEW Displaying Related Symbols MagicDraw allows displaying symbols that are related to a given simbol via relationships The DisplayRelatedSymbols class provides API methods for this Using this class you can control any of the following behaviors for displaying related symbols logic e What relationship types should be included e Depth of a relationship tree e Whether or not existing symbols should be reused Example Displaying related generalizations and interface realizations SessionManager sessionManager SessionManager getInstance sessionManager createSession Display related Set linkTypes new HashSet linkTypes add new LinkType Generalization class linkTypes add new LinkType InterfaceRealization class DisplayRelatedSymbolsInfo info new DisplayRelatedSymbolsInfo linkTypes info setDepthLimited true
101. r LOW_PRIORITY i A e e S a n E public int getPriority return AMConfigurator MEDIUM_PRIORITY Example 2 add some action into main menu after creating a new project create some action final MDAction someAction AMConfigurator conf new AMConfigurator public void configure ActionsManager mngr searching for action after which insert should be done NMAction found mngr getActionFor ActionsID NEW PROJECT action found inserting if found null find category of New Project action ActionsCategory category ActionsCategory mngr getActionParent found get all actions from this category menu List actionsInCategory category getActions add action after New Project action int indexOfFound actionsInCategory indexOf found actionsInCategory add indexOfFound 1 someAction set all actions category setActions actionsInCategory public int getPriority Creating a new action for MagicDraw return AMConfigurator MEDIUM PRIORITY Step 5 Register configurator All configurators are registered in ActionsConfiguratorManager ActionsConfiguratorsManager enables to add or remove many configurators to every MagicDraw predefined configuration see Predefined actions configurations table below All available configurations are accessible in such a way ActionsConfiguratorsManager getInstance add lt configuration_name gt Conf
102. racle DDL generation works in MagicDraw how to change template for some specific things Knowledge of the Velocity Template Language is necessary for understanding editing or creating templates Velocity documentation can be downloaded from http click sourceforge net docs velocity VelocityUsers Guide pdf For more information about Oracle DDL 11g see http download oracle com docs cd B28359_01 server 111 b28286 toc htm Introduction to Oracle DDL generation in MagicDraw The MagicDraw Oracle DDL generation consists of the following three components e Velocity engine Oracle DDL generation is performed by Velocity engine The engine collects context variables and mergers them into template e Template Template is a user defined document that provides Velocity Template Language VTL syntax The VTL syntax is used to manipulate the context variables for generating text script The template file can be changed in the CG Properties Editor dialog box in the Oracle DDL set shortcut menu choose the Properties commana The default Oracle DDL template is stored in lt MagicDraw install folder gt data DB_engineering Oracle_template folder e Context variables Context variables are MagicDraw models retrieved from OpenAPI code engineering set information and user defined variables To identify Oracle object check applied Stereotypes and Tagged Values Understanding Oracle DDL Template structure Default Oracle DDL templat
103. ractPropertyOptionsGroup class 2 Add the extending class to application environment options Example Adding custom environment options class MyOptionsGroup extends AbstractPropertyOptionsGroup Application application Application getInstance EnvironmentOptions options application getEnvironmentOptions options addGroup new ExampleOptionsGroup 88 Copyright 2003 2011 No Magic Inc EVENT SUPPORT MagicDraw UML provides the API for listening to the events while chaning a model There is a possibility either to get an event immediately after the property has been changed or get the event about all the changes in the transaction after this transaction has been executed There are four different listener registration types e Whole repository listener You will get events about the changes in all the elements e Specific element listener You will get events about the changes in any property of this element e Element s specific property listener You will get events about the changes of this property e Specific element type listener You will get events about the changes in all the elements of the specific type The transaction listener is notified when all the changes within the transaction are done and the transaction is closed TIP You can find the code examples in lt MagicDraw installation direc tory gt openapi examples events Property Change Events Each PropertyChangeListener receives
104. rator next Package aPackage Package project getElementByID mountInfo getMountPointID create class in module SessionManager getInstance createSession Create use case in module Class aCase Project getProject aPackage getElementsFactory createClassInstance aCase setOwner aPackage aCase setName myClass SessionManager getInstance closeSession save module projectsManager saveModule moduleDescriptor true if editable make module not editable read only accessibility mode moduleDescriptor setEditable false PROJECT OPTIONS MagicDraw UML provides the API for adding the custom project options These options are project related and saved together with project data In this chapter we will describe how to add a new property and how to retrieve its value Adding Own Project Options A project contains options with the ability to add new properties The following example shows how to add the above mentioned project option s configurator at the plug in s init method in order to have the additional project option Test Property for every project ProjectOptions addConfigurator new ProjectOptionsConfigurator public void configure ProjectOptions projectOptions com nomagic magicdraw properties Property property projectOptions getProperty ProjectOptions PROJECT GENERAL PROPERTIES TEST PROPERTY _ID if property null create property
105. rce code reversing into model elements MagicDraw provides API for e Code engineering sets creation for particular programming languages e Automatic component creation for every class involved in forward engineering and every file involved into reverse engineering e Specification of working or output or temporary directories for processing source code files Destination of the code reverse operation output can be any model package In this chapter we will review how to manage code engineering and how to do reverse and forward engineer ing Code Engineering Set A CodeEngineeringSet object represents a code engineering object as a resource for forward or reverse engi neering CodeEngineeringSet sagetters gt getWorkingDirectory String lt lt seiter gt setNamef name String void t addElements ToCodeEngineeringSet modelElements ListeBaseElement gt void addFilesToCodeEngineeringSet file List File gt void t addA iFilesRecursivelyToCES pathDirectory File void s lt lt geiter geiA iModelElements Liste BaseElement gt Figure 12 Interface of the Code Engineering Set Each CodeEngineeringSet provides properties which can be read e Name Represents a name of the code engineering set visible in the Browser e Model elements Represents elements that are added into the code engineering set from the model e Working directory Represents a code engineering directory where generated
106. resentation elements PathConnector provides information about connected paths to the presentation element To get a collection of connected paths to the presentation element use method PathConnector getConnectedPathElements Using set and sSet There are two types of setters for PresentationElement properties 1 set setters set some value and fire PropertyChangeEvent Use set only if you need that PresentationElement of this data in diagrams must be updated immediately 2 Setters with sSet name are simple setters used for silent property changing Use simple setters when you edit a group of properties All changes will be applied and dependent ele ments will be notified on session close The same rules are for add sAddPresentationElement and remove sRemovePresentationElement accessories The same naming rules are used in all Magicdraw Diagram Presentation Element The purpose of this presentation element is to encapsulate all other presentation elements used in some Diagram e To get a collection of inner presentation elements use PresentationElement getPresentationElements method This method will return only direct children of the diagram e To open a diagram in the MagicDraw UI call DiagramPresentationElement open e To create modify delete inner presentation elements of the diagram use PresentationElementsManager e To layout diagram use DiagramPresentationElement layout NOTE make sure diagram is op
107. retrieve script directory and other necessary information from pluginDescriptor variable There is no need to change any other fields for this variable Jython Jython is an implementation of the high level dynamic and object oriented language Python which is seam lessly integrated with the Java platform Using Jython you may access all java API and MagicDraw open API This allows to avoid compilation and to get the same results without java code Using scripting you may do everything that you can achieve using java plug in and even more you may change your code without recompiling and restarting an application More information about Jython you can find at http www jython org Information about python language you can find at http www python org 33 Copyright 2003 2011 No Magic Inc ADDING NEW FUNCTIONALITY MagicDraw actions mechanism enables to add new functionality to MagicDraw and the way to invoke it through GUI Invoking Actions Actions can be invoked from Main menu Main toolbar Diagram toolbar Browser context menu 34 Copyright 2003 2011 No Magic Inc Creating a new action for MagicDraw Diagram context menu Symbol s Properties Ak Enter Autosize Wrap Words HTML Text b o Diagram Action Example Ak Shift E Keyboard shortcuts Action can not be represented in GUI Create a new action and assign some keyboard shortcut for invoking it Creating a ne
108. reversed files are located Forward Engineering To perform code generation elements should be added to the CodeEngineeringSet object Use the following method to add a list of model elements to the code engineering set e addElements ToCodeEngineeringSet List lt BaseElement gt modelElements NOTE Model elements should be in the working package otherwise model element will not be added to code engineering set Working package is setted when creating code engineering set Managing code engineering sets Reverse Engineering Source code files are required to perform the Reverse Engineering There are 2 methods available for adding files into code engineering set 1 addFiles ToCodeEngineeringSet List lt File gt file This method adds given list of files to code engineering set 2 addAllFilesRecursively TOCES String path This method adds all specific source code files to code engineering set starting from given directory NOTE Source code files should be in working directory in order to have suc cessful reverse Managing code engineering sets CodeEngineeringManager class provides static API methods for creating removing reversing generating and adjusting code engineering settings CodeEngineeringManager class is used for managing code engineering sets When creating the code engineering set the following fields are required e Language and dialect IDs All languages and dialects IDs are stored in the CodeEngineeri
109. ributing Samples and Documentation You can distribute your created samples and documentation and import into MagicDraw with the Resource Manager lt lt folder gt MagicDraw lt lt folder gt samples lt lt file gt gt CustomPluginSample zip B lt lt folder gt manual lt lt file gt gt Custom Plugin Manual pdf B lt lt folder gt lt lt folder gt resourcemanager lt lt file gt gt a D MDR_Samples_CustomPlugin_3001_descriptor xml Figure 5 Folders and files structure required for samples and documentation distribution Distributing Plug ins Required files for plug in distribution are as follows e plugins xml Plug in description For more information about plugin xmI file see Plug in descriptor on page 13 e customPlugin jar jarred plug in class files You may select any title for this file Copyright 2003 2011 No Magic Inc lt lt folder gt D l MagicDraw lt lt folder gt plugins lt lt folder gt customPlugin B ugin_3001_descriptor xml Figure 6 Folders and files structure required for plug in distribution The plug in term may include all resources that could be distributed Such as custom diagrams profiles tem plates samples and others See the general structure of the resources that could be distributed with the Resource Manager in the image below
110. ript id example 1 name Simple menu item version 1 0 provider name No Magic script file main py requiresApi 1 0 gt lt script gt Creating script In the table below you will find the detailed script xmI file structure Element Description script Attributes Name Description id Scrip ID should be unique Used to identify script Example my first script 0 name Script name No strict rules applied to this attribute Example Example script Script version Allows numbers separated with one dot version aa pP an a value Examples 1 0 0 1 provider Script provider name Company or author name name Example No Magic Sodi Relative path to script file This file will be executed script file Example main py MagicDraw API version required by script requires api Example 1 0 Step 3 Write script code Then in the same directory create main py file from javax swing import JOptionPane Script starts here print Starting script descriptor pluginDescriptor JOptionPane showMessageDialog None I am a script After saving files restart MagicDraw On MagicDraw startup message dialog should appear fe4 Message x 9 fi lama script Variables passed to script MagicDraw passes one variable to script pluginDescriptor This variable contains information from parsed script xml file Variable is instance of PythonPluginDescriptor class Jython Script can
111. s How plug ins work MagicDraw on every startup scans plug ins directory and searches there for subdirectories e f subdirectory contains plug in descriptor file plug ins manager reads descriptor file e f requirements specified in descriptor file is fulfilled plug ins manager loads specified class specified plug in class must be derived from com nomagic magicdraw plugins Plugin class Then method init of loaded class is called init method can add GUI components using actions architecture or do other activities and return from the method init method is called only if isSupported returns true Writing plug in Plugins Manager Plugin Check directory descriptor exists Read descriptor file requirement does not meet Check requirements requirements meets Load plugin class no descriptor calling init method Writing plug in With this example we will create a plug in that displays a message on MagicDraw startup To create plug in you need to e Write plug in descriptor Step 1 Create your plug in directory in plugins directory Create a myplugin directory in plugins directory in MagicDraw installation directory Step 2 Write plug in code Plug in must contain at least one class derived from com nomagic magicdraw plugins Plugin class package myplugin public class MyPlugin extends com nomagic magicdraw plugins Plugin public void init javax swing JOptionPane showMe
112. s Large icon is used in toolbar buttons Action for toolbar must have a large icon otherwise it will be displayed as a button with an action name G s Ta i B cp a E e DERA A Pramean Fa ExampleAction Ctrl Shift E setting icon Button with icon looks better than with text in toolbar action setLargeIcon new ImageIcon getClass getResource main_toolbar_icon gif DSW BsB e ExampleAction Ctrl Shift Action s description will be shown as tool tip text Step 3 Describe enabling disabling logic There are two ways for controlling the updating of actions state 1 Add action to predefined actions group Actions can be added into one of predefined actions groups see Actions groups below All actions of one group will be disabled enabled together Conditions for groups enabling disabling and status updating are predefined and cannot be changed Example MDAction action new MDAction Example Example KeyEvent VK_E ActionsGroups PROJECT OPENED RELATED Creating a new action for MagicDraw 2 Implement updateState method for action Here you may describe all conditions when an action must be enabled and when disabled Example of updateState method for some browser context menu action public void updateState action will be enabled only if there are some selected nodes setEnabled getTree getSelectedNode null If action is not added to any group updateState
113. s are items of Tree visible on the left side in every Specification window com nomagic magicdraw ui dialogs specifications SpecificationDialogManager class should be used for registering specification dialog configurator ISpecificationNodeConfigurator More information is available in javadoc 103 Copyright 2003 2011 No Magic Inc CUSTOM DIAGRAM PAINTERS MagicDraw API provides a way to add your own custom diagram painters for painting some additional stuff on the diagram canvas A good sample would be some highlighting in the diagram NOTE Painter can be added only into opened diagram s DiagramSurface BTW only opened diagram has DiagramSurface Closed diagram will return null Code sniplet Application getInstance addProjectEventListener new ProjectEventListenerAdapter public void projectOpened Project project project addPropertyChangeListener new PropertyChangeListener public void propertyChange PropertyChangeEvent evt if evt getPropertyName equals Project DIAGRAM OPENED DiagramPresentationElement diagram Application getInstance getProject getActiveDiagram diagram getDiagramSurface addPainter new public void paint Graphics g DiagramPresentationElement diagram g setColor Color BLUE List symbols diagram getPresentationElements for int i 0 i lt symbols size i PresentationElement o PresentationElement DiagramSurfacePainter sym
114. se the following method CodeEngineeringManager removeCodeEngineeringSet codeEngineeringSet 115 Copyright 2003 2011 No Magic Inc Samples of the forward and reverse engineering e All Code Engineering Sets can be retrieved by the following method CodeEngineeringManager getAllCodeEngineeringSets project e To perform generation of CodeEngineeringSet object use the following method CodeEngineeringManager generate codeEngineerigSet e To perform reverse engineering use the following method CodeEngineeringManager reverse codeEngineeringSet showOptionsDialog Language specific options JavaCEManager provides methods to set Java specific options These options applies to all code engineering sets in project e To add classpaths for java code engineering sets use CodeEngineeringManager setJavaClasspath project arrayOfclasspaths NOTE setting a new classpath will override the old one e To get applied classpaths for java code engineering sets use CodeEngineeringManager getJavaClasspath project e To resolve collection generics when reversing java code use CodeEngineeringManager setResolveCollectionGenerics project true JavaCodeEngineeringManager lt lt getter r gt setResolveCollectionGenerics Figure 14 Class for managing JAVA Code Engineering Sets Samples of the forward and reverse engineering Performing the forward engineering This example shows how to perform simple java code generation
115. sents a set of model elements to a user It is the base for all metaclasses used for presentation All other metaclasses with this purpose are indirect subclasses of PresentationElement Current version of MagicDraw Open API provides just a basic structure of presentation elements reels Every presentation element can have children For example DiagramPresentationElement has a collection of inner presentation elements PresentationElement of some Package can have a collection of presentation elements for inner Package elements Use PresentationElementsManager to create modify delete inner presentation elements of the diagram Current version PresentationElement API allows you to e Access element bounds PresentationElement getBounds method e Access children of the element PresentationElement getPresentationElements method e Access properties of the element PresentationElement getProperty and_ PresentationElement getPropertyManager methods The sample of properties would be Suppress Operations property for class presentation element Autosize property for any ShapeElement e Access model Element of presentation element PresentationElement getElement method Presentation element can have no ModelElement for example TextBox 55 Copyright 2003 2011 No Magic Inc PRESENTATION ELEMENTS Diagram Presentation Element e Select unselect or access selection state of the presentation element A subclass of p
116. ssageDialog null My Plugin init public boolean close Writing plug in javax swing JOptionPane showMessageDialog null My Plugin close return true public boolean isSupported plugin can check here for specific conditions if false is returned plugin is not loaded return true This plug in shows message when it is initialized and another message when it is closed Step 3 Compile and pack plug in to jar file To compile the written code add all jar files recursively from lt MagicDraw installation directory gt lib to java classpath IMPORTANT Make sure that the first three jar files are added in the following order 1 patch jar 2 brand jar 3 brand_api jar Order is not important for the rest jar files Compiled code must be packed to jar file To create jar file use jar command in the plugins directory jar cf myplugin myplugin jar myplugin class Step 4 Write plug in descriptor Plug in descriptor is a file named plugin xml This file should be placed in myplugin directory lt xml version 1 0 encoding UTF 8 gt lt plugin id my first plugin name My First Plugin version 1 0 provider name Coder class myplugin MyPlugin gt lt requires gt lt api version 1 0 gt lt requires gt lt runtime gt lt library name myplugin jar gt lt runtime gt lt plugin gt For detailed information about plug in descriptor see Plug in descriptor on page 13
117. ssifier propertyOwner Classifier owner propertyOwner setName Contains propertyOwner getAttribute size attributes additionally for this Property we register listener to listen for any property changes in this Element properties property addPropertyChangeListener new DerivedValuePropertyChangeListener This transaction commit listener checks if new property is created in classifier and updates classifier s prop erty owner name All changes are done in the same session Register the custom transaction commit listener into the project MyTransactionListener transactionListener new MyTransactionListener TransactionManager transactionManager project getRepository getTransactionMan ager transactionManager addTransactionCommitListener transactionListener SELECTIONS MANAGEMENT Selection in diagrams Every PresentationElement can access selected elements or change their own selection status Collecting selected elements Project project Application getInstance getProject DiagramPresentationElement diagram project getActiveDiagram List selected diagram getSelected Selection events Selection changes fire PropertyChangeEvent To listen selection change events PropertyChangeListener must be registered to Project Project prj Application getInstance getProject prj addPropertyChangeListener new PropertyChangeLi
118. stener public void propertyChange PropertyChangeEvent evt if evt getPropertyName equals Project SELECTION CHANGED was selected List old List evt getOldValue now selected List news List evt getNewValue do something D Selection in model browser Model browser is based GUI part for displaying various model trees 94 Copyright 2003 2011 No Magic Inc Selection in model browser Browser browser Application getInstance getMainFrame getBrowser Browser has five trees e containment e diagrams inheritance extensions e search results Only one tree can be active Tree activeTree browser getActiveTree Every tree is based on Swing JTree and all manipulations can be done by using API provided by Swing JTree tree activeTree getTree Selected nodes are accessible in the following way Node nodes activeTree getSelectedNodes Node is derived from DefaultMutable TreeNode from javax swing tree 95 Copyright 2003 2011 No Magic Inc CREATING IMAGES MagicDraw Open API provides class com nomagic magicdraw export image lmageExporter for creating images from whole diagram or just part of it Image formats are predefined as constants in ImageExporter To create image from the whole diagram use method export DiagramPresentationElement int File To create image from selected symbols in the diagram use method export DiagramPrese
119. sult MeticR esult element BaseElement void lt lt getter gt gt getP ropertyintegerVYalue property String int lt lt getter gt getP ropertyF loatValue property String float lt lt getter gt isPackage element BaseElement boolean s lt getter getC alculaton Metrics Calculator lt lt setter gt setC alculator calculator Metrics Calculator void lt lt getter gt gt getP ropertiesList List lt lt getter getID 0 String lt lt setter gt setID Cid String void lt lt getter gt getP ackageF orElem ent elem ent BaseElem ent BaseElement lt lt getter isFromSam eP ackage element BaseElement otherElement BaseElem ent boolean lt lt getter gt qgetMetricvalueT ed int lt lt setter gt setMeticvalueT pel metric valueT ype int void Constructor The next example will create a metric with the given data about the metrics and put it into the Other group public MyMetric super My Metric MM MetricType OTHER MY METRIC MetricValue INTEGER_VALUE setDescription This is my metric You have also to provide a constructor for your metrics that must call the following super constructor public Metric String name String abbreviation MetricType type String id metricValueType You will have to provide unique name abbreviation and ID for your metric The value return type can be integer or real the constants are on MetricValue class There are already
120. teExceptions is thrown 57 Copyright 2003 2011 No Magic Inc PRESENTATION ELEMEN Presentation Elements Manager PresentationElementsManager can be used only in already loaded and active project In other cases results can be unpredictable PresentationElementsManager is implemented as a singleton Use method PresentationElementsManager getinstance to get a shared instance of this manager Creating shape element To create a ShapeElement for given ModelElement in the given DiagramPresentationElement use method PresentationElementsManager create ShapeElement The location of the created shape will be 0 0 The following code snippet shows how to do this com nomagic uml2 ext magicdraw classes mdkernel Class clazz DiagramPresentationElement diagram SessionManager getInstance createSession Test ShapeElement shape PresentationsElementsManager getInstance createShapeElement clazz diagram SessionManager getInstance closeSession Creating path element To create a PathElement for given ModelLink between given client and supplier elements use method PresentationElementsManager createPathElement com nomagic uml2 ext magicdraw classes mddependencies Dependency link PresentationElement clientPE PresentationElement supplierPE SessionManager getInstance createSession Test PathElement path PresentationsElementsManager getInstance createPathElement link clientP
121. ted return True return true MyMetric class public class MyMetric extends Metric public MyMetric super My Metric MM MetricType OTHER MY METRIC MetricValue INTEGER_VALUE setDescription This is my metric This metric will calculate the number of stereotypes for classes protected MetricResult calculateLocalMetricValue BaseElement target Collection stereotypes StereotypesHelper getStereotypes Element target MetricResult result new MetricResult MetricResult create stereotypes size return result 100 Copyright 2003 2011 No Magic Inc Full example source code public boolean acceptModelElement BaseElement element return element instanceof com nomagic uml2 ext magicdraw classes mdkernel Class Metric framework structure MetricsManager Metrics Suite lt lt cons tructor gt gt MetricsManager lt lt getter gt gt getins tance Metrics Manager t acceptElement element BaseElement boolean acceptDiagramElem ent element BaseElement boolean removeMetrics Suite metrics Suite Metrics Suite void removeMetric metric Metric void removeMetric id String void addMetrics Suite metrics Suite Metrics Suite void addMetric metric Metric void addMetrics metrics Collection void lt lt getter gt gt getMetrics Suite name String Metrics Suite lt lt getter gt gt g
122. the same project or to another project This must be done in the same session There are two modes of making copies e Deep copying with new data e Shallow copying with reused data Example 1 Copying an element Element element Element to copy paste Element parent Parent to which the element has to be pasted either the same project or another project SessionManager sessionManager SessionManager getInstance sessionManager createSession Clone 3rd parameter indicates whether element name uniqueness should be preserved in the parent CopyPasting copyPasteElement element parent true sessionManager closeSession Example 2 Copying multiple elements and symbols List elements Elements to copy paste List views Symbols to copy paste Element parent Parent to which elements should be pasted either the same project or another project BaseElement symbolParent Parent to which symbols should be pasted SessionManager sessionManager SessionManager getInstance sessionManager createSession Clone Working with Stereotypes and Tagged Values 4th parameter indicates whether deep or shallow copy is applied 5th parameter indicates whether element name uniqueness should be preserved in the parent List baseElements CopyPasting copyPasteElements views parent symbolParent true true sessionManager closeSession Working with
123. thod p setResourceProvider MyResourceProvider getInstance properties addProperty p MyPattern does not have extended properties so we do not override configureExtendedPropertyManager method Names of MagicDraw properties can be translated into other languages so they are not hard coded inside the properties To get property name from property ID PropertyResourceProvider is used We will write a simple PropertyResourceProvider for our pattern s properties package com nomagic magicdraw plugins impl examples mypatterns import com nomagic magicdraw properties PropertyResourceProvider public class MyResourceProvider implements PropertyResourceProvider Instance of this provider private static MyResourceProvider mInstance Returns shared instance of this provider return shared instance public static MyResourceProvider getInstance if mInstance null How to create my own pattern Returns resource for given key param key a resource key return the resource for given key public String getString String key mInstance return mInstance new MyResourceProvider if key equals MyPatternProperties METHOD_NAME return Method Name else if key equals MyPatternProperties TARGET CLASS return Target Class return null Step 2 Create pattern panels class MagicDraw API provides the default i
124. tion getInstance getProject 81 Copyright 2003 2011 No Magic Inc ProjectDescriptor ProjectDescriptor ProjectDescriptor represents a project and module as a resource for storing and loading The same project can have multiple ProjectDescriptors ProjectDescriptor getURi URI getRepresentationString String isRemote boolean There are two types of ProjectDescriptors e Local project descriptor Represents a local ordinary project A descriptor can be created for a project or file object e Remote project descriptor Represents a project stored in the Teamwork Server NOTE Teamwork Project has both descriptors local and remote because it can be saved locally Every ProjectDescriptor provides properties e URI Location is some specific String value that holds all information that is needed to access a project e Representation String Representation String is used for a project identification in user interface GUI e Remote flag Remote flag indicates if the project descriptor represents teamwork project ProjectDescriptorsFactory and Teamworkutils ProjectDescriptorsFactory can create appropriate ProjectDescriptor object TeamworkUtils helps to find an existing teamwork remote project descriptors Project management Projects are saved and loaded by using two methods in ProjectsManager class e saveProject ProjectDescriptor descriptor boolean silent e loadProject ProjectDes
125. tion properties 37 Step 3 Describe enabling disabling logic 37 3 Copyright 2003 2011 No Magic Inc CONTENTS Step 4 Configure actions 38 Step 5 Register configurator 40 Actions hierarchy 41 Predefined actions configurations 42 NEW Selecting elements via element Selection dialog 42 UML MODEL 43 Project 43 Root Model 44 Accessing Model Element properties 44 Container properties 44 Collecting all children from all hierarchy levels 45 Visitors 46 InheritanceVisitor 46 Changing UML model 47 SessionManager 47 ModelElementsManager 47 Creating new model element 48 Editing model element 48 Adding new model element or moving it to another parent 48 Removing model element 49 NEW Refactoring model elements 50 Creating Diagram 50 Creating new Relationship object 51 NEW Copying elements and symbols 51 Working with Stereotypes and Tagged Values 52 Hyperlinks 53 PRESENTATION ELEMENTS 55 Presentation Element 55 Using set and sSet 56 Diagram Presentation Element 56 Shapes 57 Paths 57 Presentation Elements Manager 57 Creating shape element 58 Creating path element 58 Reshaping shape element 58 Changing path break points 59 Deleting presentation element 59 Changing properties of presentation element 59 Notification of Presentation Element draw 60 NEW Displaying Related Symbols 61 SYMBOLS RENDERING 62 Custom Renderer Provider 62 Registering Provider 62 Custom Symbol Renderer 62 Custom Renderers Sample 63 4 Copyright
126. to container modelElement get lt SomeContainer gt add child modelElement get lt SomeContainer gt remove child Collecting all children from all hierarchy levels Here is an example of how to collect all children from Element and avoid recursion using simple for cycle ArrayList children new ArrayList Element current children add current if current element has children list will be increased for int i 0 i lt children size i current Element children get i add all children into end of this list so it emulates recursion children addAll1 current getOwnedElement UML MODEL Collecting all children from all hierarchy levels Visitors Every Element has accept method for visiting it in Visitors for more details about this mechanism see Visitor pattern Visitor has visit method for all types of model elements and presentation elements This is very useful when you are working with large collection of ModelElements and need to perform actions specific for every type of Element for example save load copy paste or specific properties setting Just derive your class from InheritanceVisitor and override some visit methods Example of how to visit a group of ModelElements Visitor myVisitor new Visitor E Model root Application getInstance getProject getModel Iterator it root getOwnedElement iterator while it hasNext
127. tom actions for user in UI but does not solve custom task executing in the batch mode For exam ple if you want to run MagicDraw open some project execute code generation and close MagicDraw plug ins will not work NOTE MagicDraw application can not be run on headless device even in batch mode Graphical environment is required MagicDraw provides API for running it in the batch mode For this you need to extend the following class com nomagic magicdraw commandline CommandLine Code sniplet public class ExportDiagramImages extends CommandLine public static void main String args launch MagicDraw new ExportDiagramImages launch args protected void run File projectFile open some project ProjectDescriptor projectDescriptor ProjectDescriptorsFactory createProjectDescriptor projectFile toURI Application getInstance getProjectsManager loadProject projectDescriptor true project is opened and now you can work with your project Full working sample is provided in Open API examples with name ImageGenerator It takes a project file desti nation directory as arguments and generates images for all diagrams NOTE Do not forget to add all jar files recursively except md_commontw jar and md_commontw_api jar from lt MagicDraw installation directory gt lib directory into the classpath Make sure the patch jar is the first in the classpath
128. ts and element that requests context menu ActionsManagers for the main menu and all toolbars are created and configured once so later actions can be only disabled but not removed Context menus are created on every invoking so ActionsManagers are created and configured every time and actions can be added or removed every time Example 1 add some action into browser s context menu final DefaultBrowserAction browserAction Creating a new action for MagicDraw BrowserContextAMConfigurator brCfg new BrowserContextAMConfigurator implement configuration Add or remove some actions in ActionsManager tree is passed as argument provides ability to access nodes public void configure ActionsManager mngr Tree browser actions must be added into some category so create the new one or add action into existing category MDActionsCategory category new MDActionsCategory category addAction browserAction add category into manager Category isn t displayed in context menu mngr addCategory category Returns priority of this configurator All configurators are sorted by priority before configuration This is very important if one configurator expects actions from other configurators In such case configurator must have lower priority than others return priority of this configurator see AMConfigurator HIGH PRIORITY see AMConfigurator MEDIUM PRIORITY see AMConfigurato
129. ty should be Class and Interface from the UML Standard Profile Validation rule that is interested in Activity parameters and Activity parameter node changes example public Map lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt getListenerConfigurations Map lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt configMap new HashMap lt Class lt extends Element gt Collection lt SmartListenerConfig gt gt Collection lt SmartListenerConfig gt configs new ArrayList lt SmartListenerConfig gt SmartListenerConfig parameterConfig new SmartListenerConfig Collection lt String gt parameterPropertiesList new ArrayList lt String gt parameterPropertiesList add PropertyNames DIRECTION parameterPropertiesList add PropertyNames TYPE parameterPropertiesList add PropertyNames OWNED TYPE Create Binary Validation Rule Case D parameterConfig listenToNested PropertyNames OWNED PARAMETER listenTo parameterPr opertiesList SmartListenerConfig cfg new SmartListenerConfig Collection lt String gt argumentCftList new ArrayList lt String gt argumentCftList add PropertyNames PARAMETER argumentCftList add PropertyNames TYPE argumentCftList add PropertyNames OWNED_ TYPE cfg listenTo argumentCftList SmartListenerConfig argumentConfig new SmartListenerConfig argumentConfig listenTo PropertyNames NODE cfg configs add parameterConfig
130. uninstalling the plug in all defined files will be removed For example if samples is defined then uninstalling the resource will remove all files from the samples folder JYTHON SCRIPTING MagicDraw allows you to access open API using Jython scripting language MagicDraw on every startup checks for scripts in plugins com nomagic magicdraw jpython scripts If there are subdirectories each of them are scanned for the script xml file This file provides information about script in this directory File is similar to plug in descriptor described in plug ins section See Plug in descriptor on page 13 If script xm contains valid information script file specified in script xml is executed Script file should contain valid Jython NEW 2 5 2 script NOTE For writing scripts the user should have basics of Jython programming language and be familiar with MagicDraw open API Creating script In the following example we will create script which shows a message on MagicDraw startup To create script you need Step 1 Create directory First of all a subdirectory in plugins com nomagic magicdraw jpython scripts should be created Step 2 Write script descriptor Script descriptor is a file written in XML and named script xml Script descriptor provides information about script file to run version of script ID etc In the mentioned directory create script xmI file lt xml version 1 0 encoding UTF 8 gt lt sc
131. validation suite See MyOCLBasedValidationRuleImpl java example in lt MagicDraw_ install dir gt openapi examples validation directory NOTE the implementation class must be in the classpath of the MagicDraw application or if the imple mentation class is in a plugin then the plugin s classloader must be registered to the validation system see Binary validation rule in plugin Binary Validation Rule Sometimes it is hard to specify the rule for some advanced concepts in OCL For example string manipulation is rather weak in OCL2 0 hence the writing rule for string formats parsing strings is very hard in OCL In such cases MagicDraw offers possibility to write rules in Java language and invoke them when validating Common steps for creating a binary validation rule 1 Create a constraint Create Binary Validation Rule Case A 2 Set stereotype UML Standard Profile Validation Profile validationRule for the validation rule 3 Set severity level error message and abbreviation 4 Specify constrained element s 5 Specify specification language binary 6 Create Java implementation class see all possible cases below 7 Compile Java code resulting in one or several classes 8 Ensure that MagicDraw can find amp load these classes You can place them in the MagicDraw classpath or use the MagicDraw plugins mechanism The same rules as writing the code for open API are used here These steps are common to all possible
132. w action for MagicDraw Step 1 Create new action class All actions used in MagicDraw must be subclasses of MDAction class see JavaDoc for more details The following MDAction subclasses that are used for basic purposes are already created in MagicDraw e DefaultBrowserAction action class used for browser action Enables to access some browser tree and nodes Recommended to use for performing some actions with the selected browser nodes e DefaultDiagramAction action class for diagram action Enables to access some diagram elements Recommended to use when for performing some actions with the selected diagram elements e PropertyAction action for changing some element or application property Can be used for changing properties defined by user You must override at least actionPerformed method and implement in it what this actions is going to do Example simple action class SimpleAction extends MDAction public SimpleAction String id String name super id name null null Shows message public void actionPerformed ActionEvent e JOptionPane showMessageDialog Application getInstance getMainFrame getDialogParent This is getName j Creating a new action for MagicDraw Examplez2 action for browser public class BrowserAction extends DefaultBrowserAction Creates action with name ExampleAction public BrowserAction super ExampleAction null
133. y property has two major attributes ID and value Property has value of type java lang Object Every spe cific property has value of specific type For example value of BooleanProperty is java lang Boolean value of String property is java lang String Property ID identifies specific property in the properties set Every property has specific editor for editing value of the property For example BooleanProperty is edited with javax swing JCheckBox component ChoiceProperty with javax swing JComboBox StringProperty with javax swing JTextField You may provide your own PropertyEditor for some specific property editing In order to do this you need to override Property createEditor method You must set some PropertyResourceProvider to your property instance in order to display normal name not id of the property in the MagicDraw UI PropertyResourceProvider has just one method PropertyResourcePro vider getString key where key is id of your property 74 Copyright 2003 2011 No Magic Inc PROPERTIES The collections of properties are grouped by PropertyManagers Every PropertyManager has name and list of properties It can return property by id properties with the same value properties whose values are different For more details about every specific kind of property see javadoc 75 Copyright 2003 2011 No Magic Inc NEW DIAGRAM TYPES There are two groups of the diagrams in MagicDraw creatable and not creatable
Download Pdf Manuals
Related Search
Related Contents
MANUAL DAS LAVADORA LP-5 LP-5A COM LOGO Scarica Manuale d`Uso e Manutenzione User Manual - AJ Medical 13. Guía de usuario para la Realización del trámite de Certificado Kenmore 152.329361 Water Heater User Manual AT20E (multi) Instructions: Food and Hydration Pack Mode d`emploi: Sac pour Toro 3000 Lawn Mower User Manual PHILIPS Strand Lighting Copyright © All rights reserved.
Failed to retrieve file