From a2f9e3481bafab35ea83c4da11960cb1d39ab6a5 Mon Sep 17 00:00:00 2001 From: Claudenir Morais Fonseca Date: Fri, 2 Oct 2020 16:51:02 +0200 Subject: [PATCH] Release 0.4.0 (#73) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Serialization of Enumeration Literals (#11) * Included complete OntoUML stereotype list and improved JSON serialization (#9) * All Steryotypes removed and OntoUML steryotypes added on plugin start, remove all UML steryotypes both type class and association and install OntoUML stereotypes. * Fixed package name. * buttons for load/unload ontoUML stereotypes * improve the activation of the default stereotypes when activate the default stereotype, removed the stereotypes that are already in the classes. * [WIP] print json schema for all elements in project. Still missing some features. added testModel.vpp to the vpp projects folder * added support for association and other types * Testing commit * [wip] added uri to the elements * Ongoing integration * Functional remote verification Non-blocking, logged, remote verification. Requires refactoring. * Minor improvements Bug-fixes and refactoring * Minor fixes * Improved generation and error display on LOG Transformation shall be updated to workaround limitations of GSON's serialization and improvements on OntoUML Schema. * Changing Stereotypes with Right Click * Experimenting with default color profiles * Fixing GSON issue and ClassCastException * Updating stereotypes * Setting up configurations menu * Configurations Menu * General improvements * General refactoring and bugfix * General refactoring and bugfix #2 * Major Refactoring and Documentation Classes yet to be refactored/documented: - ActivateOntoUMLPlugin - ActivateDefaultStereotypes - StereotypeUtils - CollectionAdapter - Most classes within package it.unibz.inf.ontouml.vp.model * Model Export feature and refactoring * Auto-coloring feature and icons update * Minor improvements to auto-coloring It now affects all views of the selected model element. * Maven project (#7) * maven project * removed readme * openapi.jar was added to the project folder in order to be executed out of the box using maven compile. * changed folder name lib to repo / changed compiler to java 11 in pom.xml * gitignore updated * solved identation in git ignore file * Revert "Merge branch 'development' into maven-project" This reverts commit a72c78c83ec31e328557caf3aeb44ae81ad1d779, reversing changes made to 1cd30e4a5be5de47df0cd78316fa7fca411bf56b. * Update .gitignore * Delete openapi.jar * Update .gitignore * Removed unused imports * Update .gitignore * Including debug dependencies * Cleaning POM file * added generation of zip file of the plugin * Update README and .gitignore Co-authored-by: Tiago Prince Sales Co-authored-by: Claudenir Morais Fonseca * removed toolbar buttons and removed some options in configurations panel. * cardinality updated * removed comment * Removed XML Export Window. * removed if to test if model verification is enabled * fixed url server verification * Fixed string regex in AssociationEnd * set timeout for 60s in request verification * added some logs in verification and also added behavior to check if custom server is enabled before mounting the URL. * Added all stereotypes * Stereotype order * Update stereotype serialization * Removed unused import * Coloring enabled by default * Update Stereotypes.java * updated associationEnd and Attribute cardinalities * change aggregationkind when applying stereotypes and set abstract to true when aplying mixin stereotype to classes * [WIP] - implementing new schema * wip - corrections in model creation to adapt to the new schema * remove propertyAssignment class. * created reference class * fixes * fix * Some updates Ongoing changes * added propertyAssignment build * wip - added property assignment to reflect better tagged values, add DataType class as well. * isDerived logic * Removed <> stereotype. <> should be used instead. * Update .gitignore * Removed Stereotypes.java This class only responsibility was to add the prefix ontouml/2 or vp/custom to stereotypes on the serialization. We decided not to have this prefixes on the exchanged models anymore. * Update ModelExportAction.java * Removed Reload plugin button * Bugfix null pointer on Association and Property constructors * removed datatype class and included datatype constructor in class class. Removed AssociationEnd and Attribute classes because it will be handled by Property class. * fixed associationclass * propertyAssignments in all elements * fixed setName and isDerived * fixed property assignments for association end * added some comments * id was not being set in Package Element * added description field to the elements * if description is empty set attribut to null * fixed Reference in Generalization constructor * fixed reference in GeneralizationSet * fixed tagged values when model element is not specified * ready to be merged * Improvements from code review * Removed duplicated code and fixed transformation of missing propertyType * Missing refactoring from tagged value extraction * Update Class.java Co-authored-by: Claudenir Morais Fonseca Co-authored-by: Tiago Prince Sales * added Literal class for enumeration serialization Co-authored-by: Viola Co-authored-by: Claudenir Morais Fonseca * Hotfix: Null pointer exception on Class constructor (#13) * fixed constructor - checked this.stereotypes for null before using. * Update Class.java Co-authored-by: Tiago Prince Sales * Serialization improvements on propertyAssignments and Generalization and GUI improvement on Model Export (#12) * Included complete OntoUML stereotype list and improved JSON serialization (#9) * All Steryotypes removed and OntoUML steryotypes added on plugin start, remove all UML steryotypes both type class and association and install OntoUML stereotypes. * Fixed package name. * buttons for load/unload ontoUML stereotypes * improve the activation of the default stereotypes when activate the default stereotype, removed the stereotypes that are already in the classes. * [WIP] print json schema for all elements in project. Still missing some features. added testModel.vpp to the vpp projects folder * added support for association and other types * Testing commit * [wip] added uri to the elements * Ongoing integration * Functional remote verification Non-blocking, logged, remote verification. Requires refactoring. * Minor improvements Bug-fixes and refactoring * Minor fixes * Improved generation and error display on LOG Transformation shall be updated to workaround limitations of GSON's serialization and improvements on OntoUML Schema. * Changing Stereotypes with Right Click * Experimenting with default color profiles * Fixing GSON issue and ClassCastException * Updating stereotypes * Setting up configurations menu * Configurations Menu * General improvements * General refactoring and bugfix * General refactoring and bugfix #2 * Major Refactoring and Documentation Classes yet to be refactored/documented: - ActivateOntoUMLPlugin - ActivateDefaultStereotypes - StereotypeUtils - CollectionAdapter - Most classes within package it.unibz.inf.ontouml.vp.model * Model Export feature and refactoring * Auto-coloring feature and icons update * Minor improvements to auto-coloring It now affects all views of the selected model element. * Maven project (#7) * maven project * removed readme * openapi.jar was added to the project folder in order to be executed out of the box using maven compile. * changed folder name lib to repo / changed compiler to java 11 in pom.xml * gitignore updated * solved identation in git ignore file * Revert "Merge branch 'development' into maven-project" This reverts commit a72c78c83ec31e328557caf3aeb44ae81ad1d779, reversing changes made to 1cd30e4a5be5de47df0cd78316fa7fca411bf56b. * Update .gitignore * Delete openapi.jar * Update .gitignore * Removed unused imports * Update .gitignore * Including debug dependencies * Cleaning POM file * added generation of zip file of the plugin * Update README and .gitignore Co-authored-by: Tiago Prince Sales Co-authored-by: Claudenir Morais Fonseca * removed toolbar buttons and removed some options in configurations panel. * cardinality updated * removed comment * Removed XML Export Window. * removed if to test if model verification is enabled * fixed url server verification * Fixed string regex in AssociationEnd * set timeout for 60s in request verification * added some logs in verification and also added behavior to check if custom server is enabled before mounting the URL. * Added all stereotypes * Stereotype order * Update stereotype serialization * Removed unused import * Coloring enabled by default * Update Stereotypes.java * updated associationEnd and Attribute cardinalities * change aggregationkind when applying stereotypes and set abstract to true when aplying mixin stereotype to classes * [WIP] - implementing new schema * wip - corrections in model creation to adapt to the new schema * remove propertyAssignment class. * created reference class * fixes * fix * Some updates Ongoing changes * added propertyAssignment build * wip - added property assignment to reflect better tagged values, add DataType class as well. * isDerived logic * Removed <> stereotype. <> should be used instead. * Update .gitignore * Removed Stereotypes.java This class only responsibility was to add the prefix ontouml/2 or vp/custom to stereotypes on the serialization. We decided not to have this prefixes on the exchanged models anymore. * Update ModelExportAction.java * Removed Reload plugin button * Bugfix null pointer on Association and Property constructors * removed datatype class and included datatype constructor in class class. Removed AssociationEnd and Attribute classes because it will be handled by Property class. * fixed associationclass * propertyAssignments in all elements * fixed setName and isDerived * fixed property assignments for association end * added some comments * id was not being set in Package Element * added description field to the elements * if description is empty set attribut to null * fixed Reference in Generalization constructor * fixed reference in GeneralizationSet * fixed tagged values when model element is not specified * ready to be merged * Improvements from code review * Removed duplicated code and fixed transformation of missing propertyType * Missing refactoring from tagged value extraction * Update Class.java Co-authored-by: Claudenir Morais Fonseca Co-authored-by: Tiago Prince Sales * added new file dialog to export model. Also suggets filename. * if no property assignment added - return null * if a Generalization has stereotypes in both ends does not add this generalization to the model. * export json Changed view to File Dialog Now suggests the same name of the last save * Quick fix on name suggestion * Removed unused semicolon * Only serializes generalizations between classes or associations * Update ModelElement.java Co-authored-by: Claudenir Morais Fonseca Co-authored-by: Tiago Prince Sales * Hotfix: Null pointer exception when reading outdate config file (#14) * Bugfix * Remove unnecessary sysout call Co-authored-by: Claudenir Morais Fonseca * Feature to disable associations dynamically (#15) * added feature to disable associations dynamically * Bugfix when applying <>, <>, <> and <> * added missing source stereotype (Quality) * Update ApplyStereotype.java * Fixed category case when setting the possible relations * changed types do HashMap * removed powertype from the association stereotypes list and also removed some unused imports * implementation changed to use a single map with all constraints. * removed unused imports * Update AssociationConstraints.java * Minor improvements Co-authored-by: Tiago Prince Sales Co-authored-by: Claudenir Morais Fonseca * [WIP] Listeners and basic coloring. * [WIP] coloring all model * [WIP] Smart Coloring fixes * fix in smart paint * fixed unused code * paint diagram button improved listeners * if auto coloring disabled do not paint * WIP added listeners when load the plugin. Still need to evaluate where the listeners should be. * fixed mixins coloring * fixed coloring to match mixin pattern * fixed subkinds in a row * Small fixes * Avoids repeating code * Renamed COLOR_NON_SORTAL to COLOR_UNKNOWN * fixes and removed unused code * added smartpaint in applystereotype It is been hard to deal with stereotype listener * removed unused listeners * Removed println() that I commited by mistake * Update SmartColoring.java * Menubar Icon update * working for generalization changes * Update OntoUML server URL * removed unused imports * Added a warning when the user clicks on smart paint and the auto coloring is set to false. * fixed null pointer exception when removing generalization. * Fixed NullPointerException when serializing generalizations * Bugfix on my previous fix ;) * added dialog box when user clicks in smart paint * Updates Smart Paint actions and removes unused imports * Updates listeners, improves readability and prevents exceptions * todo's removed. * Quick systout fix * Syntax verification (#17) * verification response warning dialog and messages in log panel * improved log messages and created function to get icon path. * Minor fixes * Adds verification dialog method * some http response handled and added some try/catch * Updates dialogs in case of failure Co-authored-by: Claudenir Morais Fonseca * Connects plugin to the server for model transformation to gUFO (#18) * Initial commit * Connects to the server * Minor issues * addded verification for custom server in transformation to gufo also adapted verification function url building. * added option to retry export to gUFO using the default server. * added option to retry in verification service if service custom has problems * Adds protection to Server Not Found Co-authored-by: Viola * Smart meta properties feature (#27) * set meta-properties whole model * bug fixed when applying stereotypes for associations. * set cardinalities if null or unspecified. * update smartproperties.java to avoid duplicated code. * set readonly only where it is true. * fixed bug in cardinality setting. * Fixed cardinality value on <> * renamed smartProperties to SmartModelling. Moved functions from ApplyStereotype to SmartModelling class. Removed set meta properties from listeners and added to the class ApplyStereotype. * Bugfix: HistoricalDependence * Group all "smart modeling" features together Plus: 1. Material relations are 1..* by defaul only when relating roles. 2. subQuantityOf is, by default, readOnly=true on the part end * Removed unused imports * Created function to set default meta properties also for classes * Cleaned up SmartModeling.java Co-authored-by: Victor Viola Co-authored-by: Tiago Prince Sales * Disable stereotypes as you model (#28) Implement the features described in issues #23 and #26 * disabling stereotypes as you model. * removed unecessary comments * added option in configurations to enable/disable smart modelling * Fixed allowed supertypes of Subkind * Subkinds cannot specialize Types * fix in setting allowed stereotypes in generalizations * fixed layout for configurations panel. * Fixed null pointer when subtype or super type did not have stereotypes * Enabling/disabling smart modeling applies to associations and classes * Toggling smart modeling also impacts association default metaproperties Co-authored-by: Victor Viola Co-authored-by: Tiago Prince Sales * diagram verification * added user logs to distinct between diagram/model verification. Also added protection to runs the diagram verification only if there is a class diagram opened. * Adjusted messages display in dialogs displayed after verification is called * Small improvements to the message log * New Log Panel and highlight elements after verification. * improved textArea in log panel. Now user cannot edit the text. * open specification option in context menu / disable take me there if class is not in any diagram * border between results in log panel * Updates ViewUtils * Updates ViewUtils * changed log panel to use JList. * Updates ViewUtils * Apply stereotype feature works when multiple classes are selected (#39) * apply multiple sterotypes at same time. Only works if all elements in the selection are the same. * if selection has classes and associations selected at the same time validate rule for only the object that had the click. * apply same stereotype for all elements selected * fix update stereotype when selection multiple objects. * when user selects more than one object do not apply constraints * added new Fixed menu - now suggests stereotypes only when 1 class is selected or all selected classes have the same super class. * fixed action behavior in context menu of the model explorer * fixed context menu when selecting stereotypes from model explorer Co-authored-by: Victor Viola * Issue31 add progress bar (#44) * apply multiple sterotypes at same time. Only works if all elements in the selection are the same. * if selection has classes and associations selected at the same time validate rule for only the object that had the click. * apply same stereotype for all elements selected * fix update stereotype when selection multiple objects. * when user selects more than one object do not apply constraints * added new Fixed menu - now suggests stereotypes only when 1 class is selected or all selected classes have the same super class. * fixed action behavior in context menu of the model explorer * fixed context menu when selecting stereotypes from model explorer * progressBar first version * progress bar when calling diagram verification * progresspanel - WIP * fixes - wip * progresbar with threads. Now user can cancel the request. * fixed bug in case of exception or response null * added message when user cancel the request. * added progress bar to export to json after user selects the filename and file directory * first close the progess bar then show the dialog * added progress bar when exporting to gufo * removed duplcated code. * bug fixed when selecting an invalid endpoint * bug fixed when handling model verification response * added progress dialog to the functions that connects to the server. Improved the way the progress dialog works. * improved in how the loading box closes. * Fixed null pointer when canceling the model export Co-authored-by: Victor Viola Co-authored-by: Tiago Prince Sales * Made project compliant to Maven's default folder structure * Fixes on pom.xml * Executing VP with plugin through Maven * Added maven wrapper * Skip installation of plugin on local maven directory * Updates scripts * Improved README.md * Cleaned up run.sh * Added build profiles to distinguish exec scripts * added .bat script to mvn exec in windows * Fixed unix run-vp script * improved bat script * Update README.md * added version label in settings panel (#48) * Added support for OntoUML tagged values(#37) * Adds proper generation of stereotypes * Updates apply stereotypes and serialization * Working on tagged value overwrite * Bug fix * Updates class serialization * Fix tagged value update * Refactor methods * Bugfix apply fixed menu * Updates context menus for properties * Updates properties menus * Updated set order dialog * Includes abstract nature * Updates JSON serialization * Bugfix * BugFix * Additional options added to the contextual menus * Removes local maven variables from repo * Updates Meta-Properties context menu * Updates enabling of meta-properties context menu Co-authored-by: Tiago Prince Sales * Bugfix duplicated tagged values * New UI to access the ontouml2gufo service (#49) * WIP - checkbox tree for diagrams and model * added dynamic icons to the tree * improved icon setting. * wip - added option to choose between trees * Save user config when exporting to GUFO * wip - selection tree - retrieving nodes * fixed window control * created new constructors. * fix bug when calling class constructor * added comments and removed others. * Moved icons * wip - package tree explorer * now models and packages have priority in the package tree. * added new model elements to package tree * added option to check class without checking attributes * fix attribute selection * check all same objects in the tree * fixed identation * fixed multiple selection when have commom objects in the selection. * fixed selection for classes * now the tree is saving in the configurations * fixed attributes when selecting classes * fixed model snapshot when selecting generalization sets * consider IDiagramUIModel as its parent element * now nodes of the tree are being inserted sorted. * now tree is organized per type AND alphabetically * added associations and generalizations to the package tree * select classes of the same type of the attribute selected. * check types for subtree * request improved * improved tree cell renderer * 1st version export view * new export to gufo window finished * fixed diagram saving element * added new icons * new icons * icon for package changed * fixed model building * improved selection for similar node * improved threads * changed icon for association end * name for association end * changed name root element for diagram tree * fixed nullpointer * add labels for combos * resize window false * prevent window export to be opened twice * prevent config window to be opened twice * changed UI export * removed unused component * adjust in UI * adjust in UI * improved layout * fixed label * layout improvement * adjust * new layout for export - wip * layout improvement - wip * added table * added packages tab * Changed labels * Added default language option * layout adjust * update * ui updated * adjust ui * Adjusted labels * Set Base IRI default value * UI fixes * changed default behavior for tables * get json string from tables * generating json to send transformation to server * Bugfix on allowed nature serialization * Updates export file format and datatype serialization * Minor refactoring * Bugfix tag removal on apply meta-properties * Updates meta-property serialization * Minor presentation issue * Bugfix on suggested stereotypes * Bugifx on gufo options export * fixed model building for tree and package * added port number to the default server * code improved * adjusted images * select generalizations when g_set is selected * fixed tree for diagram and package views * fixed serialization * fixed name of the generalizations in the tree * Fixed element and package mapping serialization Removed duplicate code * General code improvements * Smart painting based on restrictedTo meta-property * Fixed bugs related to tagged values * Updates listeners for restrictedTo inference * Updates inference criteria * Updates ApplyProperties * Improving manipulation of tagged values * Updates interaction with tagged values * BugFix - Add listeners in projects that were "not created" (when the tool open without opening an existing project) - Binds tagged value definitions to to stereotypes instead of simply adding them to the stereotype's tagged value definition container * Bugfix and cleanup * Bugfix Updates color when adding existing model element to diagram * Updates smart modeling of historical roles * BugFixes and updates menu ordering, menu access, and color scheme * Bugfix historicalRole rule * Updates «historicalRoleMixin» * Updates applicable stereotype based on generalization * Updates association constraints JSON file * Updates association constraints JSON file * Updates ReportErrorAction * Updates guides and bug report * Updates README * Updates images size * Updates report error URL * Updates README * Updates plugin update feature * Updates README * Bugfix default cardinalities * Updates situations support * Updates README Co-authored-by: Tiago Prince Sales Co-authored-by: Claudenir M. Fonseca * Plugin Update Automation (#61) * Retrieve releases from GitHub * Updates release download * Updates interfaces and download * Updates periodic lookup for new releases * Update plugin.xml and general bugfix * Bugfix * Improved plugin toolbar * Extracted nested classes from ViewUtils * General refactoring and update of releases serialization * Refactoring * Refactoring * Refactoring * BugFix Replaces ZonedDateTime serialization to strings * Refactoring * Refactoring * Fixed null pointer bug Co-authored-by: Tiago Prince Sales * Language Updates (#64) * Small fixes in the plugin * Updated restrictedTo dialog * Plugin version increased * Minor change to color defaults * Code refactoring * Renamed method * Added association constraints involving datatypes * Enable isExtensional based on restriction * Updates stereotypes to include isExtensional Know bugs: - Suggested «characterization» from «quality» to «event» - Sortals keep restrictions after generalizations are deleted - Changing the stereotype while isExtensional = true does not return the value to false. * Fixes smart paint for empty restrictedTo * Fix updates to isExtensional - Changes isExtensional to false when "collective" is not the unique value of restrictedTo - Prevents manual changes to isExtensional when prohibited * Fixed behavior on enabling/desabling menu options on the class contextual menu * Set navigability when applying a relation stereotype * Update navigability * Updates invert association * Updates meta-property menu: isAbstract and isDerived * Updates context menu for attributes * Adds source and target meta-property menus * Updates suggested stereotypes on both directions * Updates association inversion warning dialog * Added allowed associations by ontological nature * Applies association constraints based on nature restrictions * Code clean-up * Added Maven plugin for automatic code formatting * Add Github Action for styling the code in the Google Java Format * Google Java Format * BugFix invert association and reorganizes code * Google Java Format * Bugfixes * Updates labels and stereotype suggestion for multiple selected elements * Updates invertAssociation() and refactors code * Google Java Format * Bugfixes Co-authored-by: Tiago Prince Sales Co-authored-by: Claudenir Fonseca Co-authored-by: github-actions <> * Disables UI elements Disables duplicated "Invert Association" button * 0.4.0 Co-authored-by: Tiago Prince Sales Co-authored-by: Viola Co-authored-by: Victor Viola Co-authored-by: Tiago Prince Sales Co-authored-by: Tiago Prince Sales --- .github/workflows/maven.yml | 16 + .mvn/wrapper/MavenWrapperDownloader.java | 169 +- README.md | 24 +- {resources => docs}/faq-id-in-use.png | Bin {resources => docs}/feature-gufo.png | Bin .../feature-meta-properties.png | Bin {resources => docs}/feature-modeling.gif | Bin {resources => docs}/feature-restricte-to.png | Bin {resources => docs}/feature-smart-paint.png | Bin .../feature-suggested-stereotypes.png | Bin {resources => docs}/feature-toolbar.png | Bin {resources => docs}/feature-verification.gif | Bin .../install-plugin-dialog-folder-path.png | Bin {resources => docs}/install-plugin-dialog.png | Bin {resources => docs}/toolbar-help-install.png | Bin pom.xml | 24 +- .../unibz/inf/ontouml/vp/OntoUMLPlugin.java | 134 +- .../vp/controllers/ApplyProperties.java | 202 --- .../ApplyPropertiesController.java | 353 ++++ .../vp/controllers/ApplyStereotype.java | 363 ---- .../ApplyStereotypeController.java | 417 +++++ .../DiagramVerificationAction.java | 136 -- .../DiagramVerificationController.java | 128 ++ .../vp/controllers/ExportToGUFOAction.java | 249 --- .../vp/controllers/GUFOExportController.java | 231 +++ .../controllers/GitHubAccessController.java | 94 + .../vp/controllers/JsonExportController.java | 122 ++ .../vp/controllers/ModelActionController.java | 41 + .../vp/controllers/ModelExportAction.java | 125 -- .../controllers/ModelVerificationAction.java | 119 -- .../ModelVerificationController.java | 112 ++ .../OntoUMLServerAccessController.java | 287 +++ .../controllers/OpenConfigurationsAction.java | 123 -- .../vp/controllers/PaintModelAction.java | 37 - .../ReloadClassesActionController.java | 19 - .../controllers/ReloadClassesController.java | 123 ++ .../vp/controllers/ReportErrorAction.java | 36 - .../vp/controllers/ReportErrorController.java | 33 + .../controllers/SettingsMenuController.java | 95 + .../controllers/SmartModellingController.java | 70 + .../vp/controllers/UpdatePluginAction.java | 114 -- .../controllers/UpdatePluginController.java | 111 ++ .../vp/features/constraints/ActionIds.java | 210 --- .../constraints/AssociationConstraints.java | 84 - .../constraints/ClassConstraints.java | 92 - .../ontouml/vp/listeners/DiagramListener.java | 108 +- .../vp/listeners/IssueLogMenuListener.java | 53 + .../ontouml/vp/listeners/ModelListener.java | 473 ++--- .../vp/listeners/ProjectDiagramListener.java | 101 +- .../ontouml/vp/listeners/ProjectListener.java | 188 +- .../vp/listeners/ProjectModelListener.java | 92 +- .../inf/ontouml/vp/model/Association.java | 214 --- .../ontouml/vp/model/AssociationClass.java | 183 -- .../vp/model/AssociationModelDescription.java | 112 ++ .../it/unibz/inf/ontouml/vp/model/Class.java | 621 ------- .../inf/ontouml/vp/model/Configurations.java | 240 +++ .../inf/ontouml/vp/model/Generalization.java | 129 -- .../ontouml/vp/model/GeneralizationSet.java | 190 -- .../inf/ontouml/vp/model/GitHubRelease.java | 102 ++ .../ontouml/vp/model/GitHubReleaseAsset.java | 70 + .../unibz/inf/ontouml/vp/model/Literal.java | 80 - .../it/unibz/inf/ontouml/vp/model/Model.java | 387 ---- .../inf/ontouml/vp/model/ModelElement.java | 232 --- .../unibz/inf/ontouml/vp/model/Package.java | 228 --- .../vp/model/ProjectConfigurations.java | 428 +++++ .../unibz/inf/ontouml/vp/model/Property.java | 385 ---- .../ontouml/vp/model/PropertyDescription.java | 67 + .../unibz/inf/ontouml/vp/model/Reference.java | 45 - .../inf/ontouml/vp/model/ServerRequest.java | 17 + .../inf/ontouml/vp/model/uml/Association.java | 530 ++++++ .../vp/model/uml/AssociationClass.java | 175 ++ .../unibz/inf/ontouml/vp/model/uml/Class.java | 674 +++++++ .../ontouml/vp/model/uml/Generalization.java | 126 ++ .../vp/model/uml/GeneralizationSet.java | 183 ++ .../inf/ontouml/vp/model/uml/Literal.java | 80 + .../unibz/inf/ontouml/vp/model/uml/Model.java | 361 ++++ .../ontouml/vp/model/uml/ModelElement.java | 426 +++++ .../inf/ontouml/vp/model/uml/Package.java | 212 +++ .../inf/ontouml/vp/model/uml/Property.java | 455 +++++ .../inf/ontouml/vp/model/uml/Reference.java | 41 + .../inf/ontouml/vp/utils/ActionIdManager.java | 325 ++++ .../ontouml/vp/utils/CollectionAdapter.java | 29 - .../inf/ontouml/vp/utils/Configurations.java | 156 -- .../vp/utils/OntoUMLConstraintsManager.java | 143 ++ .../ontouml/vp/utils/OntoUMLServerUtils.java | 233 --- .../vp/utils/ProjectConfigurations.java | 467 ----- .../inf/ontouml/vp/utils/RestrictedTo.java | 168 ++ .../inf/ontouml/vp/utils/ServerRequest.java | 18 - .../inf/ontouml/vp/utils/SmartColoring.java | 164 -- .../ontouml/vp/utils/SmartColoringUtils.java | 154 ++ .../inf/ontouml/vp/utils/SmartModelling.java | 324 ---- .../inf/ontouml/vp/utils/Stereotype.java | 135 ++ .../inf/ontouml/vp/utils/StereotypeUtils.java | 567 ------ .../ontouml/vp/utils/StereotypesManager.java | 302 ++++ .../ontouml/vp/utils/ViewManagerUtils.java | 772 ++++++++ .../unibz/inf/ontouml/vp/utils/ViewUtils.java | 693 -------- .../ontouml/vp/views/ConfigurationsView.java | 463 +++-- .../ontouml/vp/views/ExportToGUFOView.java | 974 ----------- .../inf/ontouml/vp/views/GUFOExportView.java | 1004 +++++++++++ .../ontouml/vp/views/HTMLEnabledMessage.java | 85 +- .../inf/ontouml/vp/views/IssueLogMenu.java | 63 + .../inf/ontouml/vp/views/JCheckBoxTree.java | 1554 +++++++++-------- .../unibz/inf/ontouml/vp/views/NameUtil.java | 81 - .../inf/ontouml/vp/views/ProgressPanel.java | 96 +- .../vp/views/SelectMultipleOptionsDialog.java | 202 --- .../vp/views/SelectRestrictionsView.java | 160 ++ .../inf/ontouml/vp/views/SetOrderDialog.java | 152 -- .../inf/ontouml/vp/views/SetOrderView.java | 182 ++ .../resources/association_constraints.json | 134 +- .../association_constraints_nature.json | 123 ++ .../resources/generalization_constraints.json | 16 +- src/main/resources/plugin.xml | 332 ++-- 112 files changed, 12230 insertions(+), 10542 deletions(-) create mode 100644 .github/workflows/maven.yml rename {resources => docs}/faq-id-in-use.png (100%) rename {resources => docs}/feature-gufo.png (100%) rename {resources => docs}/feature-meta-properties.png (100%) rename {resources => docs}/feature-modeling.gif (100%) rename {resources => docs}/feature-restricte-to.png (100%) rename {resources => docs}/feature-smart-paint.png (100%) rename {resources => docs}/feature-suggested-stereotypes.png (100%) rename {resources => docs}/feature-toolbar.png (100%) rename {resources => docs}/feature-verification.gif (100%) rename {resources => docs}/install-plugin-dialog-folder-path.png (100%) rename {resources => docs}/install-plugin-dialog.png (100%) rename {resources => docs}/toolbar-help-install.png (100%) delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyProperties.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyPropertiesController.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotype.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotypeController.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationAction.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationController.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ExportToGUFOAction.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/GUFOExportController.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/GitHubAccessController.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/JsonExportController.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelActionController.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelExportAction.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationAction.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationController.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/OntoUMLServerAccessController.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/OpenConfigurationsAction.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/PaintModelAction.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesActionController.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesController.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorAction.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorController.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/SettingsMenuController.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/SmartModellingController.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginAction.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginController.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/features/constraints/ActionIds.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/features/constraints/AssociationConstraints.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/features/constraints/ClassConstraints.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/listeners/IssueLogMenuListener.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Association.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/AssociationClass.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/AssociationModelDescription.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Class.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Configurations.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Generalization.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/GeneralizationSet.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/GitHubRelease.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/GitHubReleaseAsset.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Literal.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Model.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/ModelElement.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Package.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/ProjectConfigurations.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Property.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/PropertyDescription.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/Reference.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/ServerRequest.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/Association.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/AssociationClass.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/Class.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/Generalization.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/GeneralizationSet.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/Literal.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/Model.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/ModelElement.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/Package.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/Property.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/uml/Reference.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/ActionIdManager.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/CollectionAdapter.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/Configurations.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLConstraintsManager.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLServerUtils.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/ProjectConfigurations.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/RestrictedTo.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/ServerRequest.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoring.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoringUtils.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/SmartModelling.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/Stereotype.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypeUtils.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypesManager.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/ViewManagerUtils.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/ViewUtils.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/views/ExportToGUFOView.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/views/GUFOExportView.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/views/IssueLogMenu.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/views/NameUtil.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/views/SelectMultipleOptionsDialog.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/views/SelectRestrictionsView.java delete mode 100644 src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderDialog.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderView.java create mode 100644 src/main/resources/association_constraints_nature.json diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 00000000..45ea0ab0 --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,16 @@ +name: Google Java Format + +on: [push] + +jobs: + + formatting: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 # v2 minimum required + - uses: actions/setup-java@v1 + with: + java-version: 11 + - uses: axel-op/googlejavaformat-action@v3 + with: + args: "--replace" diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java index b901097f..9ac51e49 100644 --- a/.mvn/wrapper/MavenWrapperDownloader.java +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -13,105 +13,106 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import java.net.*; import java.io.*; +import java.net.*; import java.nio.channels.*; import java.util.Properties; public class MavenWrapperDownloader { - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; + private static final String WRAPPER_VERSION = "0.5.6"; + /** Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + + "/maven-wrapper-" + + WRAPPER_VERSION + + ".jar"; - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use + * instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + /** Path where the maven-wrapper.jar will be saved to. */ + private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); + if (mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... } + } } + System.out.println("- Downloading from: " + url); - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) { + if (!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + + outputFile.getParentFile().getAbsolutePath() + + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); } + } + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault( + new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } } diff --git a/README.md b/README.md index 97f63221..32a39489 100644 --- a/README.md +++ b/README.md @@ -35,13 +35,13 @@ Stereotypes and meta-properties that are essential to OntoUML modeling are easil Notice that beyond the full list of stereotypes, a dynamic list of stereotypes is also available. This dynamic list is usually preferred during modeling as it filters wrong stereotypes for your class or association based on, respectively, their super/sub classes and their associated classes. The full list, however, tends to provide a faster and more flexible option during model fixing and refactoring. -![GIF showing a OntoUML model being edited](./resources/feature-modeling.gif) +![GIF showing a OntoUML model being edited](./docs/feature-modeling.gif) -![A screenshot of a suggested list of stereotypes in a context menu](./resources/feature-suggested-stereotypes.png) +![A screenshot of a suggested list of stereotypes in a context menu](./docs/feature-suggested-stereotypes.png) -![A screenshot of meta-properties editing in context menu](./resources/feature-meta-properties.png) +![A screenshot of meta-properties editing in context menu](./docs/feature-meta-properties.png) -![A screenshot of restricted instances menu selection](./resources/feature-restricte-to.png) +![A screenshot of restricted instances menu selection](./docs/feature-restricte-to.png) Try selecting multiple elements to fast update your models! @@ -49,7 +49,7 @@ Try selecting multiple elements to fast update your models! Automatic diagram painting based on the possible instances of classes with highlighted ultimate sortals (i.e., «kind», «collective», «quantity», «relator», «mode», and «quality») for improved model readability. -![A screenshot of an automatically painted diagram](./resources/feature-smart-paint.png) +![A screenshot of an automatically painted diagram](./docs/feature-smart-paint.png) #### Smart Modeling @@ -63,7 +63,7 @@ Automatic verification of OntoUML syntactical rules which are reported to the us The Diagram Verification feature performs the verification of the whole model but only displays issues about elements present in the currently open diagram, facilitating the user's task of fixing models. -![A gif exemplifying the model verification feature](./resources/feature-verification.gif) +![A gif exemplifying the model verification feature](./docs/feature-verification.gif) #### Model Transformation to OWL with gUFO @@ -73,7 +73,7 @@ Users must select the elements that shall be exported to gUFO either selecting f **WARNING**: the transformation feature require the presence of no verification errors among the exported entities. In addition, partial transformations of the model should be executed with care as they may introduce violations of some syntactical constraint. -![A screenshot showing the "transformation to gUFO" window](./resources/feature-gufo.png) +![A screenshot showing the "transformation to gUFO" window](./docs/feature-gufo.png) #### Continuous Updates @@ -81,7 +81,7 @@ The cloud-based features offered in the plugin are periodically updated. Updates And last, but not least, this project is supported by the [OntoUML.org](https://ontouml.org/) community and its set of features will only grow, incorporating new and updated OntoUML technologies. -![A screenshot showing the toolbar of the OntoUML plugin](./resources/feature-toolbar.png) +![A screenshot showing the toolbar of the OntoUML plugin](./docs/feature-toolbar.png) In order to update to a new version of the plugin, please download the latest [release](https://github.com/OntoUML/ontouml-vp-plugin/releases) as a ZIP file and select it through the "Update Plugin" button in the plugin (available from version 0.3.0). @@ -93,9 +93,9 @@ ___ To **install** or **update** the **OntoUML Plugin for Visual Paradigm**, please go to our [releases page](https://github.com/OntoUML/ontouml-vp-plugin/releases) and download the ZIP file `ontouml-vp-plugin` in the latest release. Then go to `Help > Install Plugin` in the top of your window and, after clicking `Install from a zip of plugin` and `Next`, select the download release. -![Install plugin window](./resources/toolbar-help-install.png) +![Install plugin window](./docs/toolbar-help-install.png) -![Install plugin window](./resources/install-plugin-dialog.png) +![Install plugin window](./docs/install-plugin-dialog.png) For more details, check out this [guide](https://knowhow.visual-paradigm.com/openapi/how-to-deploy-plugins-to-vp-application/). @@ -229,11 +229,11 @@ ___ ### Why do I get the error message "The ID [...] is already in use"? -![Error message: ID already in use](./resources/faq-id-in-use.png) +![Error message: ID already in use](./docs/faq-id-in-use.png) Each Visual Paradigm plugin must (i) have an ID, and (ii) be installed in a specific folder. If you are updating to a new version of the plugin, it may occur that the name of the folder has changed. In this case, Visual Paradigm will think that you are trying to install a new plugin with an ID already in use instead of updating it. -![Install plugin window](./resources/install-plugin-dialog-folder-path.png) +![Install plugin window](./docs/install-plugin-dialog-folder-path.png) To solve this issue, go to the `plugins` folder listed in the "Install Plugin" window (see above) and delete your old plugin folder before installing the new version. You may be required to re-open the application for that to take effect. diff --git a/resources/faq-id-in-use.png b/docs/faq-id-in-use.png similarity index 100% rename from resources/faq-id-in-use.png rename to docs/faq-id-in-use.png diff --git a/resources/feature-gufo.png b/docs/feature-gufo.png similarity index 100% rename from resources/feature-gufo.png rename to docs/feature-gufo.png diff --git a/resources/feature-meta-properties.png b/docs/feature-meta-properties.png similarity index 100% rename from resources/feature-meta-properties.png rename to docs/feature-meta-properties.png diff --git a/resources/feature-modeling.gif b/docs/feature-modeling.gif similarity index 100% rename from resources/feature-modeling.gif rename to docs/feature-modeling.gif diff --git a/resources/feature-restricte-to.png b/docs/feature-restricte-to.png similarity index 100% rename from resources/feature-restricte-to.png rename to docs/feature-restricte-to.png diff --git a/resources/feature-smart-paint.png b/docs/feature-smart-paint.png similarity index 100% rename from resources/feature-smart-paint.png rename to docs/feature-smart-paint.png diff --git a/resources/feature-suggested-stereotypes.png b/docs/feature-suggested-stereotypes.png similarity index 100% rename from resources/feature-suggested-stereotypes.png rename to docs/feature-suggested-stereotypes.png diff --git a/resources/feature-toolbar.png b/docs/feature-toolbar.png similarity index 100% rename from resources/feature-toolbar.png rename to docs/feature-toolbar.png diff --git a/resources/feature-verification.gif b/docs/feature-verification.gif similarity index 100% rename from resources/feature-verification.gif rename to docs/feature-verification.gif diff --git a/resources/install-plugin-dialog-folder-path.png b/docs/install-plugin-dialog-folder-path.png similarity index 100% rename from resources/install-plugin-dialog-folder-path.png rename to docs/install-plugin-dialog-folder-path.png diff --git a/resources/install-plugin-dialog.png b/docs/install-plugin-dialog.png similarity index 100% rename from resources/install-plugin-dialog.png rename to docs/install-plugin-dialog.png diff --git a/resources/toolbar-help-install.png b/docs/toolbar-help-install.png similarity index 100% rename from resources/toolbar-help-install.png rename to docs/toolbar-help-install.png diff --git a/pom.xml b/pom.xml index b997b2c3..d6ddf9e5 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ it.unibz.inf.ontouml ontouml-vp-plugin - 0.3.1-SNAPSHOT + 0.4.0 OntoUML 2 Plugin for Visual Paradigm @@ -178,8 +178,8 @@ maven-compiler-plugin 3.8.1 - 1.8 - 1.8 + 11 + 11 @@ -253,6 +253,24 @@ + + com.coveo + fmt-maven-plugin + 2.10 + + true + false + + + + + process-sources + + format + + + + diff --git a/src/main/java/it/unibz/inf/ontouml/vp/OntoUMLPlugin.java b/src/main/java/it/unibz/inf/ontouml/vp/OntoUMLPlugin.java index 303a1f50..1eb9eb50 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/OntoUMLPlugin.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/OntoUMLPlugin.java @@ -4,91 +4,71 @@ import com.vp.plugin.ProjectManager; import com.vp.plugin.VPPlugin; import com.vp.plugin.VPPluginInfo; -import com.vp.plugin.model.IModelElement; import com.vp.plugin.model.IProject; -import com.vp.plugin.model.factory.IModelElementFactory; - import it.unibz.inf.ontouml.vp.listeners.ProjectListener; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; /** - * Implementation of VPPlugin responsible for configuring OntoUML Plugin's - * behaviour when loading and unload. + * Implementation of VPPlugin responsible for configuring OntoUML Plugin's behaviour when loading + * and unload. * * @author Victor Viola * @author Claudenir Fonseca */ public class OntoUMLPlugin implements VPPlugin { - public static final String PLUGIN_VERSION_RELEASE = "0.3.1"; - public static final String PLUGIN_ID = "it.unibz.inf.ontouml.vp"; - public static final String PLUGIN_NAME = "OntoUML Plugin"; - public static final String PLUGIN_REPO = "https://github.com/OntoUML/ontouml-vp-plugin/"; - - public static IModelElement[] allModelElements; - public static boolean isPluginActive; - - private static boolean isExportToGUFOWindowOpen; - private static boolean isConfigWindowOpen; - private static ProjectListener projectListener; - - /** - * OntoUMLPlugin constructor. Declared to make explicit Open API requirements. - */ - public OntoUMLPlugin() { - // The constructor of a VPPlugin MUST NOT have parameters. - isExportToGUFOWindowOpen = false; - isConfigWindowOpen = false; - System.out.println("OntoUML Plugin (v" + PLUGIN_VERSION_RELEASE +") loaded successfully."); - } - - /** - * Called by Visual Paradigm when the plugin is loaded. - * - * @param pluginInfo - */ - @Override - public void loaded(VPPluginInfo pluginInfo) { - final ProjectManager pm = ApplicationManager.instance().getProjectManager(); - final IProject p = pm.getProject(); - - projectListener = new ProjectListener(); - p.addProjectListener(projectListener); - - OntoUMLPlugin.allModelElements = - pm.getSelectableStereotypesForModelType(IModelElementFactory.MODEL_TYPE_CLASS, p, true); - } - - /** - * Called by Visual Paradigm when the plugin is unloaded (i.e., Visual Paradigm - * will be exited). This method is not called when the plugin is reloaded. - */ - @Override - public void unloaded() { - } - - public static void setExportToGUFOWindowOpen(boolean open) { - isExportToGUFOWindowOpen = open; - - } - - public static boolean getExportToGUFOWindowOpen() { - return isExportToGUFOWindowOpen; - } - - public static void setConfigWindowOpen(boolean open) { - isConfigWindowOpen = open; - - } - - public static boolean getConfigWindowOpen() { - return isConfigWindowOpen; - } - - public static void reload() { - ViewUtils.log("Reloading plugin: "+PLUGIN_ID); - ApplicationManager.instance().reloadPluginClasses(PLUGIN_ID); - // TODO: try to integrate listener to the reload process - } - + public static final String PLUGIN_VERSION_RELEASE = "0.4.0"; + public static final String PLUGIN_ID = "it.unibz.inf.ontouml.vp"; + public static final String PLUGIN_NAME = "OntoUML Plugin"; + public static final String PLUGIN_REPO = "https://github.com/OntoUML/ontouml-vp-plugin/"; + public static final String PLUGIN_REPO_OWNER = "OntoUML"; + public static final String PLUGIN_REPO_NAME = "ontouml-vp-plugin"; + + private static boolean isExportToGUFOWindowOpen; + private static boolean isConfigWindowOpen; + private static ProjectListener projectListener; + + /** OntoUMLPlugin constructor. Declared to make explicit Open API requirements. */ + public OntoUMLPlugin() { + // The constructor of a VPPlugin MUST NOT have parameters. + isExportToGUFOWindowOpen = false; + isConfigWindowOpen = false; + System.out.println("OntoUML Plugin (v" + PLUGIN_VERSION_RELEASE + ") loaded successfully."); + } + + /** + * Called by Visual Paradigm when the plugin is loaded. + * + * @param pluginInfo + */ + @Override + public void loaded(VPPluginInfo pluginInfo) { + final ProjectManager pm = ApplicationManager.instance().getProjectManager(); + final IProject p = pm.getProject(); + + projectListener = new ProjectListener(); + p.addProjectListener(projectListener); + } + + /** + * Called by Visual Paradigm when the plugin is unloaded (i.e., Visual Paradigm will be exited). + * This method is not called when the plugin is reloaded. + */ + @Override + public void unloaded() {} + + public static void setExportToGUFOWindowOpen(boolean open) { + isExportToGUFOWindowOpen = open; + } + + public static boolean getExportToGUFOWindowOpen() { + return isExportToGUFOWindowOpen; + } + + public static void setConfigWindowOpen(boolean open) { + isConfigWindowOpen = open; + } + + public static boolean getConfigWindowOpen() { + return isConfigWindowOpen; + } } diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyProperties.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyProperties.java deleted file mode 100644 index 89f7f66b..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyProperties.java +++ /dev/null @@ -1,202 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import java.awt.event.ActionEvent; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPContext; -import com.vp.plugin.action.VPContextActionController; -import com.vp.plugin.diagram.IDiagramElement; -import com.vp.plugin.diagram.IDiagramUIModel; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.ITaggedValue; -import com.vp.plugin.model.factory.IModelElementFactory; - -import it.unibz.inf.ontouml.vp.features.constraints.ActionIds; -import it.unibz.inf.ontouml.vp.model.Class; -import it.unibz.inf.ontouml.vp.model.ModelElement; -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; -import it.unibz.inf.ontouml.vp.views.SelectMultipleOptionsDialog; -import it.unibz.inf.ontouml.vp.views.SetOrderDialog; - -/** - * Implementation of context sensitive action of change OntoUML stereotypes in model elements. - * - * @author Claudenir Fonseca - * @author Victor Viola - */ -public class ApplyProperties implements VPContextActionController { - - @Override - public void performAction(VPAction action, VPContext context, ActionEvent event) { - if ( - context.getModelElement() == null || - !(context.getModelElement() instanceof IClass) - ) { - return ; - } - - final IClass clickedClass = (IClass) context.getModelElement(); - - switch (action.getActionId()) { - case ActionIds.PROPERTY_SET_RESTRICTED_TO: - this.setRestrictedTo(context, clickedClass); - break; - - case ActionIds.PROPERTY_SET_IS_ABSTRACT: - final boolean isAbstract = clickedClass.isAbstract(); - forEachSelectedClass(context, cla -> cla.setAbstract(!isAbstract)); - break; - - case ActionIds.PROPERTY_SET_IS_DERIVED: - final boolean isDerived = ModelElement.getIsDerived(clickedClass); - forEachSelectedClass(context, selected -> { - ModelElement.setIsDerived(selected, !isDerived); - }); - break; - case ActionIds.PROPERTY_SET_IS_EXTENSIONAL: - setBooleanTaggedValue(context, clickedClass, StereotypeUtils.PROPERTY_IS_EXTENSIONAL); - break; - - case ActionIds.PROPERTY_SET_IS_POWERTYPE: - setBooleanTaggedValue(context, clickedClass, StereotypeUtils.PROPERTY_IS_POWERTYPE); - break; - - case ActionIds.PROPERTY_SET_ORDER: - setOrderProperty(context, clickedClass); - break; - } - } - - @Override - public void update(VPAction action, VPContext context) { - if ( - context.getModelElement() == null || - !(context.getModelElement() instanceof IClass) - ) { - return ; - } - - final IClass _class = (IClass) context.getModelElement(); - final String stereotype = StereotypeUtils.getUniqueStereotypeName(_class); - final Set allClassStereotypes = StereotypeUtils.getOntoUMLClassStereotypeNames(); - - switch (action.getActionId()) { - case ActionIds.PROPERTY_SET_RESTRICTED_TO: - if (allClassStereotypes.contains(stereotype)) { - final boolean isSmartModelingEnabled = - Configurations.getInstance() - .getProjectConfigurations() - .isSmartModellingEnabled(); - final List nonFixedRestrictedTo = - Arrays.asList(StereotypeUtils.STR_CATEGORY, - StereotypeUtils.STR_MIXIN, - StereotypeUtils.STR_PHASE_MIXIN, - StereotypeUtils.STR_ROLE_MIXIN, - StereotypeUtils.STR_HISTORICAL_ROLE_MIXIN); - - action.setEnabled(!isSmartModelingEnabled || - nonFixedRestrictedTo.contains(stereotype)); - } else { - action.setEnabled(false); - } - break; - case ActionIds.PROPERTY_SET_IS_ABSTRACT: - action.setEnabled(true); - action.setSelected(_class.isAbstract()); - break; - case ActionIds.PROPERTY_SET_IS_DERIVED: - action.setEnabled(true); - action.setSelected(ModelElement.getIsDerived(_class)); - break; - case ActionIds.PROPERTY_SET_IS_EXTENSIONAL: - action.setEnabled(StereotypeUtils.STR_COLLECTIVE.equals(stereotype)); - action.setSelected(Class.getIsExtensional(_class)); - break; - case ActionIds.PROPERTY_SET_IS_POWERTYPE: - action.setEnabled(StereotypeUtils.STR_TYPE.equals(stereotype)); - action.setSelected(Class.getIsPowertype(_class)); - break; - case ActionIds.PROPERTY_SET_ORDER: - action.setEnabled(_class.hasStereotype(StereotypeUtils.STR_TYPE)); - break; - } - } - - private void forEachSelectedClass(VPContext context, Consumer consumer) { - if (!(context.getModelElement() instanceof IClass)) - return; - - final IDiagramUIModel diagram = context.getDiagram(); - final IClass _class = (IClass) context.getModelElement(); - - if(diagram == null) { - consumer.accept(_class); - return ; - } - - final IDiagramElement[] diagramElements = context.getDiagram() - .getSelectedDiagramElement(); - - Arrays.stream(diagramElements) - .filter(e -> e.getModelElement().getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS)) - .map(e -> (IClass) e.getModelElement()) - .forEach(consumer); - } - - private void setBooleanTaggedValue(VPContext context, IClass clickedClass, String metaProperty) { - final ITaggedValue booleanTaggedValue = StereotypeUtils.reapplyStereotypeAndGetTaggedValue(clickedClass, metaProperty); - final boolean value = booleanTaggedValue != null && Boolean.parseBoolean(booleanTaggedValue.getValueAsString()); - - forEachSelectedClass(context, cla -> { - ITaggedValue taggedValue = StereotypeUtils.reapplyStereotypeAndGetTaggedValue(cla, metaProperty); - - if (taggedValue == null) - return; - - taggedValue.setValue(!value); - }); - } - - private void setOrderProperty(VPContext context, IClass clickedClass) { - final ITaggedValue baseTaggedValue = - StereotypeUtils.reapplyStereotypeAndGetTaggedValue(clickedClass, StereotypeUtils.PROPERTY_ORDER); - - if (baseTaggedValue == null) - return; - - final SetOrderDialog dialog = new SetOrderDialog(baseTaggedValue.getValueAsString()); - ApplicationManager.instance().getViewManager().showDialog(dialog); - final String order = dialog.getOrder(); - - forEachSelectedClass(context, cla -> { - ITaggedValue taggedValue = StereotypeUtils.reapplyStereotypeAndGetTaggedValue(cla, StereotypeUtils.PROPERTY_ORDER); - - if (taggedValue == null) - return; - - taggedValue.setValue(order); - }); - } - - private void setRestrictedTo(VPContext context, IClass clickedClass) { - System.out.println("\nClicked class: " + clickedClass.getName()); - String currentRestrictions = Class.getRestrictedTo(clickedClass); - currentRestrictions = currentRestrictions == null ? "" : currentRestrictions; - - final SelectMultipleOptionsDialog dialog = new SelectMultipleOptionsDialog(currentRestrictions); - ApplicationManager.instance().getViewManager().showDialog(dialog); - final String newRestrictions = dialog.getSelectedValues(); - - forEachSelectedClass(context, cla -> { - System.out.println("setRestrictedTo on class: " + cla.getName()); - Class.setRestrictedTo(cla, newRestrictions); - }); - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyPropertiesController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyPropertiesController.java new file mode 100644 index 00000000..452f2a89 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyPropertiesController.java @@ -0,0 +1,353 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPContext; +import com.vp.plugin.action.VPContextActionController; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IAssociationEnd; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.ITaggedValue; +import com.vp.plugin.model.factory.IModelElementFactory; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.uml.Association; +import it.unibz.inf.ontouml.vp.model.uml.Class; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.utils.ActionIdManager; +import it.unibz.inf.ontouml.vp.utils.RestrictedTo; +import it.unibz.inf.ontouml.vp.utils.StereotypesManager; +import it.unibz.inf.ontouml.vp.views.SelectRestrictionsView; +import it.unibz.inf.ontouml.vp.views.SetOrderView; +import java.awt.event.ActionEvent; +import java.util.List; + +/** + * Implementation of context sensitive action of change OntoUML stereotypes in model elements. + * + * @author Claudenir Fonseca + * @author Victor Viola + */ +public class ApplyPropertiesController implements VPContextActionController { + + @Override + public void performAction(VPAction action, VPContext context, ActionEvent event) { + final IModelElement clickedElement = context.getModelElement(); + final String clickedElementType = clickedElement.getModelType(); + + if (!IModelElementFactory.MODEL_TYPE_ASSOCIATION.equals(clickedElementType) + && !IModelElementFactory.MODEL_TYPE_ASSOCIATION_END.equals(clickedElementType) + && !IModelElementFactory.MODEL_TYPE_ATTRIBUTE.equals(clickedElementType) + && !IModelElementFactory.MODEL_TYPE_CLASS.equals(clickedElementType)) { + return; + } + + final IAssociation clickedAssociation = + IModelElementFactory.MODEL_TYPE_ASSOCIATION.equals(clickedElementType) + ? (IAssociation) context.getModelElement() + : null; + final IClass clickedClass = + IModelElementFactory.MODEL_TYPE_CLASS.equals(clickedElementType) + ? (IClass) context.getModelElement() + : null; + + switch (action.getActionId()) { + case ActionIdManager.CLASS_PROPERTY_SET_RESTRICTED_TO: + this.setRestrictedTo(clickedClass); + break; + + case ActionIdManager.ASSOCIATION_PROPERTY_SET_IS_ABSTRACT: + case ActionIdManager.CLASS_PROPERTY_SET_IS_ABSTRACT: + { + final boolean isAbstract = ModelElement.isAbstract(clickedElement); + ModelElement.forEachSelectedElement( + clickedElement, + selectedElement -> ModelElement.setAbstract(selectedElement, !isAbstract)); + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_SET_IS_DERIVED: + case ActionIdManager.CLASS_PROPERTY_SET_IS_DERIVED: + { + final boolean isDerived = ModelElement.isDerived(clickedElement); + ModelElement.forEachSelectedElement( + clickedElement, + selectedElement -> ModelElement.setDerived(selectedElement, !isDerived)); + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_SOURCE_SET_IS_DERIVED: + { + final IAssociationEnd sourceEnd = Association.getSourceEnd(clickedAssociation); + sourceEnd.setDerived(!sourceEnd.isDerived()); + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_TARGET_SET_IS_DERIVED: + { + final IAssociationEnd targetEnd = Association.getTargetEnd(clickedAssociation); + targetEnd.setDerived(!targetEnd.isDerived()); + break; + } + + case ActionIdManager.ATTRIBUTE_PROPERTY_SET_IS_DERIVED: + { + final boolean isDerived = ModelElement.isDerived(clickedElement); + ModelElement.setDerived(clickedElement, !isDerived); + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_SOURCE_SET_IS_ORDERED: + { + final IAssociationEnd sourceEnd = Association.getSourceEnd(clickedAssociation); + ModelElement.setOrdered(sourceEnd, !ModelElement.isOrdered(sourceEnd)); + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_TARGET_SET_IS_ORDERED: + { + final IAssociationEnd targetEnd = Association.getTargetEnd(clickedAssociation); + ModelElement.setOrdered(targetEnd, !ModelElement.isOrdered(targetEnd)); + break; + } + + case ActionIdManager.ATTRIBUTE_PROPERTY_SET_IS_ORDERED: + { + final boolean isOrdered = ModelElement.isOrdered(clickedElement); + ModelElement.setOrdered(clickedElement, !isOrdered); + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_SOURCE_SET_IS_READ_ONLY: + { + final IAssociationEnd sourceEnd = Association.getSourceEnd(clickedAssociation); + ModelElement.setReadOnly(sourceEnd, !ModelElement.isReadOnly(sourceEnd)); + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_TARGET_SET_IS_READ_ONLY: + { + final IAssociationEnd targetEnd = Association.getTargetEnd(clickedAssociation); + ModelElement.setReadOnly(targetEnd, !ModelElement.isReadOnly(targetEnd)); + break; + } + + case ActionIdManager.ATTRIBUTE_PROPERTY_SET_IS_READ_ONLY: + { + final boolean isReadOnly = ModelElement.isReadOnly(clickedElement); + ModelElement.setReadOnly(clickedElement, !isReadOnly); + break; + } + + case ActionIdManager.CLASS_PROPERTY_SET_IS_EXTENSIONAL: + setBooleanTaggedValue(clickedClass, StereotypesManager.PROPERTY_IS_EXTENSIONAL); + break; + + case ActionIdManager.CLASS_PROPERTY_SET_IS_POWERTYPE: + setBooleanTaggedValue(clickedClass, StereotypesManager.PROPERTY_IS_POWERTYPE); + break; + + case ActionIdManager.CLASS_PROPERTY_SET_ORDER: + setOrderProperty(clickedClass); + break; + } + } + + @Override + public void update(VPAction action, VPContext context) { + final IModelElement clickedElement = context.getModelElement(); + final String clickedElementType = clickedElement.getModelType(); + + if (!IModelElementFactory.MODEL_TYPE_ASSOCIATION.equals(clickedElementType) + && !IModelElementFactory.MODEL_TYPE_ASSOCIATION_END.equals(clickedElementType) + && !IModelElementFactory.MODEL_TYPE_ATTRIBUTE.equals(clickedElementType) + && !IModelElementFactory.MODEL_TYPE_CLASS.equals(clickedElementType)) { + action.setEnabled(false); + return; + } + + final IClass clickedClass = + IModelElementFactory.MODEL_TYPE_CLASS.equals(clickedElementType) + ? (IClass) context.getModelElement() + : null; + final IAssociation clickedAssociation = + IModelElementFactory.MODEL_TYPE_ASSOCIATION.equals(clickedElementType) + ? (IAssociation) context.getModelElement() + : null; + final boolean isSmartModelingEnabled = + Configurations.getInstance().getProjectConfigurations().isSmartModellingEnabled(); + boolean enabled = true; + + switch (action.getActionId()) { + case ActionIdManager.ASSOCIATION_PROPERTY_SET_IS_ABSTRACT: + action.setSelected(ModelElement.isAbstract(clickedElement)); + break; + + case ActionIdManager.CLASS_PROPERTY_SET_IS_ABSTRACT: + action.setSelected(clickedClass.isAbstract()); + enabled = Class.isAbstractEditable(clickedClass) || !isSmartModelingEnabled; + break; + + case ActionIdManager.ASSOCIATION_PROPERTY_SOURCE_SET_IS_DERIVED: + { + final IAssociationEnd sourceEnd = Association.getSourceEnd(clickedAssociation); + action.setSelected(sourceEnd.isDerived()); + enabled = true; + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_TARGET_SET_IS_DERIVED: + { + final IAssociationEnd targetEnd = Association.getTargetEnd(clickedAssociation); + action.setSelected(targetEnd.isDerived()); + enabled = true; + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_SET_IS_DERIVED: + case ActionIdManager.ATTRIBUTE_PROPERTY_SET_IS_DERIVED: + case ActionIdManager.CLASS_PROPERTY_SET_IS_DERIVED: + action.setSelected(ModelElement.isDerived(clickedElement)); + enabled = true; + break; + + case ActionIdManager.ASSOCIATION_PROPERTY_SOURCE_SET_IS_ORDERED: + { + final IAssociationEnd sourceEnd = Association.getSourceEnd(clickedAssociation); + action.setSelected(ModelElement.isOrdered(sourceEnd)); + enabled = true; + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_TARGET_SET_IS_ORDERED: + { + final IAssociationEnd targetEnd = Association.getTargetEnd(clickedAssociation); + action.setSelected(ModelElement.isOrdered(targetEnd)); + enabled = true; + break; + } + + case ActionIdManager.ATTRIBUTE_PROPERTY_SET_IS_ORDERED: + action.setSelected(ModelElement.isOrdered(clickedElement)); + enabled = true; + break; + + case ActionIdManager.ASSOCIATION_PROPERTY_SOURCE_SET_IS_READ_ONLY: + { + final IAssociationEnd sourceEnd = Association.getSourceEnd(clickedAssociation); + action.setSelected(ModelElement.isReadOnly(sourceEnd)); + enabled = true; + break; + } + + case ActionIdManager.ASSOCIATION_PROPERTY_TARGET_SET_IS_READ_ONLY: + { + final IAssociationEnd targetEnd = Association.getTargetEnd(clickedAssociation); + action.setSelected(ModelElement.isReadOnly(targetEnd)); + enabled = true; + break; + } + + case ActionIdManager.ATTRIBUTE_PROPERTY_SET_IS_READ_ONLY: + action.setSelected(ModelElement.isReadOnly(clickedElement)); + enabled = true; + break; + + case ActionIdManager.CLASS_PROPERTY_SET_RESTRICTED_TO: + enabled = + Class.isRestrictedToEditable(clickedClass) + || (!isSmartModelingEnabled && Class.hasValidStereotype(clickedClass)); + break; + + case ActionIdManager.CLASS_PROPERTY_SET_IS_EXTENSIONAL: + action.setSelected(Class.isExtensional(clickedClass)); + enabled = + Class.isCollective(clickedClass) + || Class.hasCollectiveNature(clickedClass) + || (!isSmartModelingEnabled && Class.hasValidStereotype(clickedClass)); + break; + + case ActionIdManager.CLASS_PROPERTY_SET_IS_POWERTYPE: + action.setSelected(Class.isPowertype(clickedClass)); + enabled = Class.isType(clickedClass); + break; + + case ActionIdManager.CLASS_PROPERTY_SET_ORDER: + enabled = Class.isType(clickedClass); + if (Class.hasValidStereotype(clickedClass)) { + String order = Class.getOrderOr(clickedClass).orElse("1"); + action.setLabel("Set order" + " (" + order + ")"); + } + break; + } + + action.setEnabled(enabled); + } + + private void setBooleanTaggedValue(IClass clickedClass, String metaProperty) { + final ITaggedValue booleanTaggedValue = + StereotypesManager.reapplyStereotypeAndGetTaggedValue(clickedClass, metaProperty); + final boolean value = + booleanTaggedValue != null && Boolean.parseBoolean(booleanTaggedValue.getValueAsString()); + + ModelElement.forEachSelectedElement( + clickedClass, + selectedElement -> { + ITaggedValue taggedValue = + StereotypesManager.reapplyStereotypeAndGetTaggedValue(selectedElement, metaProperty); + + if (taggedValue == null) { + return; + } + + taggedValue.setValue(!value); + }); + } + + private void setOrderProperty(IClass clickedClass) { + final ITaggedValue baseTaggedValue = + StereotypesManager.reapplyStereotypeAndGetTaggedValue( + clickedClass, StereotypesManager.PROPERTY_ORDER); + + if (baseTaggedValue == null) { + return; + } + + final SetOrderView dialog = new SetOrderView(baseTaggedValue.getValueAsString()); + ApplicationManager.instance().getViewManager().showDialog(dialog); + final String order = dialog.getOrder(); + + ModelElement.forEachSelectedElement( + clickedClass, + selectedClass -> { + ITaggedValue taggedValue = + StereotypesManager.reapplyStereotypeAndGetTaggedValue( + selectedClass, StereotypesManager.PROPERTY_ORDER); + + if (taggedValue == null) { + return; + } + + taggedValue.setValue(order); + }); + } + + private void setRestrictedTo(IClass clickedClass) { + String currentRestrictions = Class.getRestrictedTo(clickedClass); + currentRestrictions = currentRestrictions == null ? "" : currentRestrictions; + + String stereotype = ModelElement.getUniqueStereotypeName(clickedClass); + List selectableRestrictedTo = RestrictedTo.possibleRestrictedToValues(stereotype); + + final SelectRestrictionsView dialog = + new SelectRestrictionsView(currentRestrictions, selectableRestrictedTo); + ApplicationManager.instance().getViewManager().showDialog(dialog); + final String newRestrictions = dialog.getSelectedValues(); + + ModelElement.forEachSelectedElement( + clickedClass, + selectedClass -> { + Class.setRestrictedTo(selectedClass, newRestrictions); + }); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotype.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotype.java deleted file mode 100644 index 8a6f1811..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotype.java +++ /dev/null @@ -1,363 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import java.awt.event.ActionEvent; -import java.util.LinkedList; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.DiagramManager; -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPContext; -import com.vp.plugin.action.VPContextActionController; -import com.vp.plugin.diagram.IDiagramElement; -import com.vp.plugin.model.IAssociation; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.ISimpleRelationship; -import com.vp.plugin.model.factory.IModelElementFactory; - -import it.unibz.inf.ontouml.vp.features.constraints.ActionIds; -import it.unibz.inf.ontouml.vp.model.Class; -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.SmartModelling; -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; - -/** - * Implementation of context sensitive action of change OntoUML stereotypes in model elements. - * - * @author Claudenir Fonseca - * @author Victor Viola - */ -public class ApplyStereotype implements VPContextActionController { - - @Override - public void performAction(VPAction action, VPContext context, ActionEvent event) { - IDiagramElement[] diagramElements = ApplicationManager.instance() - .getDiagramManager() - .getActiveDiagram() - .getSelectedDiagramElement(); - - if (diagramElements == null) { - applyStereotype(action, context.getModelElement()); - return; - } - - IModelElement clickedElement = context.getModelElement(); - - for (IDiagramElement diagramElement : diagramElements) { - IModelElement modelElement = diagramElement.getModelElement(); - - if (modelElement.getModelType().equals(clickedElement.getModelType())) - applyStereotype(action, modelElement); - } - } - - // TODO: change this method to be independent of diagram elements - @Override - public void update(VPAction action, VPContext context) { - action.setEnabled(true); - - if (action.getActionId().contains("fixedMenu")) { return ; } - - if ( - context.getModelElement().getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS) && - !isClassSelectionAllowed() - ) { - action.setEnabled(false); - } - - final DiagramManager dm = ApplicationManager - .instance().getDiagramManager(); - IDiagramElement[] diagramElements = - dm.getActiveDiagram() != null ? - dm.getActiveDiagram().getSelectedDiagramElement() : - null; - - if (diagramElements == null) { - defineActionBehavior(action, context.getModelElement()); - return; - } - - for (IDiagramElement diagramElement : diagramElements) { - if (diagramElement.getModelElement().getModelType().equals(context.getModelElement().getModelType())) - defineActionBehavior(action, diagramElement.getModelElement()); - } - - } - - private void applyStereotype(VPAction action, IModelElement element) { - switch (action.getActionId()) { - case ActionIds.TYPE: - case ActionIds.TYPE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_TYPE); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.HISTORICAL_ROLE: - case ActionIds.HISTORICAL_ROLE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_HISTORICAL_ROLE); - break; - case ActionIds.HISTORICAL_ROLE_MIXIN: - case ActionIds.HISTORICAL_ROLE_MIXIN_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_HISTORICAL_ROLE_MIXIN); - break; - case ActionIds.EVENT: - case ActionIds.EVENT_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_EVENT); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.SITUATION: - case ActionIds.SITUATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_SITUATION); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.ENUMERATION: - case ActionIds.ENUMERATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_ENUMERATION); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.DATATYPE: - case ActionIds.DATATYPE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_DATATYPE); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.SUBKIND: - case ActionIds.SUBKIND_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_SUBKIND); - break; - case ActionIds.ROLE_MIXIN: - case ActionIds.ROLE_MIXIN_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_ROLE_MIXIN); - break; - case ActionIds.ROLE: - case ActionIds.ROLE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_ROLE); - break; - case ActionIds.RELATOR: - case ActionIds.RELATOR_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_RELATOR); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.QUANTITY: - case ActionIds.QUANTITY_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_QUANTITY); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.QUALITY: - case ActionIds.QUALITY_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_QUALITY); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.PHASE_MIXIN: - case ActionIds.PHASE_MIXIN_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_PHASE_MIXIN); - break; - case ActionIds.PHASE: - case ActionIds.PHASE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_PHASE); - break; - case ActionIds.MODE: - case ActionIds.MODE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_MODE); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.MIXIN: - case ActionIds.MIXIN_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_MIXIN); - break; - case ActionIds.KIND: - case ActionIds.KIND_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_KIND); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.COLLECTIVE: - case ActionIds.COLLECTIVE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_COLLECTIVE); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIds.CATEGORY: - case ActionIds.CATEGORY_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_CATEGORY); - break; - case ActionIds.INSTANTIATION: - case ActionIds.INSTANTIATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_INSTANTIATION); - break; - case ActionIds.TERMINATION: - case ActionIds.TERMINATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_TERMINATION); - break; - case ActionIds.PARTICIPATIONAL: - case ActionIds.PARTICIPATIONAL_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_PARTICIPATIONAL); - break; - case ActionIds.PARTICIPATION: - case ActionIds.PARTICIPATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_PARTICIPATION); - break; - case ActionIds.HISTORICAL_DEPENDENCE: - case ActionIds.HISTORICAL_DEPENDENCE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_HISTORICAL_DEPENDENCE); - break; - case ActionIds.CREATION: - case ActionIds.CREATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_CREATION); - break; - case ActionIds.MANIFESTATION: - case ActionIds.MANIFESTATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_MANIFESTATION); - break; - case ActionIds.BRINGS_ABOUT: - case ActionIds.BRINGS_ABOUT_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_BRINGS_ABOUT); - break; - case ActionIds.TRIGGERS: - case ActionIds.TRIGGERS_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_TRIGGERS); - break; - case ActionIds.MATERIAL: - case ActionIds.MATERIAL_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_MATERIAL); - break; - case ActionIds.COMPARATIVE: - case ActionIds.COMPARATIVE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_COMPARATIVE); - break; - case ActionIds.MEDIATION: - case ActionIds.MEDIATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_MEDIATION); - break; - case ActionIds.CHARACTERIZATION: - case ActionIds.CHARACTERIZATION_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_CHARACTERIZATION); - break; - case ActionIds.EXTERNAL_DEPENDENCE: - case ActionIds.EXTERNAL_DEPENDENCE_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_EXTERNAL_DEPENDENCE); - break; - case ActionIds.COMPONENT_OF: - case ActionIds.COMPONENT_OF_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_COMPONENT_OF); - break; - case ActionIds.MEMBER_OF: - case ActionIds.MEMBER_OF_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_MEMBER_OF); - break; - case ActionIds.SUB_COLLECTION_OF: - case ActionIds.SUB_COLLECTION_OF_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_SUB_COLLECTION_OF); - break; - case ActionIds.SUB_QUANTITY_OF: - case ActionIds.SUB_QUANTITY_OF_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_SUB_QUANTITY_OF); - break; - case ActionIds.BEGIN: - case ActionIds.BEGIN_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_BEGIN); - break; - case ActionIds.END: - case ActionIds.END_FIXED: - StereotypeUtils.applyStereotype(element, StereotypeUtils.STR_END); - break; - } - - boolean isSmartModelingEnabled = Configurations.getInstance().getProjectConfigurations() - .isSmartModellingEnabled(); - boolean isClass = element.getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isAssociation = element.getModelType().equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - - if (isSmartModelingEnabled && isClass) - SmartModelling.setClassMetaProperties((IClass) element); - - if (isSmartModelingEnabled && isAssociation) - SmartModelling.setAssociationMetaProperties((IAssociation) element); - } - - private void defineActionBehavior(VPAction action, IModelElement element) { - - if (element.getModelType().equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION)) { - final IAssociation association = (IAssociation) element; - SmartModelling.manageAssociationStereotypes(association, action); - return; - } - - if (element.getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS)) { - final IClass _class = (IClass) element; - SmartModelling.manageClassStereotypes(_class, action); - return; - } - } - - private boolean isClassSelectionAllowed() { - - final DiagramManager dm = ApplicationManager.instance() - .getDiagramManager(); - IDiagramElement[] diagramElements = - dm.getActiveDiagram() != null ? - dm.getActiveDiagram().getSelectedDiagramElement() : - null ; - LinkedList superClasses = new LinkedList<>(); - - if (diagramElements == null) - return true; - - if (diagramElements.length == 1) - return true; - - //build list of Ids of all classes selected - for (IDiagramElement diagramElement : diagramElements) { - - ISimpleRelationship[] relationshipsTo = diagramElement.getModelElement().toToRelationshipArray(); - - for (int i = 0; relationshipsTo != null && i < relationshipsTo.length; i++) { - ISimpleRelationship relationshipTo = relationshipsTo[i]; - String superClassType = relationshipTo.getFrom() != null ? relationshipTo.getFrom().getModelType() : ""; - - if (!(superClassType.equals(IModelElementFactory.MODEL_TYPE_CLASS))) - continue; - - IClass superClass = (IClass) relationshipTo.getFrom(); - - superClasses.add(superClass.getId()); - } - } - - //Iterates over the list of the superclasses Id - //then iterate over the list again to count if the id - //was inserted the same amount as the amount of selected classes - int counter = 0; - - for (int i = 0; i < superClasses.size(); i++) { - String id = superClasses.get(i); - - for (int j = 0; j < superClasses.size(); j++) { - String idAux = superClasses.get(j); - - if (id.equals(idAux)) - counter++; - } - - if (counter == countClassesSelected()) - return true; - else - counter = 0; - } - - return false; - } - - private int countClassesSelected() { - - IDiagramElement[] diagramElements = ApplicationManager.instance().getDiagramManager().getActiveDiagram().getSelectedDiagramElement(); - int count = 0; - - if (diagramElements == null) - return count; - - for (IDiagramElement diagramElement : diagramElements) { - if (diagramElement.getModelElement().getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS)) - count++; - } - - return count++; - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotypeController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotypeController.java new file mode 100644 index 00000000..b6ee4cc9 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotypeController.java @@ -0,0 +1,417 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPContext; +import com.vp.plugin.action.VPContextActionController; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.factory.IModelElementFactory; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.uml.Association; +import it.unibz.inf.ontouml.vp.model.uml.Class; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.utils.ActionIdManager; +import it.unibz.inf.ontouml.vp.utils.OntoUMLConstraintsManager; +import it.unibz.inf.ontouml.vp.utils.Stereotype; +import it.unibz.inf.ontouml.vp.utils.StereotypesManager; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import java.awt.event.ActionEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * Implementation of context sensitive action of change OntoUML stereotypes in model elements. + * + * @author Claudenir Fonseca + * @author Victor Viola + */ +public class ApplyStereotypeController implements VPContextActionController { + + @Override + public void performAction(VPAction action, VPContext context, ActionEvent event) { + final IModelElement clickedElement = context.getModelElement(); + final String clickedElementType = clickedElement.getModelType(); + + if (action.getActionId().contains("fixedMenu")) { + ModelElement.forEachSelectedElement( + clickedElement, selectedElement -> applyStereotype(action, selectedElement)); + return; + } + + switch (clickedElementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + retrievesSelectedOrInvertedAssociations((IAssociation) clickedElement, action.getActionId()) + .stream() + .forEach(selectedElement -> applyStereotype(action, selectedElement)); + return; + case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: + applyStereotype(action, clickedElement); + return; + case IModelElementFactory.MODEL_TYPE_CLASS: + ModelElement.forEachSelectedElement( + clickedElement, selectedClass -> applyStereotype(action, selectedClass)); + return; + default: + throw new UnsupportedOperationException("Unexpected element of type " + clickedElementType); + } + } + + @Override + public void update(VPAction action, VPContext context) { + if (action.getActionId().contains("fixedMenu")) { + action.setEnabled(true); + return; + } + + final IModelElement clickedElement = context.getModelElement(); + final String clickedElementType = clickedElement != null ? clickedElement.getModelType() : ""; + final String actionId = action.getActionId(); + + switch (clickedElementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + { + final IAssociation clickedAssociation = (IAssociation) clickedElement; + final List selectedAssociations = new ArrayList<>(); + + ModelElement.forEachSelectedElement( + clickedAssociation, + selectedAssociation -> { + if (!selectedAssociations.contains(selectedAssociation)) { + selectedAssociations.add(selectedAssociation); + } + }); + + action.setLabel(ActionIdManager.getActionLabelById(actionId)); + + if (isStereotypeActionAllowedAllAssociations(actionId, selectedAssociations)) { + action.setEnabled(true); + } else if (isStereotypeActionAllowedAllInvertedAssociations( + actionId, selectedAssociations)) { + action.setEnabled(true); + action.setLabel(action.getLabel() + " (inverted)"); + } else { + action.setEnabled(false); + } + break; + } + case IModelElementFactory.MODEL_TYPE_CLASS: + { + final IClass clickedClass = (IClass) clickedElement; + final List selectedClasses = new ArrayList<>(); + + ModelElement.forEachSelectedElement( + clickedClass, + selectedClass -> { + if (!selectedClasses.contains(selectedClass)) { + selectedClasses.add(selectedClass); + } + }); + + if (isStereotypeActionAllowedAllClasses(actionId, selectedClasses)) { + action.setEnabled(true); + } else { + action.setEnabled(false); + } + break; + } + default: + throw new UnsupportedOperationException("Unexpected element of type " + clickedElementType); + } + } + + private List retrievesSelectedOrInvertedAssociations( + IAssociation association, String actionId) { + List selectedOrInvertedAssociations = new ArrayList<>(); + final IClass associationSource = Association.getSource(association); + final IClass associationTarget = Association.getTarget(association); + + // Verifies if the actionId requires inverting the associations + if (isStereotypeActionAllowed(actionId, associationSource, associationTarget)) { + ModelElement.forEachSelectedElement( + association, + selectedAssociation -> { + selectedOrInvertedAssociations.add(selectedAssociation); + }); + } else { + final boolean shouldProceed = ViewManagerUtils.associationInvertionWarningDialog(); + + if (shouldProceed) { + ModelElement.forEachSelectedElement( + association, + selectedAssociation -> { + if (!selectedOrInvertedAssociations.contains(selectedAssociation)) { + Association.invertAssociation(selectedAssociation, true); + selectedOrInvertedAssociations.add(selectedAssociation); + } + }); + } + } + + return selectedOrInvertedAssociations; + } + + private boolean isStereotypeActionAllowed(String actionId, IClass _class) { + final Set children = Class.getChildren(_class); + + for (IClass child : children) { + final List allowedActions = + OntoUMLConstraintsManager.getAllowedActionsBasedOnChild(child); + if (!allowedActions.contains(actionId)) { + return false; + } + } + + final Set parents = Class.getParents(_class); + + for (IClass parent : parents) { + final List allowedActions = + OntoUMLConstraintsManager.getAllowedActionsBasedOnParent(parent); + if (!allowedActions.contains(actionId)) { + return false; + } + } + + return true; + } + + private boolean isStereotypeActionAllowed( + String actionId, IClass associationSource, IClass associationTarget) { + final List allowedActions = + OntoUMLConstraintsManager.getAllowedActionsBasedOnSourceAndTarget( + associationSource, associationTarget); + + return allowedActions.contains(actionId); + } + + private boolean isStereotypeActionAllowedAllClasses(String actionId, List classes) { + return classes.stream() + .allMatch( + selectedClass -> { + return isStereotypeActionAllowed(actionId, selectedClass); + }); + } + + private boolean isStereotypeActionAllowedAllAssociations( + String actionId, List associations) { + return associations.stream() + .allMatch( + selectedAssociation -> { + final IClass source = Association.getSource(selectedAssociation); + final IClass target = Association.getTarget(selectedAssociation); + return isStereotypeActionAllowed(actionId, source, target); + }); + } + + private boolean isStereotypeActionAllowedAllInvertedAssociations( + String actionId, List associations) { + return associations.stream() + .allMatch( + selectedAssociation -> { + final IClass source = Association.getSource(selectedAssociation); + final IClass target = Association.getTarget(selectedAssociation); + return isStereotypeActionAllowed(actionId, target, source); + }); + } + + private void applyStereotype(VPAction action, IModelElement element) { + switch (action.getActionId()) { + case ActionIdManager.TYPE: + case ActionIdManager.TYPE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.TYPE); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.HISTORICAL_ROLE: + case ActionIdManager.HISTORICAL_ROLE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.HISTORICAL_ROLE); + break; + case ActionIdManager.HISTORICAL_ROLE_MIXIN: + case ActionIdManager.HISTORICAL_ROLE_MIXIN_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.HISTORICAL_ROLE_MIXIN); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.EVENT: + case ActionIdManager.EVENT_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.EVENT); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.SITUATION: + case ActionIdManager.SITUATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.SITUATION); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.ENUMERATION: + case ActionIdManager.ENUMERATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.ENUMERATION); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.DATATYPE: + case ActionIdManager.DATATYPE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.DATATYPE); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.ABSTRACT: + case ActionIdManager.ABSTRACT_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.ABSTRACT); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.SUBKIND: + case ActionIdManager.SUBKIND_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.SUBKIND); + break; + case ActionIdManager.ROLE_MIXIN: + case ActionIdManager.ROLE_MIXIN_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.ROLE_MIXIN); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.ROLE: + case ActionIdManager.ROLE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.ROLE); + break; + case ActionIdManager.RELATOR: + case ActionIdManager.RELATOR_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.RELATOR); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.QUANTITY: + case ActionIdManager.QUANTITY_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.QUANTITY); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.QUALITY: + case ActionIdManager.QUALITY_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.QUALITY); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.PHASE_MIXIN: + case ActionIdManager.PHASE_MIXIN_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.PHASE_MIXIN); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.PHASE: + case ActionIdManager.PHASE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.PHASE); + break; + case ActionIdManager.MODE: + case ActionIdManager.MODE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.MODE); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.MIXIN: + case ActionIdManager.MIXIN_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.MIXIN); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.KIND: + case ActionIdManager.KIND_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.KIND); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.COLLECTIVE: + case ActionIdManager.COLLECTIVE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.COLLECTIVE); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.CATEGORY: + case ActionIdManager.CATEGORY_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.CATEGORY); + Class.setDefaultRestrictedTo((IClass) element); + break; + case ActionIdManager.INSTANTIATION: + case ActionIdManager.INSTANTIATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.INSTANTIATION); + break; + case ActionIdManager.TERMINATION: + case ActionIdManager.TERMINATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.TERMINATION); + break; + case ActionIdManager.PARTICIPATIONAL: + case ActionIdManager.PARTICIPATIONAL_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.PARTICIPATIONAL); + break; + case ActionIdManager.PARTICIPATION: + case ActionIdManager.PARTICIPATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.PARTICIPATION); + break; + case ActionIdManager.HISTORICAL_DEPENDENCE: + case ActionIdManager.HISTORICAL_DEPENDENCE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.HISTORICAL_DEPENDENCE); + break; + case ActionIdManager.CREATION: + case ActionIdManager.CREATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.CREATION); + break; + case ActionIdManager.MANIFESTATION: + case ActionIdManager.MANIFESTATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.MANIFESTATION); + break; + case ActionIdManager.BRINGS_ABOUT: + case ActionIdManager.BRINGS_ABOUT_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.BRINGS_ABOUT); + break; + case ActionIdManager.TRIGGERS: + case ActionIdManager.TRIGGERS_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.TRIGGERS); + break; + case ActionIdManager.MATERIAL: + case ActionIdManager.MATERIAL_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.MATERIAL); + break; + case ActionIdManager.COMPARATIVE: + case ActionIdManager.COMPARATIVE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.COMPARATIVE); + break; + case ActionIdManager.MEDIATION: + case ActionIdManager.MEDIATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.MEDIATION); + break; + case ActionIdManager.CHARACTERIZATION: + case ActionIdManager.CHARACTERIZATION_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.CHARACTERIZATION); + break; + case ActionIdManager.EXTERNAL_DEPENDENCE: + case ActionIdManager.EXTERNAL_DEPENDENCE_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.EXTERNAL_DEPENDENCE); + break; + case ActionIdManager.COMPONENT_OF: + case ActionIdManager.COMPONENT_OF_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.COMPONENT_OF); + break; + case ActionIdManager.MEMBER_OF: + case ActionIdManager.MEMBER_OF_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.MEMBER_OF); + break; + case ActionIdManager.SUB_COLLECTION_OF: + case ActionIdManager.SUB_COLLECTION_OF_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.SUB_COLLECTION_OF); + break; + case ActionIdManager.SUB_QUANTITY_OF: + case ActionIdManager.SUB_QUANTITY_OF_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.SUB_QUANTITY_OF); + break; + case ActionIdManager.BEGIN: + case ActionIdManager.BEGIN_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.BEGIN); + break; + case ActionIdManager.END: + case ActionIdManager.END_FIXED: + StereotypesManager.applyStereotype(element, Stereotype.END); + break; + } + + boolean isSmartModelingEnabled = + Configurations.getInstance().getProjectConfigurations().isSmartModellingEnabled(); + boolean isClass = element.getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isAssociation = + element.getModelType().equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + + if (isSmartModelingEnabled && isClass) { + SmartModellingController.setClassMetaProperties((IClass) element); + } + + if (isSmartModelingEnabled && isAssociation) { + SmartModellingController.setAssociationMetaProperties((IAssociation) element); + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationAction.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationAction.java deleted file mode 100644 index dd14de17..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationAction.java +++ /dev/null @@ -1,136 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import java.awt.Component; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; -import com.vp.plugin.diagram.IClassDiagramUIModel; -import com.vp.plugin.diagram.IDiagramUIModel; -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; - -import it.unibz.inf.ontouml.vp.model.ModelElement; -import it.unibz.inf.ontouml.vp.utils.OntoUMLServerUtils; -import it.unibz.inf.ontouml.vp.utils.ServerRequest; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; -import it.unibz.inf.ontouml.vp.views.ProgressPanel; - -/** - * Implementation of toolbar button action responsible for performing diagram verification. - * - */ -public class DiagramVerificationAction implements VPActionController { - - private ProgressPanel progressPanel; - private ProgressDialog loading; - private IDialog mainDialog; - DiagramVerificationRequest request; - Thread thread; - - /** - * - * Performs OntoUML diagram verification. - * - * @param action - * - */ - @Override - public void performAction(VPAction action) { - - if (!hasOpenedClassDiagram()) { - ViewUtils.simpleDialog("Diagram Verification", "Please open a diagram before running this command."); - return; - } - - request = new DiagramVerificationRequest(); - - loading = new ProgressDialog(); - ApplicationManager.instance().getViewManager().showDialog(loading); - - Thread thread = new Thread(request); - thread.start(); - } - - /** - * Called when the menu containing the button is accessed allowing for action manipulation, such as enable/disable or selecting the button. - * - * OBS: DOES NOT apply to this class. - */ - @Override - public void update(VPAction action) { - } - - private static boolean hasOpenedClassDiagram() { - final IDiagramUIModel[] diagramArray = ApplicationManager.instance().getProjectManager().getProject().toDiagramArray(); - - if (diagramArray == null) - return false; - - for (IDiagramUIModel diagram : diagramArray) - if (diagram instanceof IClassDiagramUIModel && diagram.isOpened()) - return true; - - return false; - } - - protected class ProgressDialog implements IDialogHandler { - - @Override - public Component getComponent() { - progressPanel = new ProgressPanel(request); - return progressPanel; - } - - @Override - public void prepare(IDialog dialog) { - mainDialog = dialog; - mainDialog.setTitle("Verification Service"); - mainDialog.setModal(false); - mainDialog.setResizable(false); - dialog.setSize(progressPanel.getWidth(), progressPanel.getHeight() + 20); - progressPanel.setContainerDialog(mainDialog); - } - - @Override - public void shown() { - } - - @Override - public boolean canClosed() { - mainDialog.close(); - return true; - } - - } - - public class DiagramVerificationRequest extends ServerRequest { - - @Override - public void run() { - while (keepRunning()) { - try { - final String response = OntoUMLServerUtils.requestModelVerification(ModelElement.generateModel(true), loading); - - if (keepRunning()) { - if (response != null) { - mainDialog.close(); - request.doStop(); - ViewUtils.logDiagramVerificationResponse(response); - } else { - loading.canClosed(); - request.doStop(); - } - } else { - loading.canClosed(); - request.doStop(); - ViewUtils.cleanAndShowMessage("Request cancelled by the user."); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationController.java new file mode 100644 index 00000000..025b4fb2 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationController.java @@ -0,0 +1,128 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPActionController; +import com.vp.plugin.diagram.IClassDiagramUIModel; +import com.vp.plugin.diagram.IDiagramUIModel; +import com.vp.plugin.view.IDialog; +import com.vp.plugin.view.IDialogHandler; +import it.unibz.inf.ontouml.vp.model.ServerRequest; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import it.unibz.inf.ontouml.vp.views.ProgressPanel; +import java.awt.Component; + +/** Implementation of toolbar button action responsible for performing diagram verification. */ +public class DiagramVerificationController implements VPActionController { + + private ProgressPanel progressPanel; + private ProgressDialog loading; + private IDialog mainDialog; + DiagramVerificationRequest request; + Thread thread; + + /** + * Performs OntoUML diagram verification. + * + * @param action + */ + @Override + public void performAction(VPAction action) { + + if (!hasOpenedClassDiagram()) { + ViewManagerUtils.simpleDialog( + "Diagram Verification", "Please open a diagram before running this command."); + return; + } + + request = new DiagramVerificationRequest(); + + loading = new ProgressDialog(); + ApplicationManager.instance().getViewManager().showDialog(loading); + + Thread thread = new Thread(request); + thread.start(); + } + + /** + * Called when the menu containing the button is accessed allowing for action manipulation, such + * as enable/disable or selecting the button. + * + *

OBS: DOES NOT apply to this class. + */ + @Override + public void update(VPAction action) {} + + private static boolean hasOpenedClassDiagram() { + final IDiagramUIModel[] diagramArray = + ApplicationManager.instance().getProjectManager().getProject().toDiagramArray(); + + if (diagramArray == null) return false; + + for (IDiagramUIModel diagram : diagramArray) + if (diagram instanceof IClassDiagramUIModel && diagram.isOpened()) return true; + + return false; + } + + protected class ProgressDialog implements IDialogHandler { + + @Override + public Component getComponent() { + progressPanel = new ProgressPanel(request); + return progressPanel; + } + + @Override + public void prepare(IDialog dialog) { + mainDialog = dialog; + mainDialog.setTitle("Verification Service"); + mainDialog.setModal(false); + mainDialog.setResizable(false); + dialog.setSize(progressPanel.getWidth(), progressPanel.getHeight() + 20); + progressPanel.setContainerDialog(mainDialog); + } + + @Override + public void shown() {} + + @Override + public boolean canClosed() { + mainDialog.close(); + return true; + } + } + + protected class DiagramVerificationRequest extends ServerRequest { + + @Override + public void run() { + while (keepRunning()) { + try { + final String response = + OntoUMLServerAccessController.requestModelVerification( + ModelElement.generateModel(true), loading); + + if (keepRunning()) { + if (response != null) { + mainDialog.close(); + request.doStop(); + ViewManagerUtils.logDiagramVerificationResponse(response); + } else { + loading.canClosed(); + request.doStop(); + } + } else { + loading.canClosed(); + request.doStop(); + ViewManagerUtils.cleanAndShowMessage("Request cancelled by the user."); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ExportToGUFOAction.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ExportToGUFOAction.java deleted file mode 100644 index 37dde2c3..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ExportToGUFOAction.java +++ /dev/null @@ -1,249 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import java.awt.Component; -import java.awt.FileDialog; -import java.awt.Frame; -import java.io.BufferedReader; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.stream.Collectors; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; - -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; -import it.unibz.inf.ontouml.vp.model.ModelElement; -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.OntoUMLServerUtils; -import it.unibz.inf.ontouml.vp.utils.ProjectConfigurations; -import it.unibz.inf.ontouml.vp.utils.ServerRequest; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; -import it.unibz.inf.ontouml.vp.views.ExportToGUFOView; -import it.unibz.inf.ontouml.vp.views.ProgressPanel; - -/** - * Implementation of toolbar button Export to gUFO. - * - * @author Victor Viola - * @author Claudenir Fonseca - * - */ -public class ExportToGUFOAction implements VPActionController { - - private ProgressPanel progressPanel; - private ProgressDialog loading; - private IDialog mainDialog; - - private ExportDialog menu; - private ExportToGUFOView _exportMenuView; - private IDialog _dialog; - MenuExport requestMenu; - - @Override - public void performAction(VPAction action) { - - requestMenu = new MenuExport(); - menu = new ExportDialog(); - - if (OntoUMLPlugin.getExportToGUFOWindowOpen() == true) - return; - else - OntoUMLPlugin.setExportToGUFOWindowOpen(true); - - ApplicationManager.instance().getViewManager().showDialog(menu); - - } - - /** - * Called when the menu containing the button is accessed allowing for action - * manipulation, such as enable/disable or selecting the button. - * - * OBS: DOES NOT apply to this class. - */ - @Override - public void update(VPAction action) { - } - - private void saveFile(BufferedReader buffer, String exportFormat) throws IOException { - final Configurations configs = Configurations.getInstance(); - final ProjectConfigurations projectConfigurations = configs.getProjectConfigurations(); - final FileDialog fd = new FileDialog((Frame) ApplicationManager.instance().getViewManager().getRootFrame(), - "Choose destination", FileDialog.SAVE); - - String suggestedFolderPath = projectConfigurations.getExportGUFOFolderPath(); - String suggestedFileName = projectConfigurations.getExportGUFOFilename(); - String exportFormatExtension = exportFormat != "Turtle" ? ".nt" : ".ttl"; - - if (suggestedFileName.isEmpty()) { - String projectName = ApplicationManager.instance().getProjectManager().getProject().getName(); - suggestedFileName = projectName + exportFormatExtension; - } - - fd.setDirectory(suggestedFolderPath); - fd.setFile(suggestedFileName); - fd.setVisible(true); - - if (fd.getDirectory() != null && fd.getFile() != null) { - final String fileDirectory = fd.getDirectory(); - final String fileName = !fd.getFile().endsWith(exportFormatExtension) ? fd.getFile() + exportFormatExtension : fd.getFile(); - final String output = buffer.lines().collect(Collectors.joining("\n")); - - Files.write(Paths.get(fileDirectory, fileName), output.getBytes()); - projectConfigurations.setExportGUFOFolderPath(fileDirectory); - projectConfigurations.setExportGUFOFilename(fileName); - configs.save(); - } - } - - public class ProgressDialog implements IDialogHandler { - - @Override - public Component getComponent() { - progressPanel = new ProgressPanel(requestMenu); - return progressPanel; - } - - @Override - public void prepare(IDialog dialog) { - mainDialog = dialog; - mainDialog.setTitle("Export to GUFO"); - mainDialog.setModal(false); - mainDialog.setResizable(false); - dialog.setSize(progressPanel.getWidth(), progressPanel.getHeight() + 20); - progressPanel.setContainerDialog(mainDialog); - } - - @Override - public void shown() { - } - - @Override - public boolean canClosed() { - mainDialog.close(); - return true; - } - } - - protected class ExportDialog implements IDialogHandler { - - /** - * - * Called once before the dialog is shown. Developer should return the content - * of the dialog (similar to the content pane). - * - */ - @Override - public Component getComponent() { - _exportMenuView = new ExportToGUFOView(Configurations.getInstance().getProjectConfigurations(), - requestMenu); - return _exportMenuView; - } - - /** - * - * Called after the getComponent(). A dialog is created on Visual Paradigm - * internally (it still not shown out). Developer can set the outlook of the - * dialog on prepare(). - * - */ - @Override - public void prepare(IDialog dialog) { - _dialog = dialog; - _dialog.setTitle(OntoUMLPlugin.PLUGIN_NAME + " Configurations"); - _dialog.setModal(false); - _dialog.setResizable(false); - _dialog.setSize(_exportMenuView.getWidth(), _exportMenuView.getHeight() + 20); - _exportMenuView.setContainerDialog(_dialog); - } - - /** - * - * Called when the dialog is shown. - * - */ - @Override - public void shown() { - } - - /** - * - * Called when the dialog is closed by the user clicking on the close button of - * the frame. - * - */ - @Override - public boolean canClosed() { - requestMenu.doStop(); - OntoUMLPlugin.setExportToGUFOWindowOpen(false); - ViewUtils.cleanAndShowMessage("Request cancelled by the user."); - return true; - } - - } - - public class MenuExport extends ServerRequest { - - final Configurations configs = Configurations.getInstance(); - final ProjectConfigurations projectConfigurations = configs.getProjectConfigurations(); - - @Override - public void run() { - while (keepRunning()) { - try { - - if (keepRunning()) { - if (!_exportMenuView.getIsOpen()) { - - if (_exportMenuView.getIsToExport()) { - - loading = new ProgressDialog(); - ApplicationManager.instance().getViewManager().showDialog(loading); - - final BufferedReader gufo = OntoUMLServerUtils.transformToGUFO( - ModelElement.generateModel(_exportMenuView.getSavedElements(), true), - projectConfigurations.getExportGUFOIRI(), - projectConfigurations.getExportGUFOFormat(), - projectConfigurations.getExportGUFOURIFormat(), - projectConfigurations.getExportGUFOInverseBox(), - projectConfigurations.getExportGUFOObjectBox(), - projectConfigurations.getExportGUFOAnalysisBox(), - projectConfigurations.getExportGUFOPackagesBox(), - projectConfigurations.getExportGUFOElementMapping(), - projectConfigurations.getExportGUFOPackageMapping(), loading); - - if (gufo != null) { - saveFile(gufo,projectConfigurations.getExportGUFOFormat()); - ViewUtils.cleanAndShowMessage("Model exported successfully."); - requestMenu.doStop(); - } else { - menu.canClosed(); - requestMenu.doStop(); - ViewUtils.cleanAndShowMessage( - "Unable to transform to GUFO. Please check your model."); - } - } else { - menu.canClosed(); - requestMenu.doStop(); - ViewUtils.cleanAndShowMessage("Request cancelled by the user."); - } - - OntoUMLPlugin.setExportToGUFOWindowOpen(false); - } - } else { - OntoUMLPlugin.setExportToGUFOWindowOpen(false); - menu.canClosed(); - requestMenu.doStop(); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/GUFOExportController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/GUFOExportController.java new file mode 100644 index 00000000..7406e08f --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/GUFOExportController.java @@ -0,0 +1,231 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPActionController; +import com.vp.plugin.view.IDialog; +import com.vp.plugin.view.IDialogHandler; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; +import it.unibz.inf.ontouml.vp.model.ServerRequest; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import it.unibz.inf.ontouml.vp.views.GUFOExportView; +import it.unibz.inf.ontouml.vp.views.ProgressPanel; +import java.awt.Component; +import java.awt.FileDialog; +import java.awt.Frame; +import java.io.BufferedReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.stream.Collectors; + +/** + * Implementation of toolbar button Export to gUFO. + * + * @author Victor Viola + * @author Claudenir Fonseca + */ +public class GUFOExportController implements VPActionController { + + private ProgressPanel progressPanel; + private ProgressDialog loading; + private IDialog mainDialog; + + private ExportDialog menu; + private GUFOExportView _exportMenuView; + private IDialog _dialog; + MenuExport requestMenu; + + @Override + public void performAction(VPAction action) { + + requestMenu = new MenuExport(); + menu = new ExportDialog(); + + if (OntoUMLPlugin.getExportToGUFOWindowOpen() == true) return; + else OntoUMLPlugin.setExportToGUFOWindowOpen(true); + + ApplicationManager.instance().getViewManager().showDialog(menu); + } + + /** + * Called when the menu containing the button is accessed allowing for action manipulation, such + * as enable/disable or selecting the button. + * + *

OBS: DOES NOT apply to this class. + */ + @Override + public void update(VPAction action) {} + + private void saveFile(BufferedReader buffer, String exportFormat) throws IOException { + final Configurations configs = Configurations.getInstance(); + final ProjectConfigurations projectConfigurations = configs.getProjectConfigurations(); + final FileDialog fd = + new FileDialog( + (Frame) ApplicationManager.instance().getViewManager().getRootFrame(), + "Choose destination", + FileDialog.SAVE); + + String suggestedFolderPath = projectConfigurations.getExportGUFOFolderPath(); + String suggestedFileName = projectConfigurations.getExportGUFOFilename(); + String exportFormatExtension = exportFormat != "Turtle" ? ".nt" : ".ttl"; + + if (suggestedFileName.isEmpty()) { + String projectName = ApplicationManager.instance().getProjectManager().getProject().getName(); + suggestedFileName = projectName + exportFormatExtension; + } + + fd.setDirectory(suggestedFolderPath); + fd.setFile(suggestedFileName); + fd.setVisible(true); + + if (fd.getDirectory() != null && fd.getFile() != null) { + final String fileDirectory = fd.getDirectory(); + final String fileName = + !fd.getFile().endsWith(exportFormatExtension) + ? fd.getFile() + exportFormatExtension + : fd.getFile(); + final String output = buffer.lines().collect(Collectors.joining("\n")); + + Files.write(Paths.get(fileDirectory, fileName), output.getBytes()); + projectConfigurations.setExportGUFOFolderPath(fileDirectory); + projectConfigurations.setExportGUFOFilename(fileName); + configs.save(); + } + } + + public class ProgressDialog implements IDialogHandler { + + @Override + public Component getComponent() { + progressPanel = new ProgressPanel(requestMenu); + return progressPanel; + } + + @Override + public void prepare(IDialog dialog) { + mainDialog = dialog; + mainDialog.setTitle("Export to GUFO"); + mainDialog.setModal(false); + mainDialog.setResizable(false); + dialog.setSize(progressPanel.getWidth(), progressPanel.getHeight() + 20); + progressPanel.setContainerDialog(mainDialog); + } + + @Override + public void shown() {} + + @Override + public boolean canClosed() { + mainDialog.close(); + return true; + } + } + + protected class ExportDialog implements IDialogHandler { + + /** + * Called once before the dialog is shown. Developer should return the content of the dialog + * (similar to the content pane). + */ + @Override + public Component getComponent() { + _exportMenuView = + new GUFOExportView(Configurations.getInstance().getProjectConfigurations(), requestMenu); + return _exportMenuView; + } + + /** + * Called after the getComponent(). A dialog is created on Visual Paradigm internally (it still + * not shown out). Developer can set the outlook of the dialog on prepare(). + */ + @Override + public void prepare(IDialog dialog) { + _dialog = dialog; + _dialog.setTitle(OntoUMLPlugin.PLUGIN_NAME + " Configurations"); + _dialog.setModal(false); + _dialog.setResizable(false); + _dialog.setSize(_exportMenuView.getWidth(), _exportMenuView.getHeight() + 20); + _exportMenuView.setContainerDialog(_dialog); + } + + /** Called when the dialog is shown. */ + @Override + public void shown() {} + + /** Called when the dialog is closed by the user clicking on the close button of the frame. */ + @Override + public boolean canClosed() { + requestMenu.doStop(); + OntoUMLPlugin.setExportToGUFOWindowOpen(false); + ViewManagerUtils.cleanAndShowMessage("Request cancelled by the user."); + return true; + } + } + + public class MenuExport extends ServerRequest { + + final Configurations configs = Configurations.getInstance(); + final ProjectConfigurations projectConfigurations = configs.getProjectConfigurations(); + + @Override + public void run() { + while (keepRunning()) { + try { + + if (keepRunning()) { + if (!_exportMenuView.getIsOpen()) { + + if (_exportMenuView.getIsToExport()) { + + loading = new ProgressDialog(); + ApplicationManager.instance().getViewManager().showDialog(loading); + + final BufferedReader gufo = + OntoUMLServerAccessController.transformToGUFO( + ModelElement.generateModel(_exportMenuView.getSavedElements(), true), + projectConfigurations.getExportGUFOIRI(), + projectConfigurations.getExportGUFOFormat(), + projectConfigurations.getExportGUFOURIFormat(), + projectConfigurations.getExportGUFOInverseBox(), + projectConfigurations.getExportGUFOObjectBox(), + projectConfigurations.getExportGUFOAnalysisBox(), + projectConfigurations.getExportGUFOPackagesBox(), + projectConfigurations.getExportGUFOElementMapping(), + projectConfigurations.getExportGUFOPackageMapping(), + loading); + + if (gufo != null) { + saveFile(gufo, projectConfigurations.getExportGUFOFormat()); + ViewManagerUtils.cleanAndShowMessage("Model exported successfully."); + requestMenu.doStop(); + } else { + menu.canClosed(); + requestMenu.doStop(); + ViewManagerUtils.cleanAndShowMessage( + "Unable to transform to GUFO. Please check your model."); + } + } else { + menu.canClosed(); + requestMenu.doStop(); + ViewManagerUtils.cleanAndShowMessage("Request cancelled by the user."); + } + + OntoUMLPlugin.setExportToGUFOWindowOpen(false); + } + } else { + OntoUMLPlugin.setExportToGUFOWindowOpen(false); + menu.canClosed(); + requestMenu.doStop(); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/GitHubAccessController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/GitHubAccessController.java new file mode 100644 index 00000000..74f16251 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/GitHubAccessController.java @@ -0,0 +1,94 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.google.gson.JsonArray; +import com.google.gson.JsonParser; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.GitHubRelease; +import it.unibz.inf.ontouml.vp.model.GitHubReleaseAsset; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import javax.net.ssl.HttpsURLConnection; + +public class GitHubAccessController { + + public static final String GITHUB_API = "https://api.github.com"; + public static final String REPOS = "/repos"; + public static final String RELEASES = "/releases"; + + public static void lookupUpdates() throws IOException { + List releases = GitHubAccessController.getReleases(); + Configurations config = Configurations.getInstance(); + config.setReleases(releases); + config.save(); + } + + public static List getReleases() throws IOException { + final URL url = + new URL( + GITHUB_API + + REPOS + + "/" + + OntoUMLPlugin.PLUGIN_REPO_OWNER + + "/" + + OntoUMLPlugin.PLUGIN_REPO_NAME + + RELEASES); + final HttpsURLConnection request = (HttpsURLConnection) url.openConnection(); + + request.setRequestMethod("GET"); + request.setRequestProperty("Accept", "application/vnd.github.v3+json"); + request.setReadTimeout(60000); + + final int responseCode = request.getResponseCode(); + + if (responseCode == HttpsURLConnection.HTTP_OK) { + try (BufferedReader in = + new BufferedReader(new InputStreamReader(request.getInputStream()))) { + StringBuilder response = new StringBuilder(); + String line; + + while ((line = in.readLine()) != null) { + response.append(line); + } + + JsonArray releasesArray = + (JsonArray) new JsonParser().parse(response.toString()).getAsJsonArray(); + List releases = new ArrayList<>(); + + releasesArray.forEach( + item -> { + releases.add(new GitHubRelease(item.getAsJsonObject())); + }); + + return releases; + } + } + + return null; + } + + public static File downloadReleaseAsset(GitHubReleaseAsset asset) + throws MalformedURLException, IOException { + final URL downloadURL = new URL(asset.getDownloadUrl()); + final ReadableByteChannel rbc = Channels.newChannel(downloadURL.openStream()); + final Path pluginDownloadDir = Files.createTempDirectory("pluginDownloadDir"); + final File downloadFile = new File(pluginDownloadDir.toFile(), asset.getName()); + final FileOutputStream fos = new FileOutputStream(downloadFile); + + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + + return downloadFile; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/JsonExportController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/JsonExportController.java new file mode 100644 index 00000000..5d9a1405 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/JsonExportController.java @@ -0,0 +1,122 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPActionController; +import com.vp.plugin.view.IDialog; +import com.vp.plugin.view.IDialogHandler; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import it.unibz.inf.ontouml.vp.views.ProgressPanel; +import java.awt.*; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +/** + * Implementation toolbar button action responsible for exporting OntoUML model in JSON (according + * to OntoUML Schema). + * + * @author Claudenir Fonseca + */ +public class JsonExportController implements VPActionController { + + private ProgressPanel progressPanel; + private ProgressDialog loading; + private IDialog mainDialog; + + Thread thread; + + /** + * Performs model export in JSON format. + * + * @param action + */ + @Override + public void performAction(VPAction action) { + final Configurations configs = Configurations.getInstance(); + final ProjectConfigurations projectConfigurations = configs.getProjectConfigurations(); + + FileDialog fd = + new FileDialog( + (Frame) ApplicationManager.instance().getViewManager().getRootFrame(), + "Choose destination", + FileDialog.SAVE); + + String suggestedFolderPath = projectConfigurations.getExportFolderPath(); + String suggestedFileName = projectConfigurations.getExportFilename(); + + if (suggestedFileName.isEmpty()) { + String projectName = ApplicationManager.instance().getProjectManager().getProject().getName(); + suggestedFileName = projectName + ".json"; + } + + fd.setDirectory(suggestedFolderPath); + fd.setFile(suggestedFileName); + fd.setVisible(true); + + String fileDirectory = fd.getDirectory(); + + if (fileDirectory != null) { + + loading = new ProgressDialog(); + ApplicationManager.instance().getViewManager().showDialog(loading); + + try { + String fileName = fd.getFile(); + + if (!fileName.endsWith(".json")) fileName += ".json"; + + final String jsonModel = ModelElement.generateModel(true); + Files.write(Paths.get(fileDirectory, fileName), jsonModel.getBytes()); + projectConfigurations.setExportFolderPath(fileDirectory); + projectConfigurations.setExportFilename(fileName); + configs.save(); + ViewManagerUtils.cleanAndShowMessage("Model exported successfully."); + } catch (IOException e) { + ViewManagerUtils.cleanAndShowMessage("Model export failed."); + e.printStackTrace(); + } + + mainDialog.close(); + } + } + + /** + * Called when the menu containing the button is accessed allowing for action manipulation, such + * as enable/disable or selecting the button. + * + *

OBS: DOES NOT apply to this class. + */ + @Override + public void update(VPAction action) {} + + protected class ProgressDialog implements IDialogHandler { + + @Override + public Component getComponent() { + progressPanel = new ProgressPanel("Building model..."); + return progressPanel; + } + + @Override + public void prepare(IDialog dialog) { + mainDialog = dialog; + mainDialog.setTitle("Export to JSON"); + mainDialog.setModal(false); + mainDialog.setResizable(false); + dialog.setSize(progressPanel.getWidth(), progressPanel.getHeight() + 20); + progressPanel.setContainerDialog(mainDialog); + } + + @Override + public void shown() {} + + @Override + public boolean canClosed() { + return false; + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelActionController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelActionController.java new file mode 100644 index 00000000..1064b27a --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelActionController.java @@ -0,0 +1,41 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPContext; +import com.vp.plugin.action.VPContextActionController; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.factory.IModelElementFactory; +import it.unibz.inf.ontouml.vp.model.uml.Association; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.utils.ActionIdManager; +import java.awt.event.ActionEvent; + +public class ModelActionController implements VPContextActionController { + + @Override + public void performAction(VPAction action, VPContext context, ActionEvent event) { + final IModelElement clickedElement = context.getModelElement(); + final String clickedElementType = clickedElement.getModelType(); + + if (!IModelElementFactory.MODEL_TYPE_ASSOCIATION.equals(clickedElementType)) { + return; + } + + final IAssociation clickedAssociation = + IModelElementFactory.MODEL_TYPE_ASSOCIATION.equals(clickedElementType) + ? (IAssociation) context.getModelElement() + : null; + + switch (action.getActionId()) { + case ActionIdManager.ASSOCIATION_ACTION_INVERT_ASSOCIATION: + ModelElement.forEachSelectedElement( + clickedAssociation, + selectedAssociation -> Association.invertAssociation(selectedAssociation, false)); + break; + } + } + + @Override + public void update(VPAction action, VPContext context) {} +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelExportAction.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelExportAction.java deleted file mode 100644 index 03cd00bc..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelExportAction.java +++ /dev/null @@ -1,125 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; -import it.unibz.inf.ontouml.vp.model.ModelElement; -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.ProjectConfigurations; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; -import it.unibz.inf.ontouml.vp.views.ProgressPanel; - -import java.awt.*; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; - -/** - * Implementation toolbar button action responsible for exporting OntoUML model - * in JSON (according to OntoUML Schema). - * - * @author Claudenir Fonseca - */ -public class ModelExportAction implements VPActionController { - - private ProgressPanel progressPanel; - private ProgressDialog loading; - private IDialog mainDialog; - - Thread thread; - - /** - * Performs model export in JSON format. - * - * @param action - */ - @Override - public void performAction(VPAction action) { - final Configurations configs = Configurations.getInstance(); - final ProjectConfigurations projectConfigurations = configs.getProjectConfigurations(); - - FileDialog fd = new FileDialog((Frame) ApplicationManager.instance().getViewManager().getRootFrame(), - "Choose destination", FileDialog.SAVE); - - String suggestedFolderPath = projectConfigurations.getExportFolderPath(); - String suggestedFileName = projectConfigurations.getExportFilename(); - - if (suggestedFileName.isEmpty()) { - String projectName = ApplicationManager.instance().getProjectManager().getProject().getName(); - suggestedFileName = projectName + ".json"; - } - - fd.setDirectory(suggestedFolderPath); - fd.setFile(suggestedFileName); - fd.setVisible(true); - - String fileDirectory = fd.getDirectory(); - - if (fileDirectory != null) { - - loading = new ProgressDialog(); - ApplicationManager.instance().getViewManager().showDialog(loading); - - try { - String fileName = fd.getFile(); - - if (!fileName.endsWith(".json")) - fileName += ".json"; - - final String jsonModel = ModelElement.generateModel(true); - Files.write(Paths.get(fileDirectory, fileName), jsonModel.getBytes()); - projectConfigurations.setExportFolderPath(fileDirectory); - projectConfigurations.setExportFilename(fileName); - configs.save(); - ViewUtils.cleanAndShowMessage("Model exported successfully."); - } catch (IOException e) { - ViewUtils.cleanAndShowMessage("Model export failed."); - e.printStackTrace(); - } - - mainDialog.close(); - } - - } - - /** - * Called when the menu containing the button is accessed allowing for action - * manipulation, such as enable/disable or selecting the button. - *

- * OBS: DOES NOT apply to this class. - */ - @Override - public void update(VPAction action) { - } - - protected class ProgressDialog implements IDialogHandler { - - @Override - public Component getComponent() { - progressPanel = new ProgressPanel("Building model..."); - return progressPanel; - } - - @Override - public void prepare(IDialog dialog) { - mainDialog = dialog; - mainDialog.setTitle("Export to JSON"); - mainDialog.setModal(false); - mainDialog.setResizable(false); - dialog.setSize(progressPanel.getWidth(), progressPanel.getHeight() + 20); - progressPanel.setContainerDialog(mainDialog); - } - - @Override - public void shown() { - } - - @Override - public boolean canClosed() { - return false; - } - - } -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationAction.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationAction.java deleted file mode 100644 index 07155fb4..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationAction.java +++ /dev/null @@ -1,119 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import java.awt.Component; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; - -import it.unibz.inf.ontouml.vp.model.ModelElement; -import it.unibz.inf.ontouml.vp.utils.OntoUMLServerUtils; -import it.unibz.inf.ontouml.vp.utils.ServerRequest; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; -import it.unibz.inf.ontouml.vp.views.ProgressPanel; - -/** - * Implementation of toolbar button action responsible for performing model verification. - * - * @author Victor Viola - * @author Claudenir Fonseca - * - */ -public class ModelVerificationAction implements VPActionController { - - private ProgressPanel progressPanel; - private ProgressDialog loading; - private IDialog mainDialog; - ModelVerificationRequest request; - - /** - * - * Performs OntoUML model verification. - * - * @param action - * - */ - @Override - public void performAction(VPAction action) { - - request = new ModelVerificationRequest(); - - loading = new ProgressDialog(); - ApplicationManager.instance().getViewManager().showDialog(loading); - - Thread thread = new Thread(request); - thread.start(); - } - - /** - * Called when the menu containing the button is accessed allowing for action manipulation, such as enable/disable or selecting the button. - * - * OBS: DOES NOT apply to this class. - */ - @Override - public void update(VPAction action) { - } - - protected class ProgressDialog implements IDialogHandler { - - @Override - public Component getComponent() { - progressPanel = new ProgressPanel(request); - return progressPanel; - } - - @Override - public void prepare(IDialog dialog) { - mainDialog = dialog; - mainDialog.setTitle("Verification Service"); - mainDialog.setModal(false); - mainDialog.setResizable(false); - dialog.setSize(progressPanel.getWidth(), progressPanel.getHeight() + 20); - progressPanel.setContainerDialog(mainDialog); - } - - @Override - public void shown() { - } - - @Override - public boolean canClosed() { - mainDialog.close(); - return true; - } - - } - - public class ModelVerificationRequest extends ServerRequest { - - @Override - public void run() { - while (keepRunning()) { - try { - final String response = OntoUMLServerUtils.requestModelVerification(ModelElement.generateModel(true), loading); - - if (keepRunning()) { - if (response != null) { - loading.canClosed(); - request.doStop(); - ViewUtils.logVerificationResponse(response); - } else { - loading.canClosed(); - request.doStop(); - } - } else { - loading.canClosed(); - request.doStop(); - ViewUtils.cleanAndShowMessage("Request cancelled by the user."); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationController.java new file mode 100644 index 00000000..2536543e --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationController.java @@ -0,0 +1,112 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPActionController; +import com.vp.plugin.view.IDialog; +import com.vp.plugin.view.IDialogHandler; +import it.unibz.inf.ontouml.vp.model.ServerRequest; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import it.unibz.inf.ontouml.vp.views.ProgressPanel; +import java.awt.Component; + +/** + * Implementation of toolbar button action responsible for performing model verification. + * + * @author Victor Viola + * @author Claudenir Fonseca + */ +public class ModelVerificationController implements VPActionController { + + private ProgressPanel progressPanel; + private ProgressDialog loading; + private IDialog mainDialog; + ModelVerificationRequest request; + + /** + * Performs OntoUML model verification. + * + * @param action + */ + @Override + public void performAction(VPAction action) { + + request = new ModelVerificationRequest(); + + loading = new ProgressDialog(); + ApplicationManager.instance().getViewManager().showDialog(loading); + + Thread thread = new Thread(request); + thread.start(); + } + + /** + * Called when the menu containing the button is accessed allowing for action manipulation, such + * as enable/disable or selecting the button. + * + *

OBS: DOES NOT apply to this class. + */ + @Override + public void update(VPAction action) {} + + protected class ProgressDialog implements IDialogHandler { + + @Override + public Component getComponent() { + progressPanel = new ProgressPanel(request); + return progressPanel; + } + + @Override + public void prepare(IDialog dialog) { + mainDialog = dialog; + mainDialog.setTitle("Verification Service"); + mainDialog.setModal(false); + mainDialog.setResizable(false); + dialog.setSize(progressPanel.getWidth(), progressPanel.getHeight() + 20); + progressPanel.setContainerDialog(mainDialog); + } + + @Override + public void shown() {} + + @Override + public boolean canClosed() { + mainDialog.close(); + return true; + } + } + + public class ModelVerificationRequest extends ServerRequest { + + @Override + public void run() { + while (keepRunning()) { + try { + final String response = + OntoUMLServerAccessController.requestModelVerification( + ModelElement.generateModel(true), loading); + + if (keepRunning()) { + if (response != null) { + loading.canClosed(); + request.doStop(); + ViewManagerUtils.logVerificationResponse(response); + } else { + loading.canClosed(); + request.doStop(); + } + } else { + loading.canClosed(); + request.doStop(); + ViewManagerUtils.cleanAndShowMessage("Request cancelled by the user."); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/OntoUMLServerAccessController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/OntoUMLServerAccessController.java new file mode 100644 index 00000000..c69f06e7 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/OntoUMLServerAccessController.java @@ -0,0 +1,287 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.vp.plugin.view.IDialogHandler; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.SocketException; +import java.net.URL; +import java.util.stream.Collectors; + +/** + * Class responsible for making requests to the OntoUML Server based on standard end points and + * configured server URL. + * + * @author Claudenir Fonseca + * @author Victor Viola + */ +public class OntoUMLServerAccessController { + + private static final String TRANSFORM_GUFO_SERVICE_ENDPOINT = "/v1/transform/gufo"; + private static final String VERIFICATION_SERVICE_ENDPOINT = "/v1/verify"; + private static final String USER_MESSAGE_BAD_REQUEST = + "There was a internal plugin error and the verification could not be completed."; + private static final String USER_MESSAGE_NOT_FOUND = "Unable to reach the server."; + private static final String USER_MESSAGE_INTERNAL_ERROR = "Internal server error."; + private static final String USER_MESSAGE_UNKNOWN_ERROR_REQUEST = + "Error sending model verification to the server."; + private static final String USER_MESSAGE_UNKNOWN_ERROR_RESPONSE = + "Error receiving model verification response."; + + public static BufferedReader transformToGUFO( + String model, + String baseIRI, + String format, + String uriFormatBy, + String inverse, + String object, + String analysis, + String packages, + String elementMapping, + String packageMapping, + IDialogHandler loading) + throws Exception { + final JsonObject optionsObj = new JsonObject(); + + boolean createObjectProperty = !Boolean.parseBoolean(object); + boolean createInverses = Boolean.parseBoolean(inverse); + boolean preAnalysis = Boolean.parseBoolean(analysis); + boolean prefixPackages = Boolean.parseBoolean(packages); + + optionsObj.addProperty("baseIRI", baseIRI); + optionsObj.addProperty("format", format); + optionsObj.addProperty("uriFormatBy", uriFormatBy); + optionsObj.addProperty("createInverses", createInverses); + optionsObj.addProperty("createObjectProperty", createObjectProperty); + optionsObj.addProperty("preAnalysis", preAnalysis); + optionsObj.addProperty("prefixPackages", prefixPackages); + optionsObj.add("customElementMapping", new Gson().fromJson(elementMapping, JsonObject.class)); + optionsObj.add("customPackageMapping", new Gson().fromJson(packageMapping, JsonObject.class)); + + final JsonObject bodyObj = new JsonObject(); + bodyObj.add("options", optionsObj); + bodyObj.add("model", new JsonParser().parse(model).getAsJsonObject()); + + final GsonBuilder builder = new GsonBuilder(); + final Gson gson = builder.serializeNulls().setPrettyPrinting().create(); + final String body = gson.toJson(bodyObj); + + final ProjectConfigurations configurations = + Configurations.getInstance().getProjectConfigurations(); + final String url; + + if (configurations.isCustomServerEnabled()) { + url = configurations.getServerURL() + TRANSFORM_GUFO_SERVICE_ENDPOINT; + } else { + url = ProjectConfigurations.DEFAULT_SERVER_URL + TRANSFORM_GUFO_SERVICE_ENDPOINT; + } + + loading.shown(); + + try { + final HttpURLConnection request = request(url, body); + final BufferedReader responseReader = + request.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST + ? new BufferedReader(new InputStreamReader(request.getInputStream())) + : new BufferedReader(new InputStreamReader(request.getErrorStream())); + + loading.canClosed(); + + switch (request.getResponseCode()) { + case HttpURLConnection.HTTP_OK: + if (!request.getContentType().equals("text/html")) { + return responseReader; + } else { + if (ViewManagerUtils.exportToGUFOIssueDialogWithOption( + "Server not found.", HttpURLConnection.HTTP_NOT_FOUND)) + return transformToGUFO( + model, + baseIRI, + format, + uriFormatBy, + inverse, + object, + analysis, + packages, + elementMapping, + packageMapping, + loading); + + System.out.println(responseReader.lines().collect(Collectors.joining())); + new Exception("Server not found.").printStackTrace(); + return null; + } + case HttpURLConnection.HTTP_BAD_REQUEST: + ViewManagerUtils.exportToGUFOIssueDialog( + "Unable to transform the model due to an unexpected error.\n" + + "Please check the model for any syntactical errors.\n\n" + + "Warning: partially exporting models to gUFO may introduce syntactical" + + " errors."); + System.out.println(responseReader.lines().collect(Collectors.joining())); + new Exception( + "Unable to transform the model due to an unexpected error.\n" + + "Please check the model for any syntactical errors.\n\n" + + "Warning: partially exporting models to gUFO may introduce syntactical" + + " errors.") + .printStackTrace(); + return null; + case HttpURLConnection.HTTP_NOT_FOUND: + if (ViewManagerUtils.exportToGUFOIssueDialogWithOption( + "Server not found.", HttpURLConnection.HTTP_NOT_FOUND)) + return transformToGUFO( + model, + baseIRI, + format, + uriFormatBy, + inverse, + object, + analysis, + packages, + elementMapping, + packageMapping, + loading); + + System.out.println(responseReader.lines().collect(Collectors.joining())); + new Exception("Server not found.").printStackTrace(); + return null; + case HttpURLConnection.HTTP_INTERNAL_ERROR: + if (ViewManagerUtils.exportToGUFOIssueDialogWithOption( + "Server error.", HttpURLConnection.HTTP_INTERNAL_ERROR)) + return transformToGUFO( + model, + baseIRI, + format, + uriFormatBy, + inverse, + object, + analysis, + packages, + elementMapping, + packageMapping, + loading); + + System.out.println(responseReader.lines().collect(Collectors.joining())); + new Exception("Server error.").printStackTrace(); + return null; + default: + ViewManagerUtils.exportToGUFOIssueDialog("Unexpected error."); + throw new Exception("Unknown error"); + } + } catch (MalformedURLException e) { + ViewManagerUtils.exportToGUFOIssueDialog("Server error."); + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } + + public static String requestModelVerification(String serializedModel, IDialogHandler loading) { + final ProjectConfigurations configurations = + Configurations.getInstance().getProjectConfigurations(); + final String url; + + if (configurations.isCustomServerEnabled()) { + url = configurations.getServerURL() + VERIFICATION_SERVICE_ENDPOINT; + } else { + url = ProjectConfigurations.DEFAULT_SERVER_URL + VERIFICATION_SERVICE_ENDPOINT; + } + + loading.shown(); + + try { + + final HttpURLConnection request = request(url, serializedModel); + final StringBuilder response = new StringBuilder(); + final BufferedReader reader = + request.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST + ? new BufferedReader(new InputStreamReader(request.getInputStream())) + : new BufferedReader(new InputStreamReader(request.getErrorStream())); + + String line = null; + + while ((line = reader.readLine()) != null) { + response.append(line.trim()); + } + + reader.close(); + + loading.canClosed(); + + switch (request.getResponseCode()) { + case HttpURLConnection.HTTP_OK: + if (!request.getContentType().equals("text/html")) { + return response.toString(); + } else { + if (ViewManagerUtils.verificationFailedDialogWithOption( + USER_MESSAGE_NOT_FOUND, HttpURLConnection.HTTP_NOT_FOUND)) + return requestModelVerification(serializedModel, loading); + } + case HttpURLConnection.HTTP_BAD_REQUEST: + ViewManagerUtils.verificationFailedDialog(USER_MESSAGE_BAD_REQUEST); + return null; + case HttpURLConnection.HTTP_NOT_FOUND: + if (ViewManagerUtils.verificationFailedDialogWithOption( + USER_MESSAGE_NOT_FOUND, HttpURLConnection.HTTP_NOT_FOUND)) + return requestModelVerification(serializedModel, loading); + + return null; + case HttpURLConnection.HTTP_INTERNAL_ERROR: + if (ViewManagerUtils.verificationFailedDialogWithOption( + USER_MESSAGE_INTERNAL_ERROR, HttpURLConnection.HTTP_INTERNAL_ERROR)) + return requestModelVerification(serializedModel, loading); + + return null; + default: + ViewManagerUtils.verificationFailedDialog(USER_MESSAGE_UNKNOWN_ERROR_RESPONSE); + return null; + } + + } catch (SocketException e) { + loading.canClosed(); + ViewManagerUtils.verificationFailedDialog(USER_MESSAGE_NOT_FOUND); + e.printStackTrace(); + } catch (IOException e) { + loading.canClosed(); + ViewManagerUtils.verificationFailedDialog(USER_MESSAGE_UNKNOWN_ERROR_RESPONSE); + e.printStackTrace(); + } catch (Exception e) { + loading.canClosed(); + ViewManagerUtils.verificationFailedDialog(USER_MESSAGE_UNKNOWN_ERROR_REQUEST); + e.printStackTrace(); + } + + return null; + } + + private static HttpURLConnection request(String urlString, String body) + throws MalformedURLException, IOException { + final URL url = new URL(urlString); + final HttpURLConnection request = (HttpURLConnection) url.openConnection(); + + request.setRequestMethod("POST"); + request.setRequestProperty("Content-Type", "application/json"); + request.setReadTimeout(60000); + request.setDoOutput(true); + + final OutputStream requestStream = request.getOutputStream(); + final byte[] requestBody = body.getBytes(); + + requestStream.write(requestBody, 0, requestBody.length); + requestStream.flush(); + requestStream.close(); + + return request; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/OpenConfigurationsAction.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/OpenConfigurationsAction.java deleted file mode 100644 index 16f0873d..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/OpenConfigurationsAction.java +++ /dev/null @@ -1,123 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.views.ConfigurationsView; - -import java.awt.*; - -/** - * - * Controller responsible for opening the OntoUML Plugin configurations menu. - * OpenConfigurationsAction contains an implementation of - * IDialogHandler necessary for presenting Java components in - * Visual Paradigm. - * - * @author Claudenir Fonseca - * - */ -public class OpenConfigurationsAction implements VPActionController { - - private ConfigurationsView _configurationsMenuView; - private IDialog _dialog; - - /** - * - * Opens OntoUML Plugin configuration menu. Called when the button is clicked, - * providing access to the action information. - * - * @param action - * - */ - @Override - public void performAction(VPAction action) { - if(OntoUMLPlugin.getConfigWindowOpen() == true) - return; - else - OntoUMLPlugin.setConfigWindowOpen(true); - - ApplicationManager.instance().getViewManager().showDialog(new ConfigurationsDialog()); - } - - /** - * Called when the menu containing the button is accessed allowing for action - * manipulation, such as enable/disable or selecting the button. - * - * OBS: DOES NOT apply to this class. - */ - @Override - public void update(VPAction action) { - } - - /** - * - * Implementation of IDialogHandler necessary for presenting - * Java components in Visual Paradigm. - * - * More information available at - * @link https://images.visual-paradigm.com/docs/plugin_user_guide/Plug-in_Users_Guide.pdf . - * - * @author Claudenir Fonseca - * - */ - protected class ConfigurationsDialog implements IDialogHandler { - - /** - * - * Called once before the dialog is shown. Developer should return the - * content of the dialog (similar to the content pane). - * - */ - @Override - public Component getComponent() { - _configurationsMenuView = new ConfigurationsView( - Configurations.getInstance().getProjectConfigurations()); - return _configurationsMenuView; - } - - /** - * - * Called after the getComponent(). A dialog is created on Visual - * Paradigm internally (it still not shown out). Developer can set the - * outlook of the dialog on prepare(). - * - */ - @Override - public void prepare(IDialog dialog) { - _dialog = dialog; - _dialog.setTitle(OntoUMLPlugin.PLUGIN_NAME + " Configurations"); - _dialog.setModal(false); - _dialog.setResizable(true); - _dialog.setSize(_configurationsMenuView.getWidth(), _configurationsMenuView.getHeight() + 20); - _configurationsMenuView.setContainerDialog(_dialog); - } - - /** - * - * Called when the dialog is shown. - * - */ - @Override - public void shown() {} - - /** - * - * Called when the dialog is closed by the user clicking on the - * close button of the frame. - * - */ - @Override - public boolean canClosed() { - OntoUMLPlugin.setConfigWindowOpen(false); - return true; - } - - } - - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/PaintModelAction.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/PaintModelAction.java deleted file mode 100644 index 6ed3c0b0..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/PaintModelAction.java +++ /dev/null @@ -1,37 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import javax.swing.JOptionPane; - -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; - -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.SmartColoring; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; - -public class PaintModelAction implements VPActionController { - - @Override - public void performAction(VPAction arg0) { - - if (!Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled()) { - final int enableSmartPaint = ViewUtils.smartPaintEnableDialog(); - - if (enableSmartPaint == JOptionPane.YES_OPTION) { - Configurations.getInstance().getProjectConfigurations().setAutomaticColoringEnabled(true); - SmartColoring.paintAll(); - } - } else { - final int proceedSmartPaintAction = ViewUtils.smartPaintConfirmationDialog(); - - if (proceedSmartPaintAction == JOptionPane.YES_OPTION) { - SmartColoring.paintAll(); - } - } - } - - @Override - public void update(VPAction arg0) { - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesActionController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesActionController.java deleted file mode 100644 index efe4ffef..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesActionController.java +++ /dev/null @@ -1,19 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; - -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; - -public class ReloadClassesActionController implements VPActionController { - - @Override - public void performAction(VPAction action) { - OntoUMLPlugin.reload(); - } - - @Override - public void update(VPAction action) { - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesController.java new file mode 100644 index 00000000..c21dc404 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesController.java @@ -0,0 +1,123 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.DiagramManager; +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPActionController; +import com.vp.plugin.diagram.IDiagramUIModel; +import com.vp.plugin.model.IPackage; +import com.vp.plugin.model.factory.IModelElementFactory; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.utils.Stereotype; +import java.util.List; + +public class ReloadClassesController implements VPActionController { + + @Override + public void performAction(VPAction action) { + // OntoUMLPlugin.reload(); + // generateModel(); + reverseDirection(action); + } + + @Override + public void update(VPAction action) {} + + private void reverseDirection(VPAction action) { + ApplicationManager app = ApplicationManager.instance(); + app.reloadPluginClasses(OntoUMLPlugin.PLUGIN_ID); + + // DiagramManager dm = app.getDiagramManager(); + // IDiagramElement[] selectedElements = dm.getSelectedDiagramElements(); + // + // for (int i = 0; selectedElements != null && i < selectedElements.length; i++) { + // IDiagramElement diagramElement = selectedElements[i]; + // IModelElement element = diagramElement.getModelElement(); + // + // if (element == null || + // !IModelElementFactory.MODEL_TYPE_ASSOCIATION.equals(element.getModelType())) { + // continue; + // } + // + // IAssociation association = (IAssociation) element; + // Association.invertAssociation(association); + // IAssociationUIModel originalAssociationView = (IAssociationUIModel) diagramElement; + // IClass originalFrom = (IClass) association.getFrom(); + // IClass originalTo = (IClass) association.getTo(); + // IAssociationEnd originalFromEnd = (IAssociationEnd) association.getFromEnd(); + // IAssociationEnd originalToEnd = (IAssociationEnd) association.getToEnd(); + // + // association.setFrom(originalTo); + // association.setTo(originalFrom); + // + // Point[] points = originalAssociationView.getPoints(); + // IDiagramUIModel diagram = diagramElement.getDiagramUIModel(); + // IAssociationUIModel reverseAssociationView = (IAssociationUIModel) + // dm.createConnector(diagram, association, originalAssociationView.getToShape(), + // originalAssociationView.getFromShape(), null); + // diagramElement.deleteViewOnly(); + // + // if(points != null) { + // for (int j = points.length - 1; j >= 0; j--) { + // reverseAssociationView.addPoint(points[j]); + // } + // } + // reverseAssociationView.resetCaption(); + // IConnectorUIModel reverseAssociationView = (IConnectorUIModel) + // dm.createDiagramElement(diagram, association); + // reverseAssociationView.set + // } + } + + @SuppressWarnings("unused") + private void generateModel() { + final ApplicationManager app = ApplicationManager.instance(); + final DiagramManager dm = app.getDiagramManager(); + final IDiagramUIModel diagram = dm.getActiveDiagram(); + final IPackage pkg = (IPackage) diagram.getParentModel(); + final IModelElementFactory factory = IModelElementFactory.instance(); + + if (diagram == null || pkg == null) { + return; + } + + final List stereotypes = Stereotype.getOntoUMLClassStereotypeNames(); + + for (String sourceStereotype : stereotypes) { + final IPackage sourcePkg = factory.createPackage(); + sourcePkg.setName(sourceStereotype); + pkg.addChild(sourcePkg); + + for (String targetStereotype : stereotypes) { + // // Method getAllowedAssociations() was removed + // final List allowedAssociations = + // OntoUMLConstraintsManager.getAllowedAssociations(sourceStereotype, + // targetStereotype); + + // if(!allowedAssociations.isEmpty()) { + // final IClass source = factory.createClass(); + // final IClass target = factory.createClass(); + // + // source.setName(sourceStereotype + " as Source"); + // target.setName(targetStereotype + " as Target"); + // + // source.addStereotype(sourceStereotype); + // target.addStereotype(targetStereotype); + // + // sourcePkg.addChild(source); + // sourcePkg.addChild(target); + // + // for (String associationStereotype : allowedAssociations) { + // final IAssociation association = factory.createAssociation(); + // + // association.addStereotype(associationStereotype); + // association.setFrom(source); + // association.setTo(target); + // + // sourcePkg.addChild(association); + // } + // } + } + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorAction.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorAction.java deleted file mode 100644 index 089eadf5..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorAction.java +++ /dev/null @@ -1,36 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import java.awt.Desktop; -import java.net.URI; - -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; - -import it.unibz.inf.ontouml.vp.utils.ViewUtils; - -public class ReportErrorAction implements VPActionController { - - final private static String REPORT_URL = "https://forms.gle/btx7CDSy9kn5yb3WA"; - - @Override - public void performAction(VPAction arg0) { - try { - final Desktop desktop = Desktop.getDesktop(); - final URI uri = new URI(REPORT_URL); - desktop.browse(uri); - } catch (UnsupportedOperationException unsupportedException) { - ViewUtils.reportBugErrorDialog(true); - unsupportedException.printStackTrace(); - } catch (SecurityException securityException) { - ViewUtils.reportBugErrorDialog(true); - securityException.printStackTrace(); - } catch(Exception e) { - ViewUtils.reportBugErrorDialog(false); - e.printStackTrace(); - } - } - - @Override - public void update(VPAction arg0) {} - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorController.java new file mode 100644 index 00000000..fb639ba6 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorController.java @@ -0,0 +1,33 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPActionController; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import java.awt.Desktop; +import java.net.URI; + +public class ReportErrorController implements VPActionController { + + private static final String REPORT_URL = "https://forms.gle/btx7CDSy9kn5yb3WA"; + + @Override + public void performAction(VPAction arg0) { + try { + final Desktop desktop = Desktop.getDesktop(); + final URI uri = new URI(REPORT_URL); + desktop.browse(uri); + } catch (UnsupportedOperationException unsupportedException) { + ViewManagerUtils.reportBugErrorDialog(true); + unsupportedException.printStackTrace(); + } catch (SecurityException securityException) { + ViewManagerUtils.reportBugErrorDialog(true); + securityException.printStackTrace(); + } catch (Exception e) { + ViewManagerUtils.reportBugErrorDialog(false); + e.printStackTrace(); + } + } + + @Override + public void update(VPAction arg0) {} +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/SettingsMenuController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/SettingsMenuController.java new file mode 100644 index 00000000..921dc2fc --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/SettingsMenuController.java @@ -0,0 +1,95 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPActionController; +import com.vp.plugin.view.IDialog; +import com.vp.plugin.view.IDialogHandler; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.views.ConfigurationsView; +import java.awt.*; + +/** + * Controller responsible for opening the OntoUML Plugin configurations menu. + * OpenConfigurationsAction contains an implementation of IDialogHandler + * necessary for presenting Java components in Visual Paradigm. + * + * @author Claudenir Fonseca + */ +public class SettingsMenuController implements VPActionController { + + private ConfigurationsView _configurationsMenuView; + private IDialog _dialog; + + /** + * Opens OntoUML Plugin configuration menu. Called when the button is clicked, providing access to + * the action information. + * + * @param action + */ + @Override + public void performAction(VPAction action) { + if (OntoUMLPlugin.getConfigWindowOpen() == true) return; + else OntoUMLPlugin.setConfigWindowOpen(true); + + ApplicationManager.instance().getViewManager().showDialog(new ConfigurationsDialog()); + } + + /** + * Called when the menu containing the button is accessed allowing for action manipulation, such + * as enable/disable or selecting the button. + * + *

OBS: DOES NOT apply to this class. + */ + @Override + public void update(VPAction action) {} + + /** + * Implementation of IDialogHandler necessary for presenting Java components in + * Visual Paradigm. + * + *

More information available at + * + * @link https://images.visual-paradigm.com/docs/plugin_user_guide/Plug-in_Users_Guide.pdf . + * @author Claudenir Fonseca + */ + protected class ConfigurationsDialog implements IDialogHandler { + + /** + * Called once before the dialog is shown. Developer should return the content of the dialog + * (similar to the content pane). + */ + @Override + public Component getComponent() { + _configurationsMenuView = + new ConfigurationsView(Configurations.getInstance().getProjectConfigurations()); + return _configurationsMenuView; + } + + /** + * Called after the getComponent(). A dialog is created on Visual Paradigm internally (it still + * not shown out). Developer can set the outlook of the dialog on prepare(). + */ + @Override + public void prepare(IDialog dialog) { + _dialog = dialog; + _dialog.setTitle(OntoUMLPlugin.PLUGIN_NAME + " Configurations"); + _dialog.setModal(false); + _dialog.setResizable(true); + _dialog.setSize(_configurationsMenuView.getWidth(), _configurationsMenuView.getHeight() + 20); + _configurationsMenuView.setContainerDialog(_dialog); + } + + /** Called when the dialog is shown. */ + @Override + public void shown() {} + + /** Called when the dialog is closed by the user clicking on the close button of the frame. */ + @Override + public boolean canClosed() { + OntoUMLPlugin.setConfigWindowOpen(false); + return true; + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/SmartModellingController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/SmartModellingController.java new file mode 100644 index 00000000..9757368b --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/SmartModellingController.java @@ -0,0 +1,70 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IAssociationEnd; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IModelElement; +import it.unibz.inf.ontouml.vp.model.uml.Association; +import it.unibz.inf.ontouml.vp.utils.Stereotype; + +public class SmartModellingController { + + public static void setAggregationKind(IModelElement element) { + IAssociation association = (IAssociation) element; + IAssociationEnd compositionFromEnd = (IAssociationEnd) association.getFromEnd(); + IAssociationEnd compositionToEnd = (IAssociationEnd) association.getToEnd(); + + if (compositionToEnd.getAggregationKind().equals(IAssociationEnd.AGGREGATION_KIND_NONE)) { + compositionToEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_COMPOSITED); + } + + compositionFromEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); + } + + public static void removeAggregationKind(IModelElement element) { + IAssociationEnd compositionFromEnd = (IAssociationEnd) ((IAssociation) element).getFromEnd(); + IAssociationEnd compositionToEnd = (IAssociationEnd) ((IAssociation) element).getToEnd(); + + compositionFromEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); + compositionToEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); + } + + private static boolean setCardinalityIfEmpty(IAssociationEnd end, String cardinality) { + + if (end.getMultiplicity() == null || end.getMultiplicity().equals("Unspecified")) { + end.setMultiplicity(cardinality); + return true; + } else { + return false; + } + } + + public static void setAssociationMetaProperties(IAssociation association) { + Association.setDefaultMultiplicity(association, false); + Association.setDefaultAggregationKind(association, false); + Association.setNavigability(association); + } + + public static void setClassMetaProperties(IClass _class) { + if (_class == null) return; + + String[] stereotypes = _class.toStereotypeArray(); + + if (stereotypes == null || stereotypes.length != 1) return; + + switch (stereotypes[0]) { + case Stereotype.CATEGORY: + _class.setAbstract(true); + break; + case Stereotype.ROLE_MIXIN: + _class.setAbstract(true); + break; + case Stereotype.PHASE_MIXIN: + _class.setAbstract(true); + break; + case Stereotype.MIXIN: + _class.setAbstract(true); + break; + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginAction.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginAction.java deleted file mode 100644 index e8d8b5b0..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginAction.java +++ /dev/null @@ -1,114 +0,0 @@ -package it.unibz.inf.ontouml.vp.controllers; - -import java.awt.FileDialog; -import java.awt.Frame; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.function.Predicate; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.VPPluginInfo; -import com.vp.plugin.action.VPAction; -import com.vp.plugin.action.VPActionController; - -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; -//import net.lingala.zip4j.core.ZipFile; -//import net.lingala.zip4j.exception.ZipException; - -public class UpdatePluginAction implements VPActionController { - - private static final int BUFFER_SIZE = 4096; - - @Override - public void performAction(VPAction arg0) { - ViewUtils.updateDialog(); - - FileDialog fd = new FileDialog((Frame) ApplicationManager.instance().getViewManager().getRootFrame(), - "Select the zip file containing the OntoUML Plugin release", FileDialog.LOAD); - - fd.setDirectory(null); - fd.setFile(null); - fd.setFilenameFilter((dir, name) -> name != null && name.endsWith(".zip")); - fd.setVisible(true); - - if (fd.getDirectory() != null && fd.getFile() != null) { - final String fileName = fd.getFile(); - final VPPluginInfo info = ApplicationManager.instance().getPluginInfo(OntoUMLPlugin.PLUGIN_ID); - final File pluginsDir = info.getPluginDir().getParentFile(); - final File zipFile = new File(fd.getDirectory(), fileName); - final String destDirName = fileName.substring(0, fileName.lastIndexOf(".zip")); - try { - unzip(zipFile, pluginsDir.getAbsolutePath() + File.separator + destDirName); - deleteFolderContents(pluginsDir, - content -> content.isDirectory() && content.getName().contains("ontouml") - && !content.getName().equals("ontouml-vp-plugin-0.3.0-SNAPSHOT")); - ViewUtils.updateSuccessDialog(); - } catch (Exception e) { - ViewUtils.updateErrorDialog(); - e.printStackTrace(); - } - } - } - - @Override - public void update(VPAction arg0) { - } - - public void unzip(File zipFile, String destDirectory) throws IOException { - File destDir = new File(destDirectory); - if (!destDir.exists()) { - destDir.mkdir(); - } - ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile)); - ZipEntry entry = zipIn.getNextEntry(); - // iterates over entries in the zip file - while (entry != null) { - String filePath = destDirectory + File.separator + entry.getName(); - if (!entry.isDirectory()) { - // if the entry is a file, extracts it - extractFile(zipIn, filePath); - } else { - // if the entry is a directory, make the directory - File dir = new File(filePath); - dir.mkdir(); - } - zipIn.closeEntry(); - entry = zipIn.getNextEntry(); - } - zipIn.close(); - } - - private void extractFile(ZipInputStream zipIn, String filePath) throws IOException { - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); - byte[] bytesIn = new byte[BUFFER_SIZE]; - int read = 0; - while ((read = zipIn.read(bytesIn)) != -1) { - bos.write(bytesIn, 0, read); - } - bos.close(); - } - - private void deleteFolderContents(File folder, Predicate condition) { - final File[] contents = folder.listFiles(); - - if (contents == null) { - return; - } - - for (File content : contents) { - if (condition == null || condition.test(content)) { - if (content.isDirectory()) { - deleteFolderContents(content, null); - } - content.delete(); - } - } - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginController.java new file mode 100644 index 00000000..a9f97256 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginController.java @@ -0,0 +1,111 @@ +package it.unibz.inf.ontouml.vp.controllers; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.action.VPAction; +import com.vp.plugin.action.VPActionController; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.model.GitHubRelease; +import it.unibz.inf.ontouml.vp.model.GitHubReleaseAsset; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.function.Predicate; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class UpdatePluginController implements VPActionController { + + private static final int BUFFER_SIZE = 4096; + + @Override + public void performAction(VPAction arg0) { + + try { + GitHubAccessController.lookupUpdates(); + GitHubRelease selectedRelease = ViewManagerUtils.updateDialog(); + GitHubReleaseAsset pluginAsset = + selectedRelease != null ? selectedRelease.getInstallationFileAsset() : null; + + if (selectedRelease == null || pluginAsset == null) { + return; + } + + File downloadedFile = GitHubAccessController.downloadReleaseAsset(pluginAsset); + + String destinationDirName = pluginAsset.getName().replace(".zip", ""); + File pluginDir = + ApplicationManager.instance().getPluginInfo(OntoUMLPlugin.PLUGIN_ID).getPluginDir(); + File destinationDir = new File(pluginDir.getParentFile(), destinationDirName); + + UpdatePluginController.unzip(downloadedFile, destinationDir); + deleteFolderContents( + pluginDir.getParentFile(), + content -> + content.isDirectory() + && content.getName().contains("ontouml-vp-plugin") + && !content.getName().equals(destinationDirName)); + ViewManagerUtils.updateSuccessDialog(); + } catch (Exception e) { + ViewManagerUtils.updateErrorDialog(); + e.printStackTrace(); + } + } + + @Override + public void update(VPAction arg0) {} + + private static void unzip(File zipFile, File destDirectory) throws IOException { + if (!destDirectory.exists()) { + destDirectory.mkdir(); + } + ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile)); + ZipEntry entry = zipIn.getNextEntry(); + // iterates over entries in the zip file + while (entry != null) { + String filePath = destDirectory + File.separator + entry.getName(); + if (!entry.isDirectory()) { + // if the entry is a file, extracts it + extractFile(zipIn, filePath); + } else { + // if the entry is a directory, make the directory + File dir = new File(filePath); + dir.mkdir(); + } + zipIn.closeEntry(); + entry = zipIn.getNextEntry(); + } + zipIn.close(); + } + + private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException { + File file = new File(filePath); + file.createNewFile(); + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = zipIn.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + } + + private void deleteFolderContents(File folder, Predicate condition) { + final File[] contents = folder.listFiles(); + + if (contents == null) { + return; + } + + for (File content : contents) { + if (condition == null || condition.test(content)) { + if (content.isDirectory()) { + deleteFolderContents(content, null); + } + content.delete(); + } + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/ActionIds.java b/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/ActionIds.java deleted file mode 100644 index 292b4ef6..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/ActionIds.java +++ /dev/null @@ -1,210 +0,0 @@ -package it.unibz.inf.ontouml.vp.features.constraints; - -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; - -public final class ActionIds { - - // Class stereotypes (ordered as in plugin.xml) - public static final String TYPE = "it.unibz.inf.ontouml.vp.addTypeStereotype"; - - public static final String HISTORICAL_ROLE = "it.unibz.inf.ontouml.vp.addHistoricalRoleStereotype"; - public static final String HISTORICAL_ROLE_MIXIN = "it.unibz.inf.ontouml.vp.addHistoricalRoleMixinStereotype"; - public static final String EVENT = "it.unibz.inf.ontouml.vp.addEventStereotype"; - - public static final String SITUATION = "it.unibz.inf.ontouml.vp.addSituationStereotype"; - - public static final String ENUMERATION = "it.unibz.inf.ontouml.vp.addEnumerationStereotype"; - public static final String DATATYPE = "it.unibz.inf.ontouml.vp.addDatatypeStereotype"; - - public static final String SUBKIND = "it.unibz.inf.ontouml.vp.addSubkindStereotype"; - public static final String ROLE_MIXIN = "it.unibz.inf.ontouml.vp.addRoleMixinStereotype"; - public static final String ROLE = "it.unibz.inf.ontouml.vp.addRoleStereotype"; - public static final String RELATOR = "it.unibz.inf.ontouml.vp.addRelatorStereotype"; - public static final String QUANTITY = "it.unibz.inf.ontouml.vp.addQuantityStereotype"; - public static final String QUALITY = "it.unibz.inf.ontouml.vp.addQualityStereotype"; - public static final String PHASE_MIXIN = "it.unibz.inf.ontouml.vp.addPhaseMixinStereotype"; - public static final String PHASE = "it.unibz.inf.ontouml.vp.addPhaseStereotype"; - public static final String MODE = "it.unibz.inf.ontouml.vp.addModeStereotype"; - public static final String MIXIN = "it.unibz.inf.ontouml.vp.addMixinStereotype"; - public static final String KIND = "it.unibz.inf.ontouml.vp.addKindStereotype"; - public static final String COLLECTIVE = "it.unibz.inf.ontouml.vp.addCollectiveStereotype"; - public static final String CATEGORY = "it.unibz.inf.ontouml.vp.addCategoryStereotype"; - - // Association stereotypes (ordered as in plugin.xml) - public static final String INSTANTIATION = "it.unibz.inf.ontouml.vp.addInstantiationStereotype"; - - public static final String TERMINATION = "it.unibz.inf.ontouml.vp.addTerminationStereotype"; - public static final String PARTICIPATIONAL = "it.unibz.inf.ontouml.vp.addParticipationalStereotype"; - public static final String PARTICIPATION = "it.unibz.inf.ontouml.vp.addParticipationStereotype"; - public static final String HISTORICAL_DEPENDENCE = "it.unibz.inf.ontouml.vp.addHistoricalDependenceStereotype"; - public static final String CREATION = "it.unibz.inf.ontouml.vp.addCreationStereotype"; - public static final String MANIFESTATION = "it.unibz.inf.ontouml.vp.addManifestationStereotype"; - - public static final String BRINGS_ABOUT= "it.unibz.inf.ontouml.vp.addBringsAboutStereotype"; - public static final String TRIGGERS= "it.unibz.inf.ontouml.vp.addTriggersStereotype"; - - public static final String SUB_QUANTITY_OF = "it.unibz.inf.ontouml.vp.addSubQuantityStereotype"; - public static final String SUB_COLLECTION_OF = "it.unibz.inf.ontouml.vp.addSubCollectionStereotype"; - public static final String MEMBER_OF = "it.unibz.inf.ontouml.vp.addMemberOfStereotype"; - public static final String MEDIATION = "it.unibz.inf.ontouml.vp.addMediationStereotype"; - public static final String MATERIAL = "it.unibz.inf.ontouml.vp.addMaterialStereotype"; - public static final String EXTERNAL_DEPENDENCE = "it.unibz.inf.ontouml.vp.addExternalDependenceStereotype"; - public static final String COMPONENT_OF = "it.unibz.inf.ontouml.vp.addComponentOfStereotype"; - public static final String COMPARATIVE = "it.unibz.inf.ontouml.vp.addComparativeStereotype"; - public static final String CHARACTERIZATION = "it.unibz.inf.ontouml.vp.addCharacterizationStereotype"; - - // Attribute stereotypes (ordered as in plugin.xml) - public static final String END = "it.unibz.inf.ontouml.vp.addEndStereotype"; - public static final String BEGIN = "it.unibz.inf.ontouml.vp.addBeginStereotype"; - -// //Fixed Menu ActionIds - public static final String TYPE_FIXED = "it.unibz.inf.ontouml.vp.addTypeStereotype.fixedMenu"; - - public static final String HISTORICAL_ROLE_FIXED = "it.unibz.inf.ontouml.vp.addHistoricalRoleStereotype.fixedMenu"; - public static final String HISTORICAL_ROLE_MIXIN_FIXED = "it.unibz.inf.ontouml.vp.addHistoricalRoleMixinStereotype.fixedMenu"; - public static final String EVENT_FIXED = "it.unibz.inf.ontouml.vp.addEventStereotype.fixedMenu"; - - public static final String SITUATION_FIXED = "it.unibz.inf.ontouml.vp.addSituationStereotype.fixedMenu"; - - public static final String ENUMERATION_FIXED = "it.unibz.inf.ontouml.vp.addEnumerationStereotype.fixedMenu"; - public static final String DATATYPE_FIXED = "it.unibz.inf.ontouml.vp.addDatatypeStereotype.fixedMenu"; - - public static final String SUBKIND_FIXED = "it.unibz.inf.ontouml.vp.addSubkindStereotype.fixedMenu"; - public static final String ROLE_MIXIN_FIXED = "it.unibz.inf.ontouml.vp.addRoleMixinStereotype.fixedMenu"; - public static final String ROLE_FIXED = "it.unibz.inf.ontouml.vp.addRoleStereotype.fixedMenu"; - public static final String RELATOR_FIXED = "it.unibz.inf.ontouml.vp.addRelatorStereotype.fixedMenu"; - public static final String QUANTITY_FIXED = "it.unibz.inf.ontouml.vp.addQuantityStereotype.fixedMenu"; - public static final String QUALITY_FIXED = "it.unibz.inf.ontouml.vp.addQualityStereotype.fixedMenu"; - public static final String PHASE_MIXIN_FIXED = "it.unibz.inf.ontouml.vp.addPhaseMixinStereotype.fixedMenu"; - public static final String PHASE_FIXED = "it.unibz.inf.ontouml.vp.addPhaseStereotype.fixedMenu"; - public static final String MODE_FIXED = "it.unibz.inf.ontouml.vp.addModeStereotype.fixedMenu"; - public static final String MIXIN_FIXED = "it.unibz.inf.ontouml.vp.addMixinStereotype.fixedMenu"; - public static final String KIND_FIXED = "it.unibz.inf.ontouml.vp.addKindStereotype.fixedMenu"; - public static final String COLLECTIVE_FIXED = "it.unibz.inf.ontouml.vp.addCollectiveStereotype.fixedMenu"; - public static final String CATEGORY_FIXED = "it.unibz.inf.ontouml.vp.addCategoryStereotype.fixedMenu"; - - // Association stereotypes (ordered as in plugin.xml) - public static final String INSTANTIATION_FIXED = "it.unibz.inf.ontouml.vp.addInstantiationStereotype.fixedMenu"; - - public static final String TERMINATION_FIXED = "it.unibz.inf.ontouml.vp.addTerminationStereotype.fixedMenu"; - public static final String PARTICIPATIONAL_FIXED = "it.unibz.inf.ontouml.vp.addParticipationalStereotype.fixedMenu"; - public static final String PARTICIPATION_FIXED = "it.unibz.inf.ontouml.vp.addParticipationStereotype.fixedMenu"; - public static final String HISTORICAL_DEPENDENCE_FIXED = "it.unibz.inf.ontouml.vp.addHistoricalDependenceStereotype.fixedMenu"; - public static final String CREATION_FIXED = "it.unibz.inf.ontouml.vp.addCreationStereotype.fixedMenu"; - public static final String MANIFESTATION_FIXED = "it.unibz.inf.ontouml.vp.addManifestationStereotype.fixedMenu"; - - public static final String BRINGS_ABOUT_FIXED = "it.unibz.inf.ontouml.vp.addBringsStereotype.fixedMenu"; - public static final String TRIGGERS_FIXED = "it.unibz.inf.ontouml.vp.addTriggersStereotype.fixedMenu"; - - public static final String SUB_QUANTITY_OF_FIXED = "it.unibz.inf.ontouml.vp.addSubQuantityStereotype.fixedMenu"; - public static final String SUB_COLLECTION_OF_FIXED = "it.unibz.inf.ontouml.vp.addSubCollectionStereotype.fixedMenu"; - public static final String MEMBER_OF_FIXED = "it.unibz.inf.ontouml.vp.addMemberOfStereotype.fixedMenu"; - public static final String MEDIATION_FIXED = "it.unibz.inf.ontouml.vp.addMediationStereotype.fixedMenu"; - public static final String MATERIAL_FIXED = "it.unibz.inf.ontouml.vp.addMaterialStereotype.fixedMenu"; - public static final String EXTERNAL_DEPENDENCE_FIXED = "it.unibz.inf.ontouml.vp.addExternalDependenceStereotype.fixedMenu"; - public static final String COMPONENT_OF_FIXED = "it.unibz.inf.ontouml.vp.addComponentOfStereotype.fixedMenu"; - public static final String COMPARATIVE_FIXED = "it.unibz.inf.ontouml.vp.addComparativeStereotype.fixedMenu"; - public static final String CHARACTERIZATION_FIXED = "it.unibz.inf.ontouml.vp.addCharacterizationStereotype.fixedMenu"; - - // Attribute stereotypes (ordered as in plugin.xml) - public static final String END_FIXED = "it.unibz.inf.ontouml.vp.addEndStereotype.fixedMenu"; - public static final String BEGIN_FIXED = "it.unibz.inf.ontouml.vp.addBeginStereotype.fixedMenu"; - - // Properties menu options IDs - public static final String PROPERTY_SET_RESTRICTED_TO = "it.unibz.inf.ontouml.vp.ClassProperties.restrictedTo"; - public static final String PROPERTY_SET_IS_EXTENSIONAL = "it.unibz.inf.ontouml.vp.ClassProperties.isExtensional"; - public static final String PROPERTY_SET_IS_DERIVED = "it.unibz.inf.ontouml.vp.ClassProperties.isDerived"; - public static final String PROPERTY_SET_IS_ABSTRACT = "it.unibz.inf.ontouml.vp.ClassProperties.isAbstract"; - public static final String PROPERTY_SET_IS_POWERTYPE = "it.unibz.inf.ontouml.vp.ClassProperties.isPowertype"; - public static final String PROPERTY_SET_ORDER = "it.unibz.inf.ontouml.vp.ClassProperties.order"; - - public static String classStereotypeToActionID(String stereotype) { - switch(stereotype) { - case StereotypeUtils.STR_TYPE: - return TYPE; - case StereotypeUtils.STR_HISTORICAL_ROLE: - return HISTORICAL_ROLE; - case StereotypeUtils.STR_HISTORICAL_ROLE_MIXIN: - return HISTORICAL_ROLE_MIXIN; - case StereotypeUtils.STR_EVENT: - return EVENT; - case StereotypeUtils.STR_SITUATION: - return SITUATION; - case StereotypeUtils.STR_CATEGORY: - return CATEGORY; - case StereotypeUtils.STR_MIXIN: - return MIXIN; - case StereotypeUtils.STR_ROLE_MIXIN: - return ROLE_MIXIN; - case StereotypeUtils.STR_PHASE_MIXIN: - return PHASE_MIXIN; - case StereotypeUtils.STR_KIND: - return KIND; - case StereotypeUtils.STR_COLLECTIVE: - return COLLECTIVE; - case StereotypeUtils.STR_QUANTITY: - return QUANTITY; - case StereotypeUtils.STR_RELATOR: - return RELATOR; - case StereotypeUtils.STR_QUALITY: - return QUALITY; - case StereotypeUtils.STR_MODE: - return MODE; - case StereotypeUtils.STR_SUBKIND: - return SUBKIND; - case StereotypeUtils.STR_ROLE: - return ROLE; - case StereotypeUtils.STR_PHASE: - return PHASE; - case StereotypeUtils.STR_ENUMERATION: - return ENUMERATION; - case StereotypeUtils.STR_DATATYPE: - return DATATYPE; - default: - return null; - } - } - - public static String associationStereotypeToActionID(String stereotype) { - switch(stereotype) { - case StereotypeUtils.STR_INSTANTIATION: - return INSTANTIATION; - case StereotypeUtils.STR_TERMINATION: - return TERMINATION; - case StereotypeUtils.STR_PARTICIPATIONAL: - return PARTICIPATIONAL; - case StereotypeUtils.STR_PARTICIPATION: - return PARTICIPATION; - case StereotypeUtils.STR_HISTORICAL_DEPENDENCE: - return HISTORICAL_DEPENDENCE; - case StereotypeUtils.STR_CREATION: - return CREATION; - case StereotypeUtils.STR_MANIFESTATION: - return MANIFESTATION; - case StereotypeUtils.STR_BRINGS_ABOUT: - return BRINGS_ABOUT; - case StereotypeUtils.STR_TRIGGERS: - return TRIGGERS; - case StereotypeUtils.STR_SUB_QUANTITY_OF: - return SUB_QUANTITY_OF; - case StereotypeUtils.STR_SUB_COLLECTION_OF: - return SUB_COLLECTION_OF; - case StereotypeUtils.STR_MEMBER_OF: - return MEMBER_OF; - case StereotypeUtils.STR_MEDIATION: - return MEDIATION; - case StereotypeUtils.STR_MATERIAL: - return MATERIAL; - case StereotypeUtils.STR_EXTERNAL_DEPENDENCE: - return EXTERNAL_DEPENDENCE; - case StereotypeUtils.STR_COMPONENT_OF: - return COMPONENT_OF; - case StereotypeUtils.STR_COMPARATIVE: - return COMPARATIVE; - case StereotypeUtils.STR_CHARACTERIZATION: - return CHARACTERIZATION; - default: - return null; - } - } -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/AssociationConstraints.java b/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/AssociationConstraints.java deleted file mode 100644 index 8eb7ed24..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/AssociationConstraints.java +++ /dev/null @@ -1,84 +0,0 @@ -package it.unibz.inf.ontouml.vp.features.constraints; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.VPPluginInfo; - -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; - -public class AssociationConstraints { - - final private static Type mapOfListsType = new TypeToken>>() { - }.getType(); - private static String filename = "association_constraints.json"; - private static String filepath; - - private static Map> constraints; - - private static void loadConstraints() { - try { - if(filepath == null) { - final ApplicationManager app = ApplicationManager.instance(); - final VPPluginInfo[] plugins = app.getPluginInfos(); - - for (VPPluginInfo plugin : plugins) { - if(plugin.getPluginId().equals(OntoUMLPlugin.PLUGIN_ID)) { - File pluginDir = plugin.getPluginDir(); - filepath = pluginDir.getAbsolutePath() + File.separator + filename; - } - } - } - - final JsonParser parser = new JsonParser(); - final JsonElement element = parser.parse(new FileReader(filepath)); - final Gson gson = new Gson(); - constraints = gson.fromJson(element, mapOfListsType); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - public static List getAllowedActionIDs(String sourceStereotype, String targetStereotype) { - if(constraints == null) { - loadConstraints(); - } - - List allowedStereotypes = constraints.get(sourceStereotype + ":" + targetStereotype); - - if(allowedStereotypes == null) { - allowedStereotypes = new ArrayList(); - } - - return allowedStereotypes - .stream() - .map(allowed -> ActionIds.associationStereotypeToActionID(allowed)) - .collect(Collectors.toList()); - } - - public static List getAllowedAssociations(String sourceStereotype, String targetStereotype) { - if(constraints == null) { - loadConstraints(); - } - - List allowedStereotypes = constraints.get(sourceStereotype + ":" + targetStereotype); - - if(allowedStereotypes == null) { - allowedStereotypes = new ArrayList(); - } - - return allowedStereotypes; - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/ClassConstraints.java b/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/ClassConstraints.java deleted file mode 100644 index 5039966d..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/features/constraints/ClassConstraints.java +++ /dev/null @@ -1,92 +0,0 @@ -package it.unibz.inf.ontouml.vp.features.constraints; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.VPPluginInfo; - -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; - -public class ClassConstraints { - - final private static Type mapOfListsType = new TypeToken>>() { - }.getType(); - private static String filename = "generalization_constraints.json"; - private static String filepath; - - private static JsonObject constraints; - private static Map> allowedSuperClassesFor, allowedSubClassesFor; - - private static void loadConstraints() { - try { - if(filepath == null) { - final ApplicationManager app = ApplicationManager.instance(); - final VPPluginInfo[] plugins = app.getPluginInfos(); - - for (VPPluginInfo plugin : plugins) { - if(plugin.getPluginId().equals(OntoUMLPlugin.PLUGIN_ID)) { - File pluginDir = plugin.getPluginDir(); - filepath = pluginDir.getAbsolutePath() + File.separator + filename; - } - } - } - - final JsonParser parser = new JsonParser(); - final JsonElement element = parser.parse(new FileReader(filepath)); - constraints = element.getAsJsonObject(); - - final Gson gson = new Gson(); - allowedSubClassesFor = gson.fromJson(constraints.getAsJsonObject("allowedSubClassesFor"), mapOfListsType); - allowedSuperClassesFor = gson.fromJson(constraints.getAsJsonObject("allowedSuperClassesFor"), mapOfListsType); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - - public static List getAllowedActionIDsOnGeneral(String stereotype) { - if(constraints == null) { - loadConstraints(); - } - - List allowedStereotypes = allowedSubClassesFor.get(stereotype); - - if(allowedStereotypes == null) { - allowedStereotypes = new ArrayList(); - } - - return allowedStereotypes - .stream() - .map(allowed -> ActionIds.classStereotypeToActionID(allowed)) - .collect(Collectors.toList()); - } - - public static List getAllowedActionIDsOnSpecific(String stereotype) { - if(constraints == null) { - loadConstraints(); - } - - List allowedStereotypes = allowedSuperClassesFor.get(stereotype); - - if(allowedStereotypes == null) { - allowedStereotypes = new ArrayList(); - } - - return allowedStereotypes - .stream() - .map(allowed -> ActionIds.classStereotypeToActionID(allowed)) - .collect(Collectors.toList()); - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/listeners/DiagramListener.java b/src/main/java/it/unibz/inf/ontouml/vp/listeners/DiagramListener.java index 3a471184..39b14a06 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/listeners/DiagramListener.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/listeners/DiagramListener.java @@ -1,73 +1,69 @@ package it.unibz.inf.ontouml.vp.listeners; -import java.util.Iterator; - import com.vp.plugin.diagram.IDiagramElement; import com.vp.plugin.diagram.IDiagramListener; import com.vp.plugin.diagram.IDiagramUIModel; import com.vp.plugin.diagram.shape.IClassUIModel; - -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.SmartColoring; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.utils.SmartColoringUtils; +import java.util.Iterator; public class DiagramListener implements IDiagramListener { - public DiagramListener() {} + public DiagramListener() {} - @Override - public void diagramElementAdded(IDiagramUIModel diagram, IDiagramElement shape) { - try { - smartPaint(shape); - } catch (Exception e) { - System.err.println("An error ocurred while adding an element to diagram."); - e.printStackTrace(); - } - } + @Override + public void diagramElementAdded(IDiagramUIModel diagram, IDiagramElement shape) { + try { + smartPaint(shape); + } catch (Exception e) { + System.err.println("An error ocurred while adding an element to diagram."); + e.printStackTrace(); + } + } - @Override - public void diagramElementRemoved(IDiagramUIModel diagram, IDiagramElement shape) {} + @Override + public void diagramElementRemoved(IDiagramUIModel diagram, IDiagramElement shape) {} - @Override - public void diagramUIModelLoaded(IDiagramUIModel diagram) { - try { - smartPaint(diagram); - } catch (Exception e) { - System.err.println("An error ocurred while adding an element to diagram."); - e.printStackTrace(); - } - } + @Override + public void diagramUIModelLoaded(IDiagramUIModel diagram) { + try { + smartPaint(diagram); + } catch (Exception e) { + System.err.println("An error ocurred while adding an element to diagram."); + e.printStackTrace(); + } + } - @Override - public void diagramUIModelPropertyChanged(IDiagramUIModel diagram, String propertyName, Object originalProperty, - Object modifiedProperty) {} + @Override + public void diagramUIModelPropertyChanged( + IDiagramUIModel diagram, + String propertyName, + Object originalProperty, + Object modifiedProperty) {} - @Override - public void diagramUIModelRenamed(IDiagramUIModel diagram) {} + @Override + public void diagramUIModelRenamed(IDiagramUIModel diagram) {} - private void smartPaint(IDiagramElement diagramElement) { - if ( - diagramElement != null && - diagramElement instanceof IClassUIModel && - Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled() - ) { - SmartColoring.paint((IClassUIModel) diagramElement); - } - } + private void smartPaint(IDiagramElement diagramElement) { + if (diagramElement != null + && diagramElement instanceof IClassUIModel + && Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled()) { + SmartColoringUtils.paint((IClassUIModel) diagramElement); + } + } - private void smartPaint(IDiagramUIModel diagram) { - if ( - diagram != null && - Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled() - ) { - final Iterator iter = diagram.diagramElementIterator(); - while(iter != null && iter.hasNext()) { - final IDiagramElement next = (IDiagramElement) iter.next(); - - if(next instanceof IClassUIModel) { - SmartColoring.paint((IClassUIModel) next); - } - } - } - } + private void smartPaint(IDiagramUIModel diagram) { + if (diagram != null + && Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled()) { + final Iterator iter = diagram.diagramElementIterator(); + while (iter != null && iter.hasNext()) { + final IDiagramElement next = (IDiagramElement) iter.next(); -} \ No newline at end of file + if (next instanceof IClassUIModel) { + SmartColoringUtils.paint((IClassUIModel) next); + } + } + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/listeners/IssueLogMenuListener.java b/src/main/java/it/unibz/inf/ontouml/vp/listeners/IssueLogMenuListener.java new file mode 100644 index 00000000..2915533a --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/listeners/IssueLogMenuListener.java @@ -0,0 +1,53 @@ +package it.unibz.inf.ontouml.vp.listeners; + +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import it.unibz.inf.ontouml.vp.views.IssueLogMenu; +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.ArrayList; +import javax.swing.*; + +public final class IssueLogMenuListener extends MouseAdapter { + private ArrayList idModelElementList; + private JList messageList; + + public IssueLogMenuListener(ArrayList list, JList messages) { + super(); + idModelElementList = list; + messageList = messages; + } + + @Override + public void mouseMoved(MouseEvent e) { + final Point p = e.getPoint(); + final int index = messageList.locationToIndex(p); + + messageList.setSelectedIndex(index); + } + + @Override + public void mouseExited(MouseEvent e) { + messageList.clearSelection(); + } + + public void mouseReleased(MouseEvent e) { + doPop(e); + } + + private void doPop(MouseEvent e) { + IssueLogMenu menu; + String idModelElement = idModelElementList.get(messageList.locationToIndex(e.getPoint())); + + if (idModelElement == null) { + menu = new IssueLogMenu(); + } else { + menu = new IssueLogMenu(idModelElement); + if (!ViewManagerUtils.isElementInAnyDiagram(idModelElement)) { + menu.disableItem("Take me there!"); + } + } + + menu.show(e.getComponent(), e.getX(), e.getY()); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/listeners/ModelListener.java b/src/main/java/it/unibz/inf/ontouml/vp/listeners/ModelListener.java index f0c75a3d..bf45ec20 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/listeners/ModelListener.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/listeners/ModelListener.java @@ -1,229 +1,260 @@ package it.unibz.inf.ontouml.vp.listeners; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IGeneralization; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.uml.Class; +import it.unibz.inf.ontouml.vp.model.uml.Generalization; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.utils.RestrictedTo; +import it.unibz.inf.ontouml.vp.utils.SmartColoringUtils; +import it.unibz.inf.ontouml.vp.utils.Stereotype; +import it.unibz.inf.ontouml.vp.utils.StereotypesManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; +import java.util.List; import java.util.Set; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.IGeneralization; - -import it.unibz.inf.ontouml.vp.model.Class; -import it.unibz.inf.ontouml.vp.model.Generalization; -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.SmartColoring; -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; - public class ModelListener implements PropertyChangeListener { - // Property change names of interest events - final public static String PCN_MODEL_VIEW_ADDED = "modelViewAdded"; - // Events on classes - final public static String PCN_STEREOTYPES = "stereotypes"; - final public static String PCN_RESTRICTED_TO = StereotypeUtils.PROPERTY_RESTRICTED_TO; - final public static String PCN_FROM_RELATIONSHIP_ADDED = "fromRelationshipAdded"; - final public static String PCN_FROM_RELATIONSHIP_REMOVED = "fromRelationshipRemoved"; - final public static String PCN_TO_RELATIONSHIP_ADDED = "toRelationshipAdded"; - final public static String PCN_TO_RELATIONSHIP_REMOVED = "toRelationshipRemoved"; - // Events on generalizations - final public static String PCN_FROM_MODEL = "fromModel"; - final public static String PCN_TO_MODEL = "toModel"; - - final private Set interestStereotypes; - - public ModelListener() { - interestStereotypes = StereotypeUtils.getSortalStereotypeNames(); - interestStereotypes.addAll(StereotypeUtils.getUltimateSortalStereotypeNames()); - interestStereotypes.add(StereotypeUtils.STR_TYPE); - } - - @Override - public void propertyChange(PropertyChangeEvent event) { - try { - final Object source = event.getSource(); - - if (source instanceof IClass) { - processClassEvent(event); - } else if (source instanceof IGeneralization) { - processGeneralizationEvent(event); - } - } catch (Exception e) { - System.err.println("An error ocurred while processing a change event on model element."); - e.printStackTrace(); - } - } - - private void processClassEvent(PropertyChangeEvent event) { - final boolean isSmartModelingEnabled = Configurations.getInstance().getProjectConfigurations() - .isSmartModellingEnabled(); - - switch (event.getPropertyName()) { - case PCN_STEREOTYPES: - if (isSmartModelingEnabled) { - enforceAndPropagateRestrictedTo(event); - } - break; - case PCN_RESTRICTED_TO: - if (isSmartModelingEnabled) { - enforceAndPropagateRestrictedTo(event); - } - smartPaint(event); - break; - case PCN_MODEL_VIEW_ADDED: - smartPaint(event); - break; - } - } - - private void processGeneralizationEvent(PropertyChangeEvent event) { - final boolean isSmartModelingEnabled = Configurations.getInstance().getProjectConfigurations() - .isSmartModellingEnabled(); - - if (!isSmartModelingEnabled) { - return; - } - - final IGeneralization sourceGen = event.getSource() instanceof IGeneralization - ? (IGeneralization) event.getSource() - : null; - - switch (event.getPropertyName()) { - case PCN_TO_MODEL: - lookupAndPropagateRestrictedTo(event.getOldValue()); - lookupAndPropagateRestrictedTo(event.getNewValue()); - break; - case PCN_FROM_MODEL: - lookupAndPropagateRestrictedTo(event.getOldValue()); - lookupAndPropagateRestrictedTo(event.getNewValue()); - lookupAndPropagateRestrictedTo(Generalization.getSpecific(sourceGen)); - break; - } - } - - private void smartPaint(PropertyChangeEvent event) { - if (!Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled()) { - return; - } - - final IClass _class = event.getSource() instanceof IClass ? (IClass) event.getSource() : null; - final Object newRestriction = event.getNewValue(); - final Object oldRestriction = event.getOldValue(); - - if (_class != null && !newRestriction.equals(oldRestriction)) { - SmartColoring.paint(_class); - } - } - - private void enforceAndPropagateRestrictedTo(PropertyChangeEvent event) { - final IClass _class = event.getSource() instanceof IClass ? (IClass) event.getSource() : null; - final String stereotype = StereotypeUtils.getUniqueStereotypeName(_class); - final Object newValue = event.getNewValue(); - final Object oldValue = event.getOldValue(); - - if (stereotype == null) { - return; - } - - switch (stereotype) { - case StereotypeUtils.STR_EVENT: - case StereotypeUtils.STR_DATATYPE: - case StereotypeUtils.STR_ENUMERATION: - case StereotypeUtils.STR_KIND: - case StereotypeUtils.STR_COLLECTIVE: - case StereotypeUtils.STR_QUANTITY: - case StereotypeUtils.STR_RELATOR: - case StereotypeUtils.STR_MODE: - case StereotypeUtils.STR_QUALITY: - case StereotypeUtils.STR_TYPE: - if (!newValue.equals(oldValue)) { - Class.setDefaultRestrictedTo(_class); - propagateRestrictionsToDescendants(_class); - } - break; - case StereotypeUtils.STR_CATEGORY: - case StereotypeUtils.STR_ROLE_MIXIN: - case StereotypeUtils.STR_PHASE_MIXIN: - case StereotypeUtils.STR_MIXIN: - case StereotypeUtils.STR_HISTORICAL_ROLE_MIXIN: - if (!newValue.equals(oldValue)) { - propagateRestrictionsToDescendants(_class); - } - break; - case StereotypeUtils.STR_SUBKIND: - case StereotypeUtils.STR_ROLE: - case StereotypeUtils.STR_PHASE: - case StereotypeUtils.STR_HISTORICAL_ROLE: - final Set sortalParents = getSortalParents(_class); - final String parentsRestrictions = Class.getRestrictedTo(sortalParents); - String currentRestrictions = Class.getRestrictedTo(_class); - - currentRestrictions = currentRestrictions == null ? "" : currentRestrictions; - - if (!currentRestrictions.equals(parentsRestrictions)) { - Class.setRestrictedTo(_class, parentsRestrictions); - propagateRestrictionsToDescendants(_class); - } - break; - } - } - - private void lookupAndPropagateRestrictedTo(Object classObject) { - final IClass _class = classObject instanceof IClass ? (IClass) classObject : null; - final String stereotype = _class != null ? StereotypeUtils.getUniqueStereotypeName(_class) : null; - - if (_class == null || stereotype == null) { - return; - } - - switch (stereotype) { - case StereotypeUtils.STR_SUBKIND: - case StereotypeUtils.STR_ROLE: - case StereotypeUtils.STR_PHASE: - case StereotypeUtils.STR_HISTORICAL_ROLE: - final Set interestParents = getSortalParents(_class); - final String parentsRestrictions = Class.getRestrictedTo(interestParents); - - String currentRestrictions = Class.getRestrictedTo(_class); - currentRestrictions = currentRestrictions == null ? "" : currentRestrictions; - - if (!currentRestrictions.equals(parentsRestrictions)) { - Class.setRestrictedTo(_class, parentsRestrictions); - propagateRestrictionsToDescendants(_class); - } - break; - } - } - - private void propagateRestrictionsToDescendants(IClass _class) { - Class.applyOnDescendants(_class, descendent -> { - String descendentStereotype = StereotypeUtils.getUniqueStereotypeName(descendent); - - if (!interestStereotypes.contains(descendentStereotype)) { - return false; - } - - final Set descendentParents = getSortalParents(descendent); - - final String newRestriction = Class.getRestrictedTo(descendentParents); - String currentRestriction = Class.getRestrictedTo(descendent); - currentRestriction = currentRestriction == null ? "" : currentRestriction; - - if (!currentRestriction.equals(newRestriction)) { - Class.setRestrictedTo(descendent, newRestriction); - return true; - } - - return false; - }); - } - - private Set getSortalParents(IClass _class) { - final Set sortalParents = Class.getParents(_class); - sortalParents.removeIf(parent -> { - final String parentStereotype = StereotypeUtils.getUniqueStereotypeName(parent); - return !interestStereotypes.contains(parentStereotype); - }); - - return sortalParents; - } - -} \ No newline at end of file + // Property change names of interest events + private static final String PCN_MODEL_VIEW_ADDED = "modelViewAdded"; + // Events on classes + private static final String PCN_STEREOTYPES = "stereotypes"; + private static final String PCN_RESTRICTED_TO = StereotypesManager.PROPERTY_RESTRICTED_TO; + private static final String PCN_IS_EXTENSIONAL = StereotypesManager.PROPERTY_IS_EXTENSIONAL; + // Events on generalizations + private static final String PCN_FROM_MODEL = "fromModel"; + private static final String PCN_TO_MODEL = "toModel"; + + private final List interestStereotypes; + + public ModelListener() { + interestStereotypes = Stereotype.getSortalStereotypeNames(); + interestStereotypes.addAll(Stereotype.getUltimateSortalStereotypeNames()); + interestStereotypes.add(Stereotype.TYPE); + } + + @Override + public void propertyChange(PropertyChangeEvent event) { + try { + final Object source = event.getSource(); + + if (source instanceof IClass) { + processClassEvent(event); + } else if (source instanceof IGeneralization) { + processGeneralizationEvent(event); + } + } catch (Exception e) { + System.err.println("An error ocurred while processing a change event on model element."); + e.printStackTrace(); + } + } + + private void processClassEvent(PropertyChangeEvent event) { + final boolean isSmartModelingEnabled = + Configurations.getInstance().getProjectConfigurations().isSmartModellingEnabled(); + + switch (event.getPropertyName()) { + case PCN_STEREOTYPES: + if (isSmartModelingEnabled) { + enforceAndPropagateRestrictedTo(event); + } + break; + case PCN_RESTRICTED_TO: + if (isSmartModelingEnabled) { + enforceAndPropagateRestrictedTo(event); + tryToResetIsExtensionalValue(event); + } + smartPaint(event); + break; + case PCN_IS_EXTENSIONAL: + if (isSmartModelingEnabled) { + preventManualChangeToIsExtensional(event); + } + break; + case PCN_MODEL_VIEW_ADDED: + smartPaint(event); + break; + } + } + + private void processGeneralizationEvent(PropertyChangeEvent event) { + final boolean isSmartModelingEnabled = + Configurations.getInstance().getProjectConfigurations().isSmartModellingEnabled(); + + if (!isSmartModelingEnabled) { + return; + } + + final IGeneralization sourceGen = + event.getSource() instanceof IGeneralization ? (IGeneralization) event.getSource() : null; + + switch (event.getPropertyName()) { + case PCN_TO_MODEL: + lookupAndPropagateRestrictedTo(event.getOldValue()); + lookupAndPropagateRestrictedTo(event.getNewValue()); + break; + case PCN_FROM_MODEL: + lookupAndPropagateRestrictedTo(event.getOldValue()); + lookupAndPropagateRestrictedTo(event.getNewValue()); + lookupAndPropagateRestrictedTo(Generalization.getSpecific(sourceGen)); + break; + } + } + + private void smartPaint(PropertyChangeEvent event) { + if (!Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled()) { + return; + } + + final IClass _class = event.getSource() instanceof IClass ? (IClass) event.getSource() : null; + final Object newRestriction = event.getNewValue(); + final Object oldRestriction = event.getOldValue(); + + if (_class != null && !newRestriction.equals(oldRestriction)) { + SmartColoringUtils.paint(_class); + } + } + + private void enforceAndPropagateRestrictedTo(PropertyChangeEvent event) { + final IClass _class = event.getSource() instanceof IClass ? (IClass) event.getSource() : null; + final String stereotype = ModelElement.getUniqueStereotypeName(_class); + final Object newValue = event.getNewValue(); + final Object oldValue = event.getOldValue(); + + if (stereotype == null) { + return; + } + + switch (stereotype) { + case Stereotype.EVENT: + case Stereotype.DATATYPE: + case Stereotype.ENUMERATION: + case Stereotype.KIND: + case Stereotype.COLLECTIVE: + case Stereotype.QUANTITY: + case Stereotype.RELATOR: + case Stereotype.QUALITY: + case Stereotype.TYPE: + if (!newValue.equals(oldValue)) { + Class.setDefaultRestrictedTo(_class); + propagateRestrictionsToDescendants(_class); + } + break; + case Stereotype.MODE: + case Stereotype.CATEGORY: + case Stereotype.ROLE_MIXIN: + case Stereotype.PHASE_MIXIN: + case Stereotype.MIXIN: + case Stereotype.HISTORICAL_ROLE_MIXIN: + if (!newValue.equals(oldValue)) { + propagateRestrictionsToDescendants(_class); + } + break; + case Stereotype.SUBKIND: + case Stereotype.ROLE: + case Stereotype.PHASE: + case Stereotype.HISTORICAL_ROLE: + final Set sortalParents = getSortalParents(_class); + final String parentsRestrictions = Class.getRestrictedTo(sortalParents); + String currentRestrictions = Class.getRestrictedTo(_class); + + currentRestrictions = currentRestrictions == null ? "" : currentRestrictions; + + if (!currentRestrictions.equals(parentsRestrictions)) { + Class.setRestrictedTo(_class, parentsRestrictions); + propagateRestrictionsToDescendants(_class); + } + break; + } + } + + private void tryToResetIsExtensionalValue(PropertyChangeEvent event) { + final IClass _class = event.getSource() instanceof IClass ? (IClass) event.getSource() : null; + final Object newRestrictionValue = event.getNewValue(); + final Object oldRestrictionValue = event.getOldValue(); + + if (newRestrictionValue != null + && !newRestrictionValue.equals(oldRestrictionValue) + && !newRestrictionValue.equals(RestrictedTo.COLLECTIVE)) { + Class.setIsExtensional(_class, false); + } + } + + private void preventManualChangeToIsExtensional(PropertyChangeEvent event) { + final IClass _class = event.getSource() instanceof IClass ? (IClass) event.getSource() : null; + final String restritedToValue = Class.getRestrictedTo(_class); + final Object newIsExtensionalValue = event.getNewValue(); + final Object oldIsExtensionalValue = event.getOldValue(); + + if (newIsExtensionalValue != null + && !newIsExtensionalValue.equals(oldIsExtensionalValue) + && !restritedToValue.equals(RestrictedTo.COLLECTIVE)) { + Class.setIsExtensional(_class, false); + } + } + + private void lookupAndPropagateRestrictedTo(Object classObject) { + final IClass _class = classObject instanceof IClass ? (IClass) classObject : null; + final String stereotype = _class != null ? ModelElement.getUniqueStereotypeName(_class) : null; + + if (_class == null || stereotype == null) { + return; + } + + switch (stereotype) { + case Stereotype.SUBKIND: + case Stereotype.ROLE: + case Stereotype.PHASE: + case Stereotype.HISTORICAL_ROLE: + final Set interestParents = getSortalParents(_class); + final String parentsRestrictions = Class.getRestrictedTo(interestParents); + + String currentRestrictions = Class.getRestrictedTo(_class); + currentRestrictions = currentRestrictions == null ? "" : currentRestrictions; + + if (!currentRestrictions.equals(parentsRestrictions)) { + Class.setRestrictedTo(_class, parentsRestrictions); + propagateRestrictionsToDescendants(_class); + } + break; + } + } + + private void propagateRestrictionsToDescendants(IClass _class) { + Class.applyOnDescendants( + _class, + descendent -> { + String descendentStereotype = ModelElement.getUniqueStereotypeName(descendent); + + if (!interestStereotypes.contains(descendentStereotype)) { + return false; + } + + final Set descendentParents = getSortalParents(descendent); + + final String newRestriction = Class.getRestrictedTo(descendentParents); + String currentRestriction = Class.getRestrictedTo(descendent); + currentRestriction = currentRestriction == null ? "" : currentRestriction; + + if (!currentRestriction.equals(newRestriction)) { + Class.setRestrictedTo(descendent, newRestriction); + return true; + } + + return false; + }); + } + + private Set getSortalParents(IClass _class) { + final Set sortalParents = Class.getParents(_class); + sortalParents.removeIf( + parent -> { + final String parentStereotype = ModelElement.getUniqueStereotypeName(parent); + return !interestStereotypes.contains(parentStereotype); + }); + + return sortalParents; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectDiagramListener.java b/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectDiagramListener.java index f6d951f0..82863336 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectDiagramListener.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectDiagramListener.java @@ -1,61 +1,58 @@ package it.unibz.inf.ontouml.vp.listeners; -import java.util.Iterator; - import com.vp.plugin.ApplicationManager; import com.vp.plugin.diagram.IDiagramUIModel; import com.vp.plugin.model.IProject; import com.vp.plugin.model.IProjectDiagramListener; +import java.util.Iterator; public class ProjectDiagramListener implements IProjectDiagramListener { - private DiagramListener diagramListener; - - public ProjectDiagramListener() { - diagramListener = new DiagramListener(); - } - - @Override - public void diagramAdded(IProject project, IDiagramUIModel diagram) { - try { - addListenerToDiagram(diagram); - } catch (Exception e) { - System.err.println("An error ocurred while adding diagram."); - e.printStackTrace(); - } - } - - @Override - public void diagramRemoved(IProject project, IDiagramUIModel diagram) { - try { - removeListenerFromDiagram(diagram); - } catch (Exception e) { - System.err.println("An error ocurred while removing diagram."); - e.printStackTrace(); - } - } - - private void addListenerToDiagram(IDiagramUIModel diagram) { - if(diagram != null) { - diagram.addDiagramListener(diagramListener); - } - } - - private void removeListenerFromDiagram(IDiagramUIModel diagram) { - if(diagram != null) { - diagram.removeDiagramListener(diagramListener); - } - } - - public void addListenersToDiagrams() { - final IProject project = ApplicationManager.instance() - .getProjectManager().getProject(); - final Iterator iter = project.diagramIterator(); - - while(iter != null && iter.hasNext()) { - final IDiagramUIModel diagram = (IDiagramUIModel) iter.next(); - diagram.addDiagramListener(diagramListener); - } - } - -} \ No newline at end of file + private DiagramListener diagramListener; + + public ProjectDiagramListener() { + diagramListener = new DiagramListener(); + } + + @Override + public void diagramAdded(IProject project, IDiagramUIModel diagram) { + try { + addListenerToDiagram(diagram); + } catch (Exception e) { + System.err.println("An error ocurred while adding diagram."); + e.printStackTrace(); + } + } + + @Override + public void diagramRemoved(IProject project, IDiagramUIModel diagram) { + try { + removeListenerFromDiagram(diagram); + } catch (Exception e) { + System.err.println("An error ocurred while removing diagram."); + e.printStackTrace(); + } + } + + private void addListenerToDiagram(IDiagramUIModel diagram) { + if (diagram != null) { + diagram.addDiagramListener(diagramListener); + } + } + + private void removeListenerFromDiagram(IDiagramUIModel diagram) { + if (diagram != null) { + diagram.removeDiagramListener(diagramListener); + } + } + + public void addListenersToDiagrams() { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + final Iterator iter = project.diagramIterator(); + + while (iter != null && iter.hasNext()) { + final IDiagramUIModel diagram = (IDiagramUIModel) iter.next(); + diagram.addDiagramListener(diagramListener); + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectListener.java b/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectListener.java index 348bf0aa..1ca10026 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectListener.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectListener.java @@ -3,69 +3,135 @@ import com.vp.plugin.ApplicationManager; import com.vp.plugin.model.IProject; import com.vp.plugin.model.IProjectListener; - -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.controllers.GitHubAccessController; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.GitHubRelease; +import it.unibz.inf.ontouml.vp.utils.StereotypesManager; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import java.time.ZonedDateTime; +import java.util.List; public class ProjectListener implements IProjectListener { - private ProjectModelListener projectModelListener; - private ProjectDiagramListener projectDiagramListener; - - public ProjectListener() { - projectModelListener = new ProjectModelListener(); - projectDiagramListener = new ProjectDiagramListener(); - addListeners(); - StereotypeUtils.generate(); - } - - private void addListeners() { - try { - final IProject project = ApplicationManager.instance() - .getProjectManager().getProject(); - - project.addProjectModelListener(projectModelListener); - project.addProjectDiagramListener(projectDiagramListener); - - projectModelListener.addListenersToModelElements(); - projectDiagramListener.addListenersToDiagrams(); - } catch (Exception e) { - System.err.println("An error ocurred while adding listeners to the project."); - e.printStackTrace(); - } - } - - @Override - public void projectAfterOpened(IProject project) { - try { - if(project == null) { return ; } - - addListeners(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void projectNewed(IProject project) { - try { - if(project == null) { return ; } - - addListeners(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void projectOpened(IProject project) {} - - @Override - public void projectPreSave(IProject project) {} - - @Override - public void projectRenamed(IProject project) {} - - @Override - public void projectSaved(IProject project) {} + private ProjectModelListener projectModelListener; + private ProjectDiagramListener projectDiagramListener; + + public ProjectListener() { + projectModelListener = new ProjectModelListener(); + projectDiagramListener = new ProjectDiagramListener(); + addListeners(); + } + + private void addListeners() { + try { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + + project.addProjectModelListener(projectModelListener); + project.addProjectDiagramListener(projectDiagramListener); + + projectModelListener.addListenersToModelElements(); + projectDiagramListener.addListenersToDiagrams(); + } catch (Exception e) { + System.err.println("An error ocurred while adding listeners to the project."); + e.printStackTrace(); + } + } + + private void generateStereotypes() { + try { + StereotypesManager.generate(); + } catch (Exception e) { + System.err.println("An error ocurred while generating stereotypes to the project."); + e.printStackTrace(); + } + } + + private void checkUpdates() { + try { + Configurations config = Configurations.getInstance(); + ZonedDateTime lastCheck = config.getLastUpdatesCheck(); + + if (lastCheck != null && lastCheck.plusDays(1).isBefore(ZonedDateTime.now())) { + GitHubAccessController.lookupUpdates(); + List releases = config.getReleases(); + GitHubRelease latestRelease = config.getLatestRelease(); + boolean upToDate = false; + + for (GitHubRelease release : releases) { + if (release.getTagName().equals(OntoUMLPlugin.PLUGIN_VERSION_RELEASE) + && release.getCreatedAt().isBefore(latestRelease.getCreatedAt())) { + upToDate = true; + } + } + + if (!upToDate) { + System.out.println("New updates are available."); + ViewManagerUtils.simpleLog( + "New updates are available. Go to \"Update Plugin\" to get the latest version of the" + + " OntoUML Plugin for Visual Paradigm."); + } else { + System.out.println("No new updates available."); + ViewManagerUtils.simpleLog( + "Your OntoUML Plugin for Visual Paradigm is up to date with our latest release."); + } + } else { + System.out.println("Last check for updates was already performed in the last 24 hours."); + } + + config.setLastUpdatesCheck(ZonedDateTime.now()); + + } catch (Exception e) { + System.out.println("Failed to get releases from GitHub"); + e.printStackTrace(); + } + } + + @Override + public void projectAfterOpened(IProject project) { + System.out.println("Project Listenner - After Opened"); + try { + if (project == null) { + return; + } + + addListeners(); + generateStereotypes(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void projectNewed(IProject project) { + System.out.println("Project Listenner - Newed"); + try { + if (project == null) { + return; + } + + addListeners(); + generateStereotypes(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void projectOpened(IProject project) { + System.out.println("Project Listenner - Opened"); + checkUpdates(); + generateStereotypes(); + } + + @Override + public void projectPreSave(IProject project) {} + + @Override + public void projectRenamed(IProject project) {} + @Override + public void projectSaved(IProject project) { + checkUpdates(); + } } diff --git a/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectModelListener.java b/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectModelListener.java index 0f797094..f207ed94 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectModelListener.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/listeners/ProjectModelListener.java @@ -1,7 +1,5 @@ package it.unibz.inf.ontouml.vp.listeners; -import java.util.Iterator; - import com.vp.plugin.ApplicationManager; import com.vp.plugin.model.IClass; import com.vp.plugin.model.IGeneralization; @@ -9,58 +7,58 @@ import com.vp.plugin.model.IProject; import com.vp.plugin.model.IProjectModelListener; import com.vp.plugin.model.factory.IModelElementFactory; +import java.util.Iterator; public class ProjectModelListener implements IProjectModelListener { - private ModelListener modelListener; - - ProjectModelListener() { - modelListener = new ModelListener(); - } + private ModelListener modelListener; - @Override - public void modelAdded(IProject project, IModelElement modelElement) { - try { - addListenerToModelElement(modelElement); - } catch (Exception e) { - System.err.println("An error ocurred while adding model element."); - e.printStackTrace(); - } - } + ProjectModelListener() { + modelListener = new ModelListener(); + } - @Override - public void modelRemoved(IProject project, IModelElement modelElement) { - try { - removeListenerFromModelElement(modelElement); - } catch (Exception e) { - System.err.println("An error ocurred while removing model element."); - e.printStackTrace(); - } - } + @Override + public void modelAdded(IProject project, IModelElement modelElement) { + try { + addListenerToModelElement(modelElement); + } catch (Exception e) { + System.err.println("An error ocurred while adding model element."); + e.printStackTrace(); + } + } - private void addListenerToModelElement(IModelElement modelElement) { - if(modelElement instanceof IClass || modelElement instanceof IGeneralization) { - modelElement.addPropertyChangeListener(modelListener); - } - } + @Override + public void modelRemoved(IProject project, IModelElement modelElement) { + try { + removeListenerFromModelElement(modelElement); + } catch (Exception e) { + System.err.println("An error ocurred while removing model element."); + e.printStackTrace(); + } + } - private void removeListenerFromModelElement(IModelElement modelElement) { - if(modelElement instanceof IClass || modelElement instanceof IGeneralization) { - modelElement.removePropertyChangeListener(modelListener); - } - } + private void addListenerToModelElement(IModelElement modelElement) { + if (modelElement instanceof IClass || modelElement instanceof IGeneralization) { + modelElement.addPropertyChangeListener(modelListener); + } + } - public void addListenersToModelElements() { - final IProject project = ApplicationManager.instance() - .getProjectManager().getProject(); - final String[] desiredElements = {IModelElementFactory.MODEL_TYPE_CLASS, - IModelElementFactory.MODEL_TYPE_GENERALIZATION}; - final Iterator iter = project.allLevelModelElementIterator(desiredElements); + private void removeListenerFromModelElement(IModelElement modelElement) { + if (modelElement instanceof IClass || modelElement instanceof IGeneralization) { + modelElement.removePropertyChangeListener(modelListener); + } + } - while(iter != null && iter.hasNext()) { - final IModelElement modelElement = (IModelElement) iter.next(); - modelElement.addPropertyChangeListener(modelListener); - } - } + public void addListenersToModelElements() { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + final String[] desiredElements = { + IModelElementFactory.MODEL_TYPE_CLASS, IModelElementFactory.MODEL_TYPE_GENERALIZATION + }; + final Iterator iter = project.allLevelModelElementIterator(desiredElements); -} \ No newline at end of file + while (iter != null && iter.hasNext()) { + final IModelElement modelElement = (IModelElement) iter.next(); + modelElement.addPropertyChangeListener(modelListener); + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Association.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Association.java deleted file mode 100644 index e1a370aa..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Association.java +++ /dev/null @@ -1,214 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import com.google.gson.JsonObject; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.IAssociation; -import com.vp.plugin.model.IAssociationEnd; - -/** - * - * Implementation of ModelElement to handle IAssociation objects to be - * serialized as ontouml-schema/Association - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - * - */ - -public class Association implements ModelElement { - - private final IAssociation sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description; - - @SerializedName("properties") - @Expose - private List properties; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; - - @SerializedName("stereotypes") - @Expose - private List stereotypes; - - @SerializedName("isAbstract") - @Expose - private boolean isAbstract; - - @SerializedName("isDerived") - @Expose - private boolean isDerived; - - public Association(IAssociation source) { - this.sourceModelElement = source; - - this.type = ModelElement.TYPE_RELATION; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - addProperty(new Property((IAssociationEnd) source.getFromEnd())); - addProperty(new Property((IAssociationEnd) source.getToEnd())); - - String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); - } - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - setAbstract(source.isAbstract()); - setDerived(source.isDerived()); - } - - public Association(IAssociation source, HashSet modelElements) { - this.sourceModelElement = source; - - this.type = ModelElement.TYPE_RELATION; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - if(modelElements.contains(source.getFromEnd().getId())) - addProperty(new Property((IAssociationEnd) source.getFromEnd())); - - if(modelElements.contains(source.getToEnd().getId())) - addProperty(new Property((IAssociationEnd) source.getToEnd())); - - String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); - } - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - setAbstract(source.isAbstract()); - setDerived(source.isDerived()); - } - - @Override - public String getId() { - return getSourceModelElement().getId(); - } - - @Override - public IAssociation getSourceModelElement() { - return this.sourceModelElement; - } - - @Override - public String getOntoUMLType() { - return this.type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description); - } - - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } - - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } - - public List getStereotypes() { - return this.stereotypes; - } - - public void setStereotypes(List stereotypes) { - this.stereotypes = stereotypes; - } - - public String getStereotype(int position) { - return this.stereotypes.get(position); - } - - public void addStereotype(String name) { - if (this.stereotypes == null) - this.stereotypes = new ArrayList(); - - this.stereotypes.add(name); - } - - public void removeStereotype(String name) { - - if (this.stereotypes.contains(name)) - this.stereotypes.remove(name); - } - - public List getProperties() { - return properties; - } - - public void setProperties(List properties) { - this.properties = properties; - } - - public Property getProperty(int position) { - return this.properties.get(position); - } - - public void addProperty(Property property) { - if (this.properties == null) - this.properties = new ArrayList(); - - this.properties.add(property); - } - - public void removeProperty(Property property) { - - if (this.properties.contains(property)) - this.properties.remove(property); - } - - public boolean isAbstract() { - return this.isAbstract; - } - - public void setAbstract(boolean isAbstract) { - this.isAbstract = isAbstract; - } - - public boolean isDerived() { - return this.isDerived; - } - - public void setDerived(boolean isDerived) { - this.isDerived = isDerived; - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/AssociationClass.java b/src/main/java/it/unibz/inf/ontouml/vp/model/AssociationClass.java deleted file mode 100644 index e7b76a2b..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/AssociationClass.java +++ /dev/null @@ -1,183 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import com.google.gson.JsonObject; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.IAssociationClass; -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * Implementation of ModelElement to handle IAssociationClass objects - * to be serialized as ontouml-schema/Association - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - * - */ - -public class AssociationClass implements ModelElement { - - private final IAssociationClass sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description; - - @SerializedName("properties") - @Expose - private List properties; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; - - @SerializedName("stereotypes") - @Expose - private List stereotypes; - - @SerializedName("isAbstract") - @Expose - private boolean isAbstract; - - @SerializedName("isDerived") - @Expose - private boolean isDerived; - - public AssociationClass(IAssociationClass source) { - this.sourceModelElement = source; - this.type = ModelElement.TYPE_ASSOCIATION_CLASS; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - Property sourceEnd = new Property(source, source.getFrom()); - Property targetEnd = new Property(source, source.getTo()); - - addStereotype(StereotypeUtils.STR_DERIVATION); - - addProperty(sourceEnd); - addProperty(targetEnd); - } - - @Override - public String getId() { - return getSourceModelElement().getId(); - } - - @Override - public IAssociationClass getSourceModelElement() { - return this.sourceModelElement; - } - - @Override - public String getOntoUMLType() { - return this.type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description); - } - - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } - - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } - - public List getStereotypes() { - return this.stereotypes; - } - - public void setStereotypes(List stereotypes) { - this.stereotypes = stereotypes; - } - - public String getStereotype(int position) { - return this.stereotypes.get(position); - } - - public void addStereotype(String name) { - if (this.stereotypes == null) - this.stereotypes = new ArrayList(); - - this.stereotypes.add(name); - } - - public void removeStereotype(String name) { - - if (this.stereotypes.contains(name)) - this.stereotypes.remove(name); - } - - public List getProperties() { - return properties; - } - - public void setProperties(List properties) { - this.properties = properties; - } - - public Property getProperty(int position) { - return this.properties.get(position); - } - - public void addProperty(Property property) { - if (this.properties == null) - this.properties = new ArrayList(); - - this.properties.add(property); - } - - public void removeProperty(Property property) { - - if (this.properties.contains(property)) - this.properties.remove(property); - } - - public boolean isAbstract() { - return this.isAbstract; - } - - public void setAbstract(boolean isAbstract) { - this.isAbstract = isAbstract; - } - - public boolean isDerived() { - return this.isDerived; - } - - public void setDerived(boolean isDerived) { - this.isDerived = isDerived; - } -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/AssociationModelDescription.java b/src/main/java/it/unibz/inf/ontouml/vp/model/AssociationModelDescription.java new file mode 100644 index 00000000..888fa6f3 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/AssociationModelDescription.java @@ -0,0 +1,112 @@ +package it.unibz.inf.ontouml.vp.model; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.DiagramManager; +import com.vp.plugin.diagram.IDiagramElement; +import com.vp.plugin.diagram.IDiagramUIModel; +import com.vp.plugin.diagram.connector.IAssociationUIModel; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IModelElement; +import it.unibz.inf.ontouml.vp.model.uml.Association; +import java.awt.Point; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class AssociationModelDescription { + + private IAssociationUIModel associationUIModel; + public final IAssociation association; + public final IDiagramUIModel diagram; + public final IDiagramElement sourceDiagramElement; + public final IDiagramElement targetDiagramElement; + public final Point[] points; + public final boolean isMasterView; + public final boolean isShowDirection; + public final boolean isShowSourceRoleName; + public final boolean isShowSourceRoleVisibility; + public final boolean isShowTargetRoleName; + public final boolean isShowTargetRoleVisibility; + public final boolean isShowAssociationEndPropertyStrings; + + public AssociationModelDescription(IAssociationUIModel associationModel) { + associationUIModel = associationModel; + + association = (IAssociation) associationModel.getModelElement(); + diagram = associationModel.getDiagramUIModel(); + sourceDiagramElement = associationModel.getFromShape(); + targetDiagramElement = associationModel.getToShape(); + points = associationModel.getPoints(); + + isMasterView = associationModel.isMasterView(); + isShowDirection = associationModel.isShowDirection(); + isShowAssociationEndPropertyStrings = associationModel.isShowAssociationEndPropertyStrings(); + isShowSourceRoleName = associationModel.isShowFromRoleName(); + isShowSourceRoleVisibility = associationModel.isShowFromRoleVisibility(); + isShowTargetRoleName = associationModel.isShowToRoleName(); + isShowTargetRoleVisibility = associationModel.isShowToRoleVisibility(); + } + + private Point[] getInvertedPoints() { + Point[] invertedPoints = points; + + if (invertedPoints != null) { + final List pointsListToReverse = Arrays.asList(invertedPoints); + Collections.reverse(pointsListToReverse); + invertedPoints = pointsListToReverse.toArray(invertedPoints); + } + + return invertedPoints; + } + + public void deleteAssociationModel() { + if (associationUIModel != null) { + associationUIModel.setShowAssociationEndPropertyStrings(false); + associationUIModel.setShowFromRoleName(false); + associationUIModel.setShowFromRoleVisibility(false); + associationUIModel.setShowToRoleName(false); + associationUIModel.setShowToRoleVisibility(false); + associationUIModel.deleteViewOnly(); + associationUIModel = null; + } + } + + public IAssociationUIModel recreateInvertedAssociationModel() { + final IModelElement currentSource = Association.getSource(association); + final IModelElement currentTarget = Association.getTarget(association); + final IModelElement originalSource = sourceDiagramElement.getModelElement(); + final IModelElement originalTarget = targetDiagramElement.getModelElement(); + + if (currentSource.equals(originalSource) || currentTarget.equals(originalTarget)) { + throw new IllegalStateException( + "Inverted association models can only be created after the original association" + + " inverted."); + } + + final DiagramManager dm = ApplicationManager.instance().getDiagramManager(); + final IAssociationUIModel invertedAssociationModel = + (IAssociationUIModel) + dm.createConnector( + diagram, + association, + targetDiagramElement, + sourceDiagramElement, + getInvertedPoints()); + + if (isMasterView) { + invertedAssociationModel.toBeMasterView(); + } + + invertedAssociationModel.setShowDirection(isShowDirection); + invertedAssociationModel.setShowFromRoleName(isShowSourceRoleName); + invertedAssociationModel.setShowFromRoleVisibility(isShowSourceRoleVisibility); + invertedAssociationModel.setShowToRoleName(isShowTargetRoleName); + invertedAssociationModel.setShowToRoleVisibility(isShowTargetRoleVisibility); + invertedAssociationModel.setShowAssociationEndPropertyStrings( + isShowAssociationEndPropertyStrings); + + invertedAssociationModel.resetCaption(); + + return invertedAssociationModel; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Class.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Class.java deleted file mode 100644 index bdb67265..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Class.java +++ /dev/null @@ -1,621 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.Collectors; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.IAttribute; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.IDataType; -import com.vp.plugin.model.IEnumerationLiteral; -import com.vp.plugin.model.IGeneralization; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.ISimpleRelationship; -import com.vp.plugin.model.ITaggedValue; -import com.vp.plugin.model.ITaggedValueContainer; - -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; - -/** - * Implementation of ModelElement to handle IClass and IDataType objects to be - * serialized as ontouml-schema/Class - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - */ - -public class Class implements ModelElement { - - private final IModelElement sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description; - - @SerializedName("properties") - @Expose - private Set properties; - - @SerializedName("literals") - @Expose - private LinkedList literals; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; - - @SerializedName("stereotypes") - @Expose - private List stereotypes; - - @SerializedName("isAbstract") - @Expose - private boolean isAbstract; - - @SerializedName("isDerived") - @Expose - private boolean isDerived; - - @SerializedName("allowed") - @Expose - private JsonArray restrictedTo; - - @SerializedName("isExtensional") - @Expose - private JsonElement isExtensional; - - @SerializedName("isPowertype") - @Expose - private JsonElement isPowertype; - - @SerializedName("order") - @Expose - private String order; - - private Class(IModelElement source) { - this.sourceModelElement = source; - this.type = ModelElement.TYPE_CLASS; - this.id = source.getId(); - this.properties = null; - this.stereotypes = null; - this.literals = null; - } - - public Class(IClass source) { - this((IModelElement) source); - - final IAttribute[] attributes = source.toAttributeArray(); - for (int i = 0; attributes != null && i < attributes.length; i++) { - addProperties(new Property(attributes[i])); - } - - final String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); - } - - if (this.stereotypes != null && this.stereotypes.contains(StereotypeUtils.STR_ENUMERATION)) { - IEnumerationLiteral[] literalArray = source.toEnumerationLiteralArray(); - for (int i = 0; literalArray != null && i < literalArray.length; i++) - addLiteral(new Literal(literalArray[i])); - } - - setAbstract(source.isAbstract()); - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - - if (source.getName().trim().startsWith("/")) { - setName(source.getName().substring(1)); - this.isDerived = true; - } else { - setName(source.getName().trim()); - } - - setDescription(source.getDescription()); - - loadTags(source); - } - - public Class(IDataType source) { - this((IModelElement) source); - - addStereotype(StereotypeUtils.STR_DATATYPE); - setAbstract(false); - setDerived(false); - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - - if (source.getName().trim().startsWith("/")) { - setName(source.getName().substring(1)); - this.isDerived = true; - } else { - setName(source.getName().trim()); - } - - // TODO: change this to apply only to default VP datatypes - if (restrictedTo == null) { - restrictedTo = new JsonArray(); - restrictedTo.add("abstract"); - } - - } - - public Class(IClass source, HashSet modelElements) { - this((IModelElement) source); - - final IAttribute[] attributes = source.toAttributeArray(); - for (int i = 0; attributes != null && i < attributes.length; i++) { - if (modelElements.contains(attributes[i].getId())) - addProperties(new Property(attributes[i])); - } - - final String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); - } - - if (this.stereotypes != null && this.stereotypes.contains(StereotypeUtils.STR_ENUMERATION)) { - IEnumerationLiteral[] literalArray = source.toEnumerationLiteralArray(); - for (int i = 0; literalArray != null && i < literalArray.length; i++) - addLiteral(new Literal(literalArray[i])); - } - - setAbstract(source.isAbstract()); - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - - if (source.getName().trim().startsWith("/")) { - setName(source.getName().substring(1)); - this.isDerived = true; - } else { - setName(source.getName().trim()); - } - - setDescription(source.getDescription()); - - loadTags(source); - } - - private void loadTags(IClass source) { - if (source.getTaggedValues() != null) { - final JsonParser parser = new JsonParser(); - - if(hasRestrictedTo(source)) { - String restrictedTo = getRestrictedTo(source); - - if (restrictedTo == null) { - this.restrictedTo = null; - } else { - restrictedTo = restrictedTo.trim() - .replaceAll(" +", ",").replaceAll(",", "\",\""); - - final JsonElement restrictedToArray = !restrictedTo.equals("") ? - parser.parse("[\"" + restrictedTo + "\"]") : - parser.parse("[]"); - this.restrictedTo = - restrictedToArray.isJsonArray() && ((JsonArray) restrictedToArray).size() > 0 ? - (JsonArray) restrictedToArray : null; - } - } - - if(hasIsExtensional(source)) { - this.isExtensional = parser.parse(""+getIsExtensional(source)); - } else { - this.isExtensional = parser.parse("null"); - } - - if(hasIsPowertype(source)) { - this.isPowertype = parser.parse(""+getIsPowertype(source)); - } else { - this.isPowertype = parser.parse("null"); - } - - if(hasOrder(source)) { - this.order = getOrder(source); - } - } - } - - @Override - public IModelElement getSourceModelElement() { - return this.sourceModelElement; - } - - @Override - public String getId() { - return getSourceModelElement().getId(); - } - - @Override - public String getOntoUMLType() { - return this.type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description); - ; - } - - public Set getProperties() { - return properties; - } - - public void addProperties(Property property) { - if (this.properties == null) - this.properties = new HashSet(); - - this.properties.add(property); - } - - public void removeProperties(Property property) { - if (this.properties != null && this.properties.contains(property)) - this.properties.remove(property); - } - - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } - - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } - - public List getStereotypes() { - return this.stereotypes; - } - - public void setStereotypes(List stereotypes) { - this.stereotypes = stereotypes; - } - - public String getStereotype(int position) { - return this.stereotypes.get(position); - } - - public void addStereotype(String name) { - if (this.stereotypes == null) - this.stereotypes = new ArrayList(); - - this.stereotypes.add(name); - } - - public void removeStereotype(String name) { - if (this.stereotypes != null && this.stereotypes.contains(name)) - this.stereotypes.remove(name); - } - - public boolean isAbstract() { - return this.isAbstract; - } - - public void setAbstract(boolean isAbstract) { - this.isAbstract = isAbstract; - } - - public boolean isDerived() { - return this.isDerived; - } - - public void setDerived(boolean isDerived) { - this.isDerived = isDerived; - } - - public LinkedList getLiterals() { - return literals; - } - - public void setLiterals(LinkedList literals) { - this.literals = literals; - } - - public void addLiteral(Literal literal) { - if (getLiterals() == null) { - setLiterals(new LinkedList()); - } - - this.literals.add(literal); - } - - public static Set getParents(IClass _class) { - final Set parents = new HashSet(); - final ISimpleRelationship[] relationships = _class.toToRelationshipArray(); - - for (int i = 0; relationships != null && i < relationships.length; i++) { - if(relationships[i] instanceof IGeneralization) { - final IGeneralization generalization = (IGeneralization) relationships[i]; - final IModelElement parent = Generalization.getGeneral(generalization); - - if (parent instanceof IClass) { - parents.add((IClass) parent); - } - } - } - - return parents; - } - - public static Set getChildren(IClass _class) { - final Set children = new HashSet(); - final ISimpleRelationship[] relationships = _class.toFromRelationshipArray(); - - for (int i = 0; relationships != null && i < relationships.length; i++) { - if(relationships[i] instanceof IGeneralization) { - final IGeneralization generalization = (IGeneralization) relationships[i]; - final IModelElement child = Generalization.getSpecific(generalization); - - if (child instanceof IClass) { - children.add((IClass) child); - } - } - } - - return children; - } - - public static Set getAncestors(IClass _class) { - final Set ancestors = new HashSet(); - final Set parents = getChildren(_class); - - for (IClass parent : parents) { - ancestors.addAll(getDescendants(parent)); - ancestors.add(parent); - } - - return ancestors; - } - - public static Set getDescendants(IClass _class) { - final Set descendants = new HashSet(); - final Set children = getChildren(_class); - - for (IClass child : children) { - descendants.addAll(getDescendants(child)); - descendants.add(child); - } - - return descendants; - } - - public static void applyOnChildren(IClass _class, Consumer function) { - final Set children = getChildren(_class); - - for (IClass child : children) { - function.accept(child); - } - } - - public static void applyOnParents(IClass _class, Consumer function) { - final Set parents = getParents(_class); - - for (IClass parent : parents) { - function.accept(parent); - } - } - - public static void applyOnDescendants(IClass _class, Function function) { - final Set children = getChildren(_class); - - for (IClass child : children) { - final boolean shouldContinue = function.apply(child); - if(shouldContinue) { - applyOnDescendants(child, function); - } - } - } - - public static void applyOnAncestors(IClass _class, Function function) { - final Set parents = getParents(_class); - - for (IClass parent : parents) { - final boolean shouldContinue = function.apply(parent); - if(shouldContinue) { - applyOnAncestors(parent, function); - } - } - } - - public static void setRestrictedTo(IClass _class, String restrictions) { - if(_class.getTaggedValues() == null) { - return ; - } - - Iterator values = _class.getTaggedValues().taggedValueIterator(); - - while(values != null && values.hasNext()) { - final ITaggedValue value = (ITaggedValue) values.next(); - - if( - value.getName().equals(StereotypeUtils.PROPERTY_RESTRICTED_TO) - ) { - final String notNull = restrictions != null ? restrictions : ""; - final List sortList = Arrays.asList(notNull.split("\\s+")); - Collections.sort(sortList); - final Set noDuplicates = new LinkedHashSet(sortList); - final String newRestrictions = noDuplicates.toString() - .replaceAll("[\\[\\],]", "").trim(); - final String currentRestrictions = value.getValueAsString() != null ? - value.getValueAsString() : "" ; - - if(!currentRestrictions.equals(newRestrictions)) { - value.setValue(newRestrictions); - } - - return ; - } - } - } - - private static void setDefaultRestrictedTo(IClass element, String stereotypeName) { - final String defaultNature = StereotypeUtils.getDefaultRestrictedTo(stereotypeName); - setRestrictedTo(element, defaultNature); - } - - public static void setDefaultRestrictedTo(IClass _class) { - setDefaultRestrictedTo(_class, - StereotypeUtils.getUniqueStereotypeName(_class)); - } - - public static String getRestrictedTo(IClass _class) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue restrictedTo = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_RESTRICTED_TO) : - null; - - return restrictedTo != null ? restrictedTo.getValueAsString() : null; - } - - public static String getRestrictedTo(Set classes) { - String classesRestrictions = ""; - - for (IClass _class : classes) { - final String _classRestrictions = getRestrictedTo(_class); - if (_classRestrictions != null) { - classesRestrictions += " " + _classRestrictions; - } - } - - classesRestrictions = Arrays.stream(classesRestrictions.split("\\s+")) - .distinct().collect(Collectors.joining(" ")); - - return !classesRestrictions.equals("") ? classesRestrictions : null; - } - - public static boolean hasRestrictedTo(IClass _class) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue restrictedTo = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_RESTRICTED_TO) : - null; - - return restrictedTo != null; - } - - public static String getOrder(IClass _class) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue order = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_ORDER) : - null; - - return order != null ? order.getValueAsString() : null ; - } - - public static void setOrder(IClass _class, String newOrder) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue order = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_ORDER) : - null; - - if (order != null) { - order.setValue(newOrder); - } - } - - public static boolean hasOrder(IClass _class) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue order = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_ORDER) : - null; - - return order != null; - } - - public static boolean getIsPowertype(IClass _class) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue isPowertype = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_IS_POWERTYPE) : - null; - final String isPowertypeValue = isPowertype != null ? - isPowertype.getValueAsString() : "" ; - - return Boolean.parseBoolean(isPowertypeValue); - } - - public static void setIsPowertype(IClass _class, boolean isPowertypeValue) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue isPowertype = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_IS_POWERTYPE) : - null; - - if (isPowertype != null) { - isPowertype.setValue(isPowertypeValue); - } - } - - public static boolean hasIsPowertype(IClass _class) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue isPowertype = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_IS_POWERTYPE) : - null; - - return isPowertype != null; - } - - public static boolean getIsExtensional(IClass _class) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue isExtensional = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_IS_EXTENSIONAL) : - null; - final String isExtensionalValue = isExtensional != null ? - isExtensional.getValueAsString() : "" ; - - return Boolean.parseBoolean(isExtensionalValue); - } - - public static void setIsExtensional(IClass _class, boolean isExtensionalValue) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue isExtensional = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_IS_EXTENSIONAL) : - null; - - if (isExtensional != null) { - isExtensional.setValue(isExtensionalValue); - } - } - - public static boolean hasIsExtensional(IClass _class) { - final ITaggedValueContainer container = _class.getTaggedValues(); - final ITaggedValue isExtensional = container != null ? - container.getTaggedValueByName(StereotypeUtils.PROPERTY_IS_EXTENSIONAL) : - null; - - return isExtensional != null; - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Configurations.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Configurations.java new file mode 100644 index 00000000..ada7bbf6 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/Configurations.java @@ -0,0 +1,240 @@ +package it.unibz.inf.ontouml.vp.model; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSyntaxException; +import com.google.gson.annotations.Expose; +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.model.IProject; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * OntoUML Plugin configuration utility, allows persisting user preferences on the functionalities + * enabled by the plugin. + * + * @author Claudenir Fonseca + */ +public class Configurations { + + private static final String CONFIG_FILE_NAME = ".ontouml.config.json"; + + private static Configurations instance; + + @Expose() private List projects; + + @Expose() private List releases; + + @Expose() private GitHubRelease latestRelease; + + @Expose() private GitHubRelease latestAlphaRelease; + + @Expose() private GitHubRelease installedRelease; + + // Since Gson shows problems with the default serialization of ZonedDateTime we rely on strings + @Expose() private String lastUpdatesCheck; + + private Configurations() { + this.projects = new ArrayList(); + this.releases = new ArrayList<>(); + this.latestRelease = null; + this.latestAlphaRelease = null; + this.installedRelease = null; + this.lastUpdatesCheck = ZonedDateTime.now().toString(); + } + + private List getProjectConfigurationsList() { + return projects; + } + + private boolean addProjectConfigurations(ProjectConfigurations projectConfigurations) { + return getProjectConfigurationsList().add(projectConfigurations); + } + + public List getReleases() { + return releases; + } + + public void setReleases(List releases) { + if (releases == null) { + return; + } + + this.releases = releases; + + this.releases.forEach( + release -> { + if (release.isPrerelease()) { + latestAlphaRelease = + latestAlphaRelease == null + || latestAlphaRelease.getCreatedAt() == null + || release.getCreatedAt().isAfter(latestAlphaRelease.getCreatedAt()) + ? release + : latestAlphaRelease; + } else { + latestRelease = + latestRelease == null + || latestRelease.getCreatedAt() == null + || release.getCreatedAt().isAfter(latestRelease.getCreatedAt()) + ? release + : latestRelease; + } + + installedRelease = + release.getTagName().equals(OntoUMLPlugin.PLUGIN_VERSION_RELEASE) + ? release + : installedRelease; + }); + } + + public ZonedDateTime getLastUpdatesCheck() { + return ZonedDateTime.parse(lastUpdatesCheck); + } + + public void setLastUpdatesCheck(ZonedDateTime lastUpdatesCheck) { + this.lastUpdatesCheck = lastUpdatesCheck.toString(); + } + + public GitHubRelease getLatestRelease() { + return latestRelease; + } + + public GitHubRelease getLatestAlphaRelease() { + return latestAlphaRelease; + } + + public GitHubRelease getInstalledRelease() { + return installedRelease; + } + + /** + * Returns singleton instance of the class. + * + * @return configurations + */ + public static Configurations getInstance() { + if (instance == null) { + final ApplicationManager application = ApplicationManager.instance(); + final File workspace = application.getWorkspaceLocation(); + final File configurationsFile = new File(workspace, CONFIG_FILE_NAME); + + if (configurationsFile.exists()) { + String json = ""; + try { + json = new String(Files.readAllBytes(configurationsFile.toPath())); + Gson gson = new Gson(); + instance = gson.fromJson(json, Configurations.class); + } catch (Exception e) { + if (e instanceof IOException) + application + .getViewManager() + .showMessage( + "Unable to load configuration file (" + OntoUMLPlugin.PLUGIN_NAME + ").\n"); + else if (e instanceof JsonSyntaxException) + application + .getViewManager() + .showMessage( + "Configuration file ill-formed (" + OntoUMLPlugin.PLUGIN_NAME + ").\n"); + else + application + .getViewManager() + .showMessage( + "Unknown error while reading configuration file (" + + OntoUMLPlugin.PLUGIN_NAME + + ").\n"); + + e.printStackTrace(); + } + } + + if (instance == null) instance = new Configurations(); + } + + return instance; + } + + /** Persists user preferences on Visual Paradigm's workspace. */ + public void save() { + final ApplicationManager application = ApplicationManager.instance(); + final File workspace = application.getWorkspaceLocation(); + final File configurationsFile = new File(workspace, CONFIG_FILE_NAME); + final FileWriter fw; + final GsonBuilder builder = new GsonBuilder(); + + builder.registerTypeAdapter( + ZonedDateTime.class, + new JsonDeserializer() { + + @Override + public ZonedDateTime deserialize( + JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + return ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString()); + } + }); + + builder.setPrettyPrinting(); + // builder.excludeFieldsWithoutExposeAnnotation(); + + final Gson gson = builder.create(); + final String json = gson.toJson(this); + + try { + if (!configurationsFile.exists()) { + configurationsFile.createNewFile(); + } + + fw = new FileWriter(configurationsFile); + fw.write(json); + fw.close(); + } catch (IOException e) { + application + .getViewManager() + .showMessage("Unable save " + OntoUMLPlugin.PLUGIN_NAME + " configurations."); + e.printStackTrace(); + } + } + + /** + * Retrieves the configurations of the current project. + * + * @return current project's configurations. + */ + public ProjectConfigurations getProjectConfigurations() { + final IProject current = ApplicationManager.instance().getProjectManager().getProject(); + + return getProjectConfigurations(current.getId()); + } + + /** + * Retrieves the project configurations given the provided ID. If no previous configurations is + * present, a new instance of ProjectConfigurations is returned with default + * settings. + * + * @param projectId - Interest project's ID. + * @return current project's configurations. + */ + public ProjectConfigurations getProjectConfigurations(String projectId) { + for (ProjectConfigurations projectConfigurations : getProjectConfigurationsList()) { + if (projectConfigurations.getId().equals(projectId)) { + return projectConfigurations; + } + } + + ProjectConfigurations projectConfigurations = new ProjectConfigurations(projectId); + addProjectConfigurations(projectConfigurations); + + return projectConfigurations; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Generalization.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Generalization.java deleted file mode 100644 index d8539fbb..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Generalization.java +++ /dev/null @@ -1,129 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import com.google.gson.JsonObject; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.IGeneralization; -import com.vp.plugin.model.IModelElement; - -/** - * - * Implementation of ModelElement to handle IGeneralization objects to be - * serialized as ontouml-schema/Generalization - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - * - */ - -public class Generalization implements ModelElement { - - private final IGeneralization sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; - - @SerializedName("general") - @Expose - private Reference general; - - @SerializedName("specific") - @Expose - private Reference specific; - - public Generalization(IGeneralization source) { - this.sourceModelElement = source; - - this.type = ModelElement.TYPE_GENERALIZATION; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - setGeneral(new Reference(source.getFrom())); - setSpecific(new Reference(source.getTo())); - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - } - - @Override - public String getId() { - return getSourceModelElement() != null ? getSourceModelElement().getId() : null; - } - - @Override - public IGeneralization getSourceModelElement() { - return this.sourceModelElement; - } - - @Override - public String getOntoUMLType() { - return this.type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description);; - } - - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } - - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } - - public Reference getGeneral() { - return general; - } - - public void setGeneral(Reference general) { - this.general = general; - } - - public Reference getSpecific() { - return specific; - } - - public void setSpecific(Reference specific) { - this.specific = specific; - } - - public static IModelElement getGeneral(IGeneralization generalization) { - return generalization.getFrom(); - } - - public static IModelElement getSpecific(IGeneralization generalization) { - return generalization.getTo(); - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/GeneralizationSet.java b/src/main/java/it/unibz/inf/ontouml/vp/model/GeneralizationSet.java deleted file mode 100644 index bbf58a07..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/GeneralizationSet.java +++ /dev/null @@ -1,190 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import com.google.gson.JsonObject; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.*; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -/** - * - * Implementation of ModelElement to handle IGeneralizationSet objects to be - * serialized as ontouml-schema/GeneralizationSet - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - * - */ - -public class GeneralizationSet implements ModelElement { - - private final IGeneralizationSet sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; - - @SerializedName("categorizer") - @Expose - private Reference categorizer; - - @SerializedName("generalizations") - @Expose - private List generalizations; - - @SerializedName("isDisjoint") - @Expose - private boolean isDisjoint; - - @SerializedName("isComplete") - @Expose - private boolean isComplete; - - public GeneralizationSet(IGeneralizationSet source) { - this.sourceModelElement = source; - - this.type = ModelElement.TYPE_GENERALIZATION_SET; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - setComplete(source.isCovering()); - setDisjoint(source.isDisjoint()); - - if (source.getPowerType() != null) - setCategorizer(new Reference(source.getPowerType())); - - final IGeneralization[] generalizations = source.toGeneralizationArray(); - for (int i = 0; generalizations != null && i < generalizations.length; i++) - addGeneralization(new Reference(generalizations[i])); - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - } - - public GeneralizationSet(IGeneralizationSet source, HashSet idElements) { - this.sourceModelElement = source; - - this.type = ModelElement.TYPE_GENERALIZATION_SET; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - setComplete(source.isCovering()); - setDisjoint(source.isDisjoint()); - - if (source.getPowerType() != null) - setCategorizer(new Reference(source.getPowerType())); - - final IGeneralization[] generalizations = source.toGeneralizationArray(); - for (int i = 0; generalizations != null && i < generalizations.length; i++) { - if(idElements.contains(generalizations[i].getId())) - addGeneralization(new Reference(generalizations[i])); - } - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - } - - @Override - public String getId() { - return getSourceModelElement().getId(); - } - - @Override - public IModelElement getSourceModelElement() { - return this.sourceModelElement; - } - - @Override - public String getOntoUMLType() { - return type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description);; - } - - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } - - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } - - public boolean isDisjoint() { - return isDisjoint; - } - - public void setDisjoint(boolean isDisjoint) { - this.isDisjoint = isDisjoint; - } - - public boolean isComplete() { - return isComplete; - } - - public void setComplete(boolean isComplete) { - this.isComplete = isComplete; - } - - public Reference getCategorizer() { - return this.categorizer; - } - - public void setCategorizer(Reference categorizer) { - this.categorizer = categorizer; - } - - public List getGeneralizations() { - return generalizations; - } - - public void setGeneralizations(List generalizations) { - this.generalizations = generalizations; - } - - public void addGeneralization(Reference ref) { - if (this.generalizations == null) - this.generalizations = new ArrayList(); - - this.generalizations.add(ref); - } - - public void removeGeneralization(Reference ref) { - if (this.generalizations != null && this.generalizations.contains(ref)) - this.generalizations.remove(ref); - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubRelease.java b/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubRelease.java new file mode 100644 index 00000000..faa17556 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubRelease.java @@ -0,0 +1,102 @@ +package it.unibz.inf.ontouml.vp.model; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; + +public class GitHubRelease { + + private static final String PROP_TAG_NAME = "tag_name"; + private static final String PROP_CREATED_AT = "created_at"; + private static final String PROP_PRERELEASE = "prerelease"; + private static final String PROP_ASSETS = "assets"; + private static final String PROP_ID = "id"; + + @Expose() private String tagName; + + // Since Gson shows problems with the default serialization of ZonedDateTime we rely on strings + @Expose() private String createdAt; + + @Expose() private boolean isPrerelease; + + @Expose() private List assets; + + @Expose() private GitHubReleaseAsset installationFileAsset; + + @SerializedName("releaseId") + @Expose() + private String id; + + public GitHubRelease() { + tagName = null; + createdAt = null; + isPrerelease = false; + assets = null; + installationFileAsset = null; + id = null; + } + + public GitHubRelease(JsonObject source) { + if (source == null) { + throw new NullPointerException(); + } + + tagName = source.get(PROP_TAG_NAME).getAsString(); + createdAt = source.get(PROP_CREATED_AT).getAsString(); + isPrerelease = source.get(PROP_PRERELEASE).getAsBoolean(); + id = source.get(PROP_ID).getAsString(); + + assets = new ArrayList<>(); + installationFileAsset = null; + + JsonArray assetsArray = source.get(PROP_ASSETS).getAsJsonArray(); + assetsArray.forEach( + item -> { + GitHubReleaseAsset asset = + item.isJsonObject() ? new GitHubReleaseAsset(item.getAsJsonObject()) : null; + + if (asset != null) { + assets.add(asset); + } + + if (asset.isInstallationFileAsset()) { + installationFileAsset = asset; + } + }); + } + + public ZonedDateTime getCreatedAt() { + if (createdAt != null) return ZonedDateTime.parse(createdAt); + + return null; + } + + public boolean isPrerelease() { + return isPrerelease; + } + + public String getTagName() { + return tagName; + } + + public List getAssets() { + return assets; + } + + public GitHubReleaseAsset getInstallationFileAsset() { + return installationFileAsset; + } + + public String getId() { + return id; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof GitHubRelease ? getId().equals(((GitHubRelease) obj).getId()) : false; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubReleaseAsset.java b/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubReleaseAsset.java new file mode 100644 index 00000000..cd2d48fd --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubReleaseAsset.java @@ -0,0 +1,70 @@ +package it.unibz.inf.ontouml.vp.model; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class GitHubReleaseAsset { + + private static final String PROP_NAME = "name"; + private static final String PROP_ID = "id"; + private static final String PROP_BROWSER_DOWNLOAD_URL = "browser_download_url"; + private static final String PROP_CONTENT_TYPE = "content_type"; + + private static final String CONTENT_TYPE_APPLICATION_ZIP = "application/zip"; + + // public JsonObject source; + + @Expose() private String name; + + @SerializedName("assetId") + @Expose() + private String id; + + @Expose() private String downloadUrl; + + @Expose() private String contentType; + + public GitHubReleaseAsset() { + name = null; + id = null; + downloadUrl = null; + contentType = null; + } + + public GitHubReleaseAsset(JsonObject source) { + if (source == null) { + throw new NullPointerException(); + } + + name = source.get(PROP_NAME).getAsString(); + id = source.get(PROP_ID).getAsString(); + downloadUrl = source.get(PROP_BROWSER_DOWNLOAD_URL).getAsString(); + contentType = source.get(PROP_CONTENT_TYPE).getAsString(); + } + + public String getName() { + return name; + } + + public String getDownloadUrl() { + return downloadUrl; + } + + public String getId() { + return id; + } + + public String getContentType() { + return contentType; + } + + public boolean isInstallationFileAsset() { + return getContentType().equals(CONTENT_TYPE_APPLICATION_ZIP); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof GitHubRelease ? getId().equals(((GitHubRelease) obj).getId()) : false; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Literal.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Literal.java deleted file mode 100644 index 1212d5e4..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Literal.java +++ /dev/null @@ -1,80 +0,0 @@ - package it.unibz.inf.ontouml.vp.model; - -import com.google.gson.JsonObject; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.IEnumerationLiteral; - -public class Literal implements ModelElement { - - private final IEnumerationLiteral sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; - - public Literal(IEnumerationLiteral source) { - this.sourceModelElement = source; - this.type = ModelElement.TYPE_LITERAL; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - } - - @Override - public IEnumerationLiteral getSourceModelElement() { - return this.sourceModelElement; - } - - @Override - public String getId() { - return getSourceModelElement().getId(); - } - - @Override - public String getOntoUMLType() { - return this.type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description);; - } - - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } - - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Model.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Model.java deleted file mode 100644 index 0fc657b7..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Model.java +++ /dev/null @@ -1,387 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import com.google.gson.JsonObject; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.model.IAssociation; -import com.vp.plugin.model.IAssociationClass; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.IDataType; -import com.vp.plugin.model.IGeneralization; -import com.vp.plugin.model.IGeneralizationSet; -import com.vp.plugin.model.IModel; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.IPackage; -import com.vp.plugin.model.IProject; -import com.vp.plugin.model.factory.IModelElementFactory; - -/** - * - * Implementation of ModelElement to handle IModel objects to be serialized as - * ontouml-schema/Package - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - * - */ - -public class Model implements ModelElement { - - private final IModel sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description = null; - - @SerializedName("contents") - @Expose - private List contents; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments = null; - - /** - * - * Constructs a model to contain all project's model elements independent of a - * IModelElement. - * - */ - public Model() { - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - final String[] rootLevelElements = { IModelElementFactory.MODEL_TYPE_PACKAGE, - IModelElementFactory.MODEL_TYPE_MODEL, IModelElementFactory.MODEL_TYPE_CLASS, - IModelElementFactory.MODEL_TYPE_DATA_TYPE }; - final String[] anyLevelElements = { IModelElementFactory.MODEL_TYPE_GENERALIZATION, - IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET, IModelElementFactory.MODEL_TYPE_ASSOCIATION, - IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS }; - - this.sourceModelElement = null; - this.type = ModelElement.TYPE_PACKAGE; - this.id = project.getId(); - this.setName(project.getName()); - this.addModelElements(project.toModelElementArray(rootLevelElements)); - this.addModelElements(project.toAllLevelModelElementArray(anyLevelElements)); - } - - /** - * - * Constructs a model based on the model elements defined by the user - * - * - */ - public Model(HashSet idElements) { - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - final String[] rootLevelElements = { IModelElementFactory.MODEL_TYPE_PACKAGE, - IModelElementFactory.MODEL_TYPE_MODEL, IModelElementFactory.MODEL_TYPE_CLASS, - IModelElementFactory.MODEL_TYPE_DATA_TYPE }; - final String[] anyLevelElements = { IModelElementFactory.MODEL_TYPE_GENERALIZATION, - IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET, IModelElementFactory.MODEL_TYPE_ASSOCIATION, - IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS }; - - this.sourceModelElement = null; - this.type = ModelElement.TYPE_PACKAGE; - this.id = project.getId(); - this.setName(project.getName()); - - if (idElements == null) - return; - - if (containsDiagramModel(idElements)) { - HashSet modelElements = new HashSet(); - - Iterator ite = idElements.iterator(); - // add only valid elements - while (ite.hasNext()) { - String id = ite.next(); - - if (project.getModelElementById(id) == null) - continue; - else - modelElements.add(project.getModelElementById(id)); - } - - IModelElement[] elementsArray = new IModelElement[modelElements.size()]; - modelElements.toArray(elementsArray); - - addModelElements(elementsArray, idElements); - } else { - addModelElements(project.toModelElementArray(rootLevelElements), idElements); - addModelElements(project.toAllLevelModelElementArray(anyLevelElements), idElements); - } - - } - - /** - * - * Constructs a model based on a IModelElement and which is - * serialized as a Package in OntoUML Schema. - * - */ - public Model(IModel source) { - this.sourceModelElement = source; - this.type = ModelElement.TYPE_PACKAGE; - this.id = source.getId(); - this.setName(source.getName()); - this.addModelElements(source.toChildArray()); - } - - public Model(IModel source, HashSet idElements) { - this.sourceModelElement = source; - this.type = ModelElement.TYPE_PACKAGE; - this.id = source.getId(); - this.setName(source.getName()); - - IModelElement[] childArray = source.toChildArray(); - - if (childArray == null) - return; - - for (int i = 0; i < childArray.length; i++) { - if (idElements.contains(childArray[i].getId())) { - this.addModelElement(childArray[i], idElements); - } - } - - } - - @Override - public String getId() { - return getSourceModelElement() != null ? getSourceModelElement().getId() : null; - } - - @Override - public IModel getSourceModelElement() { - return this.sourceModelElement; - } - - public String getOntoUMLType() { - return type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description); - } - - public List getElements() { - return contents; - } - - public void setElements(List elementsList) { - this.contents = elementsList; - } - - public void addElement(ModelElement element) { - if (this.contents == null) - this.contents = new ArrayList(); - - this.contents.add(element); - } - - public boolean removeElement(ModelElement element) { - return this.contents.remove(element); - } - - private void addModelElement(IModelElement projectElement, HashSet idElements) { - - switch (projectElement.getModelType()) { - case IModelElementFactory.MODEL_TYPE_PACKAGE: - addElement(new Package((IPackage) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_MODEL: - addElement(new Model((IModel) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_CLASS: - addElement(new Class((IClass) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_DATA_TYPE: - addElement(new Class((IDataType) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_GENERALIZATION: - IGeneralization gen = (IGeneralization) projectElement; - IModelElement fromElement = gen.getFrom(); - - if (fromElement == null) - break; - - String fromType = fromElement.getModelType(); - - if (fromType == null) - break; - - boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - - if (!isFromClass && !isFromAssociation) - break; - - IModelElement toElement = gen.getTo(); - - if (toElement == null) - break; - - String toType = toElement.getModelType(); - - if (toType == null) - break; - - boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - - if (!isToClass && !isToAssociation) - break; - - addElement(new Generalization((IGeneralization) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_ASSOCIATION: - addElement(new Association((IAssociation) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: - addElement(new GeneralizationSet((IGeneralizationSet) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: - addElement(new AssociationClass((IAssociationClass) projectElement)); - } - } - - private void addModelElements(IModelElement[] modelElements, HashSet idElements) { - for (int i = 0; modelElements != null && i < modelElements.length; i++) { - final IModelElement projectElement = modelElements[i]; - - if (!idElements.contains(projectElement.getId())) - continue; - - addModelElement(projectElement, idElements); - - } - } - - private void addModelElements(IModelElement[] modelElements) { - for (int i = 0; modelElements != null && i < modelElements.length; i++) { - final IModelElement projectElement = modelElements[i]; - - switch (projectElement.getModelType()) { - case IModelElementFactory.MODEL_TYPE_PACKAGE: - addElement(new Package((IPackage) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_MODEL: - addElement(new Model((IModel) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_CLASS: - addElement(new Class((IClass) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_DATA_TYPE: - addElement(new Class((IDataType) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_GENERALIZATION: - IGeneralization gen = (IGeneralization) projectElement; - IModelElement fromElement = gen.getFrom(); - - if (fromElement == null) - break; - - String fromType = fromElement.getModelType(); - - if (fromType == null) - break; - - boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - - if (!isFromClass && !isFromAssociation) - break; - - IModelElement toElement = gen.getTo(); - - if (toElement == null) - break; - - String toType = toElement.getModelType(); - - if (toType == null) - break; - - boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - - if (!isToClass && !isToAssociation) - break; - - addElement(new Generalization((IGeneralization) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_ASSOCIATION: - addElement(new Association((IAssociation) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: - addElement(new GeneralizationSet((IGeneralizationSet) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: - addElement(new AssociationClass((IAssociationClass) projectElement)); - } - } - } - - private static boolean containsDiagramModel(HashSet idElements) { - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - - Iterator ite = idElements.iterator(); - - while (ite.hasNext()) { - String id = ite.next(); - - if (project.getDiagramById(id) == null) - continue; - else - return true; - - } - - return false; - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/ModelElement.java b/src/main/java/it/unibz/inf/ontouml/vp/model/ModelElement.java deleted file mode 100644 index f6cc1f04..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/ModelElement.java +++ /dev/null @@ -1,232 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.ITaggedValue; -import com.vp.plugin.model.ITaggedValueContainer; -import com.vp.plugin.model.factory.IModelElementFactory; - -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; - -/** - * @author Victor Viola - * @author Claudenir Fonseca - */ -public interface ModelElement { - - public static final String TYPE_PACKAGE = "Package"; - public static final String TYPE_CLASS = "Class"; - public static final String TYPE_RELATION = "Relation"; - public static final String TYPE_ASSOCIATION_CLASS = "Relation"; - public static final String TYPE_GENERALIZATION = "Generalization"; - public static final String TYPE_GENERALIZATION_SET = "GeneralizationSet"; - public static final String TYPE_PROPERTY = "Property"; - public static final String TYPE_LITERAL = "Literal"; - - /** - * @return IModelElement on which the object is based. - */ - public IModelElement getSourceModelElement(); - - /** - * @return object's type in OntoUML Schema. - */ - public String getOntoUMLType(); - - /** - * @return object's ID (based on a IModelElement). - */ - public String getId(); - - /** - * Returns Visual Paradigm's link to the related model element. This method - * removes the project's name which originally start the link returned. - * - * @param modelElement - Instance of ModelElement based on a - * IModelElement. - * @return a link identify a IModelElement in Visual Paradigm - * following the pattern - * "vpp://modelelement/Cd.WKPaAUB22rwx4". - */ - public static String getLink(ModelElement modelElement) { - return modelElement.getSourceModelElement() != null ? ModelElement - .getModelElementURI(modelElement.getSourceModelElement()) - : null; - } - - /** - * Returns Visual Paradigm's link to the related model element. This method - * removes the project's name which originally start the link returned. - * - * @param modelElement - * @return a link identify a IModelElement in Visual Paradigm - * following the pattern - * "vpp://modelelement/Cd.WKPaAUB22rwx4". - */ - public static String getModelElementURI(IModelElement modelElement) { - if (modelElement == null) - return null; - - final String link = ApplicationManager.instance().getProjectManager() - .getLink(modelElement, false); - - return link.substring(link.indexOf(".vpp:") + 1); - } - - /** - * Returns serialized JSON string of a ModelElement in OntoUML - * Schema. - * - * @param modelElement - * @param pretty - true if return string should be indented. - * @return serialized version JSON of a ModelElement. - */ - public static String serialize(ModelElement modelElement, boolean pretty) { - if (pretty) { - return new GsonBuilder().excludeFieldsWithoutExposeAnnotation() - .serializeNulls().setPrettyPrinting().create().toJson(modelElement); - } else { - return new GsonBuilder().excludeFieldsWithoutExposeAnnotation() - .serializeNulls().create().toJson(modelElement); - } - } - - /** - * Returns serialized JSON string of the whole project in OntoUML Schema. - * - * @param pretty - true if return string should be indented. - * @return serialized version JSON of whole project in OntoUML Schema. - */ - public static String generateModel(boolean pretty) { - final Model model = new Model(); - - if (pretty) { - return new GsonBuilder().excludeFieldsWithoutExposeAnnotation() - .serializeNulls().setPrettyPrinting().create().toJson(model); - } else { - return new GsonBuilder().excludeFieldsWithoutExposeAnnotation() - .serializeNulls().create().toJson(model); - } - } - - public static String generateModel(HashSet elements, boolean pretty) { - - final Model model = new Model(elements); - /* - Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard(); - StringSelection sl = new StringSelection(new GsonBuilder().excludeFieldsWithoutExposeAnnotation() - .serializeNulls().setPrettyPrinting().create().toJson(model)); - c.setContents(sl, sl); - */ - if (pretty) { - return new GsonBuilder().excludeFieldsWithoutExposeAnnotation() - .serializeNulls().setPrettyPrinting().create().toJson(model); - } else { - return new GsonBuilder().excludeFieldsWithoutExposeAnnotation() - .serializeNulls().create().toJson(model); - } - } - - public static String safeGetString(String s) { - if (s != null && s.length() != 0) - return s; - return null; - } - - public static String toOntoUMLSchemaType(IModelElement element) { - switch (element.getModelType()) { - case IModelElementFactory.MODEL_TYPE_MODEL: - case IModelElementFactory.MODEL_TYPE_PACKAGE: - return TYPE_PACKAGE; - case IModelElementFactory.MODEL_TYPE_CLASS: - case IModelElementFactory.MODEL_TYPE_DATA_TYPE: - return TYPE_CLASS; - case IModelElementFactory.MODEL_TYPE_ASSOCIATION: - case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: - return TYPE_RELATION; - case IModelElementFactory.MODEL_TYPE_GENERALIZATION: - return TYPE_GENERALIZATION; - case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: - return TYPE_GENERALIZATION_SET; - case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: - case IModelElementFactory.MODEL_TYPE_ASSOCIATION_END: - return TYPE_PROPERTY; - case IModelElementFactory.MODEL_TYPE_ENUMERATION_LITERAL: - return TYPE_LITERAL; - } - - return null; - } - - public static JsonObject transformPropertyAssignments(IModelElement sourceElement) { - ITaggedValueContainer lContainer = sourceElement.getTaggedValues(); - if (lContainer == null) - return null; - - JsonObject obj = new JsonObject(); - ITaggedValue[] lTaggedValues = lContainer.toTaggedValueArray(); - List ignoredClassValues = - Arrays.asList(new String[]{StereotypeUtils.PROPERTY_RESTRICTED_TO, - StereotypeUtils.PROPERTY_IS_EXTENSIONAL, - StereotypeUtils.PROPERTY_IS_POWERTYPE, - StereotypeUtils.PROPERTY_ORDER}); - - for (int i = 0; lTaggedValues != null && i < lTaggedValues.length; i++) { - if (ignoredClassValues.contains(lTaggedValues[i].getName())) { - continue; - } - - switch (lTaggedValues[i].getType()) { - case 1: - JsonObject referenceTag = new JsonObject(); - - if (lTaggedValues[i].getValueAsElement() != null) { - referenceTag.addProperty("type", ModelElement.toOntoUMLSchemaType(lTaggedValues[i].getValueAsElement())); - referenceTag.addProperty("id", lTaggedValues[i].getValueAsElement().getId()); - } else { - referenceTag = null; - } - obj.add(lTaggedValues[i].getName(), referenceTag); - break; - case 5: - obj.addProperty(lTaggedValues[i].getName(), Integer.parseInt((String) lTaggedValues[i].getValue())); - break; - case 6: - obj.addProperty(lTaggedValues[i].getName(), Float.parseFloat((String) lTaggedValues[i].getValue())); - break; - case 7: - obj.addProperty(lTaggedValues[i].getName(), Boolean.parseBoolean((String) lTaggedValues[i].getValue())); - break; - default: - obj.addProperty(lTaggedValues[i].getName(), (String) lTaggedValues[i].getValueAsString()); - } - } - - if (obj.size() == 0) - return null; - - return obj; - } - - public static boolean getIsDerived(IModelElement element) { - return element.getName().trim().startsWith("/"); - } - - public static void setIsDerived(IModelElement element, boolean isDerived) { - final String currentName = element.getName() != null ? - element.getName().trim() : ""; - - if (getIsDerived(element)) { - element.setName(currentName.substring(1)); - } else { - element.setName("/" + currentName); - } - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Package.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Package.java deleted file mode 100644 index 6d3d0f83..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Package.java +++ /dev/null @@ -1,228 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import com.google.gson.JsonObject; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.*; -import com.vp.plugin.model.factory.IModelElementFactory; - -import java.util.HashSet; -import java.util.LinkedList; - -/** - * Implementation of ModelElement to handle IPackage objects to be serialized as - * ontouml-schema/Package - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - */ - -public class Package implements ModelElement { - - private final IPackage sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; - - @SerializedName("contents") - @Expose - private LinkedList contents; - - public Package(IPackage source) { - this.sourceModelElement = source; - this.type = ModelElement.TYPE_PACKAGE; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - final IModelElement[] children = source.toChildArray(); - for (int i = 0; children != null && i < children.length; i++) { - final IModelElement child = children[i]; - - switch (child.getModelType()) { - case IModelElementFactory.MODEL_TYPE_PACKAGE: - addElement(new Package((IPackage) child)); - break; - case IModelElementFactory.MODEL_TYPE_MODEL: - addElement(new Model((IModel) child)); - break; - case IModelElementFactory.MODEL_TYPE_CLASS: - addElement(new Class((IClass) child)); - break; - // TODO Add remaining elements, maybe by adding these to relation's - // source's package. - // case IModelElementFactory.MODEL_TYPE_GENERALIZATION: - // case IModelElementFactory.MODEL_TYPE_ASSOCIATION: - // case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: - // case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: - } - } - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - } - - public Package(IPackage source, HashSet idElements) { - this.sourceModelElement = source; - this.type = ModelElement.TYPE_PACKAGE; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - IModelElement[] childArray = source.toChildArray(); - - if (childArray == null) - return; - - for (int i = 0; i < childArray.length; i++) { - if (idElements.contains(childArray[i].getId())) { - addModelElement(childArray[i], idElements); - } - } - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - } - - @Override - public IPackage getSourceModelElement() { - return sourceModelElement; - } - - @Override - public String getId() { - return getSourceModelElement().getId(); - } - - @Override - public String getOntoUMLType() { - return this.type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description); - ; - } - - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } - - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } - - public LinkedList getContents() { - return contents; - } - - public void setContents(LinkedList contents) { - this.contents = contents; - } - - public void addElement(ModelElement element) { - if (getContents() == null) { - setContents(new LinkedList()); - } - - this.contents.add(element); - } - - private void addModelElement(IModelElement projectElement, HashSet idElements) { - - switch (projectElement.getModelType()) { - case IModelElementFactory.MODEL_TYPE_PACKAGE: - addElement(new Package((IPackage) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_MODEL: - addElement(new Model((IModel) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_CLASS: - addElement(new Class((IClass) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_DATA_TYPE: - addElement(new Class((IDataType) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_GENERALIZATION: - IGeneralization gen = (IGeneralization) projectElement; - IModelElement fromElement = gen.getFrom(); - - if (fromElement == null) - break; - - String fromType = fromElement.getModelType(); - - if (fromType == null) - break; - - boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - - if (!isFromClass && !isFromAssociation) - break; - - IModelElement toElement = gen.getTo(); - - if (toElement == null) - break; - - String toType = toElement.getModelType(); - - if (toType == null) - break; - - boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - - if (!isToClass && !isToAssociation) - break; - - addElement(new Generalization((IGeneralization) projectElement)); - break; - - case IModelElementFactory.MODEL_TYPE_ASSOCIATION: - addElement(new Association((IAssociation) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: - addElement(new GeneralizationSet((IGeneralizationSet) projectElement, idElements)); - break; - - case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: - addElement(new AssociationClass((IAssociationClass) projectElement)); - } - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/ProjectConfigurations.java b/src/main/java/it/unibz/inf/ontouml/vp/model/ProjectConfigurations.java new file mode 100644 index 00000000..9c4cc3ef --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/ProjectConfigurations.java @@ -0,0 +1,428 @@ +package it.unibz.inf.ontouml.vp.model; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import java.util.HashSet; + +/** + * Class that captures user preferences for a given project and enables JSON serialization. + * + * @author Claudenir Fonseca + * @author Victor Viola + */ +/** @author Victor Viola */ +public class ProjectConfigurations { + + public static final boolean DEFAULT_IS_PLUGIN_ENABLED = true; + public static final boolean DEFAULT_IS_CUSTOM_SERVER_ENABLED = false; + public static final boolean DEFAULT_IS_EXPORT_ENABLED = true; + public static final boolean DEFAULT_IS_AUTOMATIC_COLORING_ENABLED = true; + public static final boolean DEFAULT_IS_AUTOMATIC_MODELLING_ENABLED = true; + public static final boolean DEFAULT_IGNORE_ASSOCIATION_INVERSION_WARNING = false; + public static final String DEFAULT_SERVER_URL = "http://api.ontouml.org"; + public static final String DEFAULT_EXPORT_PATH = System.getProperty("user.home"); + public static final String DEFAULT_EXPORT_FILENAME = ""; + public static final String DEFAULT_GUFO_EXPORT_PATH = System.getProperty("user.home"); + public static final String DEFAULT_GUFO_EXPORT_FILENAME = ""; + + @SerializedName("projectId") + @Expose() + private String id; + + @SerializedName("isOntoUMLPluginEnabled") + @Expose() + private boolean isOntoUMLPluginEnabled; + + @SerializedName("serverURL") + @Expose() + private String serverURL; + + @SerializedName("isCustomServerEnabled") + @Expose() + private boolean isCustomServerEnabled; + + @SerializedName("exportFolderPath") + @Expose() + private String exportFolderPath; + + @SerializedName("exportFileName") + @Expose() + private String exportFileName; + + @SerializedName("exportGUFOFolderPath") + @Expose() + private String exportGUFOFolderPath; + + @SerializedName("exportGUFOFileName") + @Expose() + private String exportGUFOFileName; + + @SerializedName("exportGUFOIRI") + @Expose() + private String exportGUFOIRI; + + @SerializedName("exportGUFOFormat") + @Expose() + private String exportGUFOFormat; + + @SerializedName("exportGUFOURIFormat") + @Expose() + private String exportGUFOURIFormat; + + @SerializedName("exportGUFOElementsDiagramTree") + @Expose() + private HashSet exportGUFOElementsDiagramTree; + + @SerializedName("exportGUFOElementsPackageTree") + @Expose() + private HashSet exportGUFOElementsPackageTree; + + @SerializedName("exportGUFOInverseBox") + @Expose() + private String exportGUFOInverseBox; + + @SerializedName("exportGUFOObjectBox") + @Expose() + private String exportGUFOObjectBox; + + @SerializedName("exportGUFOAnalysisBox") + @Expose() + private String exportGUFOAnalysisBox; + + @SerializedName("exportGUFOPackagesBox") + @Expose() + private String exportGUFOPackagesBox; + + @SerializedName("exportGUFOElementMapping") + @Expose() + private String exportGUFOElementMapping; + + @SerializedName("exportGUFOPackageMapping") + @Expose() + private String exportGUFOPackageMapping; + + @SerializedName("isExportEnabled") + @Expose() + private boolean isModelExportEnabled; + + @SerializedName("isAutomaticColoringEnabled") + @Expose() + private boolean isAutomaticColoringEnabled; + + @SerializedName("isSmartModellingEnabled") + @Expose() + private boolean isSmartModellingEnabled; + + @SerializedName("ignoreAssociationInversionWarning") + @Expose() + private boolean ignoreAssociationInversionWarning; + + /** Constructor without args to be called when deserializing project settings. */ + public ProjectConfigurations() { + this.id = ""; + this.setDefaultValues(); + } + + /** + * Initializes an instance of ProjectConfigurations with default settings. + * + * @param projectId - String containing the ID of the project related to initialized + * configuration. + */ + public ProjectConfigurations(String projectId) { + this.id = projectId; + this.setDefaultValues(); + } + + /** + * Resets default project configurations. By default, none of the options are enabled and the + * server's URL is the plugin's defaults. + */ + public void setDefaultValues() { + this.isOntoUMLPluginEnabled = ProjectConfigurations.DEFAULT_IS_PLUGIN_ENABLED; + + this.isCustomServerEnabled = ProjectConfigurations.DEFAULT_IS_CUSTOM_SERVER_ENABLED; + this.serverURL = ProjectConfigurations.DEFAULT_SERVER_URL; + + this.isModelExportEnabled = ProjectConfigurations.DEFAULT_IS_EXPORT_ENABLED; + this.exportFolderPath = ProjectConfigurations.DEFAULT_EXPORT_PATH; + this.exportFileName = ProjectConfigurations.DEFAULT_EXPORT_FILENAME; + this.exportGUFOFolderPath = ProjectConfigurations.DEFAULT_GUFO_EXPORT_PATH; + this.exportGUFOFileName = ProjectConfigurations.DEFAULT_GUFO_EXPORT_FILENAME; + + this.isAutomaticColoringEnabled = ProjectConfigurations.DEFAULT_IS_AUTOMATIC_COLORING_ENABLED; + this.isSmartModellingEnabled = ProjectConfigurations.DEFAULT_IS_AUTOMATIC_MODELLING_ENABLED; + this.ignoreAssociationInversionWarning = + ProjectConfigurations.DEFAULT_IGNORE_ASSOCIATION_INVERSION_WARNING; + } + + /** + * Returns the related project's ID. + * + * @return project's ID. + */ + public String getId() { + return id; + } + + /** + * Checks if OntoUMLPlugin is enabled for the related project. + * + * @return true if plugin is enabled. + */ + public boolean isOntoUMLPluginEnabled() { + return isOntoUMLPluginEnabled; + } + + /** + * Sets if OntoUMLPlugin is enabled for the related project. + * + * @param isOntoUMLPluginEnabled + */ + public void setOntoUMLPluginEnabled(boolean isOntoUMLPluginEnabled) { + this.isOntoUMLPluginEnabled = isOntoUMLPluginEnabled; + } + + /** + * Returns OntoUML Server URL. + * + * @return serverURL + */ + public String getServerURL() { + return serverURL; + } + + /** + * Sets OntoUML Server URL. + * + * @param serverURL + */ + public void setServerURL(String serverURL) { + this.serverURL = serverURL; + } + + /** + * Checks if a custom server URL must be used. + * + * @return true if plugin is enabled and a custom server is enabled. + * @see {@link #isOntoUMLPluginEnabled()} + */ + public boolean isCustomServerEnabled() { + return isOntoUMLPluginEnabled() && isCustomServerEnabled; + } + + /** + * Sets if a custom server URL must be used. + * + * @param isCustomServerEnabled + */ + public void setCustomServerEnabled(boolean isCustomServerEnabled) { + this.isCustomServerEnabled = isCustomServerEnabled; + } + + /** + * Returns automatic export folders path as a String. + * + * @return exportFolderPath + */ + public String getExportFolderPath() { + return exportFolderPath; + } + + /** + * Sets automatic export folders path from a String. + * + * @param exportFolderPath + */ + public void setExportFolderPath(String exportFolderPath) { + this.exportFolderPath = exportFolderPath; + } + + /** + * Returns automatic export filename as a String. + * + * @return exportFileName + */ + public String getExportFilename() { + return exportFileName; + } + + /** + * Sets automatic export filename from a String. + * + * @param exportFileName + */ + public void setExportFilename(String exportFileName) { + this.exportFileName = exportFileName; + } + + public void setExportGUFOFolderPath(String exportFolderPath) { + this.exportGUFOFolderPath = exportFolderPath; + } + + public String getExportGUFOFolderPath() { + return exportGUFOFolderPath; + } + + public void setExportGUFOFilename(String exportFilename) { + this.exportGUFOFileName = exportFilename; + } + + public String getExportGUFOFilename() { + return exportGUFOFileName; + } + + public String getExportGUFOIRI() { + return exportGUFOIRI; + } + + public void setExportGUFOIRI(String exportGUFOIRI) { + this.exportGUFOIRI = exportGUFOIRI; + } + + public String getExportGUFOFormat() { + return exportGUFOFormat; + } + + public void setExportGUFOFormat(String exportGUFOFormat) { + this.exportGUFOFormat = exportGUFOFormat; + } + + public String getExportGUFOURIFormat() { + return exportGUFOURIFormat; + } + + public void setExportGUFOURIFormat(String exportGUFOURIFormat) { + this.exportGUFOURIFormat = exportGUFOURIFormat; + } + + public HashSet getExportGUFOElementsDiagramTree() { + return exportGUFOElementsDiagramTree; + } + + public void setExportGUFOElementsDiagramTree(HashSet exportGUFOElementsDiagramTree) { + this.exportGUFOElementsDiagramTree = exportGUFOElementsDiagramTree; + } + + public HashSet getExportGUFOElementsPackageTree() { + return exportGUFOElementsPackageTree; + } + + public void setExportGUFOElementsPackageTree(HashSet exportGUFOElementsPackageTree) { + this.exportGUFOElementsPackageTree = exportGUFOElementsPackageTree; + } + + public String getExportGUFOInverseBox() { + return exportGUFOInverseBox; + } + + public void setExportGUFOInverseBox(String exportGUFOInverseBox) { + this.exportGUFOInverseBox = exportGUFOInverseBox; + } + + public String getExportGUFOObjectBox() { + return exportGUFOObjectBox; + } + + public void setExportGUFOObjectBox(String exportGUFOObjectBox) { + this.exportGUFOObjectBox = exportGUFOObjectBox; + } + + public String getExportGUFOAnalysisBox() { + return exportGUFOAnalysisBox; + } + + public void setExportGUFOAnalysisBox(String exportGUFOAnalysisBox) { + this.exportGUFOAnalysisBox = exportGUFOAnalysisBox; + } + + public String getExportGUFOPackagesBox() { + return exportGUFOPackagesBox; + } + + public void setExportGUFOPackagesBox(String exportGUFOPackagesBox) { + this.exportGUFOPackagesBox = exportGUFOPackagesBox; + } + + public String getExportGUFOElementMapping() { + return exportGUFOElementMapping; + } + + public void setExportGUFOElementMapping(String exportGUFOElementMapping) { + this.exportGUFOElementMapping = exportGUFOElementMapping; + } + + public String getExportGUFOPackageMapping() { + return exportGUFOPackageMapping; + } + + public void setExportGUFOPackageMapping(String exportGUFOPackageMapping) { + this.exportGUFOPackageMapping = exportGUFOPackageMapping; + } + + /** + * Checks if an export folder is set for automatic model export. + * + * @return true if plugin is enabled and automatic model export is enabled. + * @see {@link #isOntoUMLPluginEnabled()} + */ + public boolean isModelExportEnabled() { + return isOntoUMLPluginEnabled() && isModelExportEnabled; + } + + /** + * Sets if automatic model export is enabled. + * + *

param isModelExportEnabled + */ + public void setModelExportEnabled(boolean isModelExportEnabled) { + this.isModelExportEnabled = isModelExportEnabled; + } + + /** + * Checks if model elements should be automatically painted with the default color profile. + * + * @return true if plugin is enabled and automatic model element coloring is + * enabled. + * @see {@link #isOntoUMLPluginEnabled()} + */ + public boolean isAutomaticColoringEnabled() { + return isOntoUMLPluginEnabled() && isAutomaticColoringEnabled; + } + + /** + * Sets if model elements should be automatically painted with the default color profile. + * + * @param isAutomaticColoringEnabled + */ + public void setAutomaticColoringEnabled(boolean isAutomaticColoringEnabled) { + this.isAutomaticColoringEnabled = isAutomaticColoringEnabled; + } + + /** + * Checks if class stereotypes should be automatically disabled.. + * + * @return true if plugin is enabled and smart modelling is enabled. + * @see {@link #isOntoUMLPluginEnabled()} + */ + public boolean isSmartModellingEnabled() { + return isOntoUMLPluginEnabled() && isSmartModellingEnabled; + } + + /** + * Sets if class stereotypes should be automatically disabled. + * + * @param isSmartModellingEnabled + */ + public void setSmartModellingEnabled(boolean isSmartModellingEnabled) { + this.isSmartModellingEnabled = isSmartModellingEnabled; + } + + public boolean ignoreAssociationInversionWarning() { + return this.ignoreAssociationInversionWarning; + } + + public void setIgnoreAssociationInversionWarning(boolean ignoreAssociationInversionWarning) { + this.ignoreAssociationInversionWarning = ignoreAssociationInversionWarning; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Property.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Property.java deleted file mode 100644 index 69eb03b1..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Property.java +++ /dev/null @@ -1,385 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import com.google.gson.JsonObject; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.*; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * - * Implementation of ModelElement to handle IAtrribute and IAssociationEnd - * objects to be serialized as ontouml-schema/Property - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - * - */ - -public class Property implements ModelElement { - - private final IModelElement sourceModelElement; - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - @SerializedName("name") - @Expose - private String name; - - @SerializedName("description") - @Expose - private String description; - - @SerializedName("propertyType") - @Expose - private Reference propertyType; - - @SerializedName("cardinality") - @Expose - private String cardinality; - - @SerializedName("isDerived") - @Expose - private boolean isDerived; - - @SerializedName("isOrdered") - @Expose - private boolean isOrdered; - - @SerializedName("isReadOnly") - @Expose - private boolean isReadOnly; - - @SerializedName("stereotypes") - @Expose - private List stereotypes; - - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; - - @SerializedName("subsettedProperties") - @Expose - private List subsettedProperties; - - @SerializedName("redefinedProperties") - @Expose - private List redefinedProperties; - - @SerializedName("aggregationKind") - @Expose - private String aggregationKind; - - private Property(IModelElement source) { - this.sourceModelElement = source; - - this.type = ModelElement.TYPE_PROPERTY; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); - - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - - } - - public Property(IAttribute source) { - this((IModelElement) source); - - IModelElement reference = source.getTypeAsElement(); - if (reference != null) { - setPropertyType(new Reference(reference)); - } else { - System.out.println("Attribute " + source.getParent().getName() + "::" + source.getName() - + " type is a non-standard string: " + source.getTypeAsString()); - } - - if (!((source.getMultiplicity()).equals(IAttribute.MULTIPLICITY_UNSPECIFIED))) - setCardinality(source.getMultiplicity()); - - setOrdered(source.getMultiplicityDetail()); - setDerived(source.isDerived()); - setReadOnly(source.isReadOnly()); - - final String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); - } - - Iterator subsettedIterator = source.subsettedPropertyIterator(); - while (subsettedIterator.hasNext()) { - IAttribute atr = (IAttribute) subsettedIterator.next(); - addSubsettedProperty(new Reference(atr)); - } - - Iterator redefinedProperties = source.redefinedPropertyIterator(); - while (redefinedProperties.hasNext()) { - IAttribute rdp = (IAttribute) redefinedProperties.next(); - addRedefinedProperty(new Reference(rdp)); - } - - setAggregationKind(source.getAggregation()); - setDerived(source.isDerived()); - } - - public Property(IAssociationEnd source) { - this((IModelElement) source); - - IModelElement reference = source.getTypeAsElement(); - if (reference != null) { - setPropertyType(new Reference(reference)); - } else { - if (source != null && source.getParent() != null) { - System.out.println("Association End " + source.getParent().getName() + "::" + source.getName() - + " type is a non-standard string: " + source.getTypeAsString()); - } - else { - System.out.println("Strange..."); - } - } - - if (!((source.getMultiplicity()).equals(IAttribute.MULTIPLICITY_UNSPECIFIED))) - setCardinality(source.getMultiplicity()); - - setDerived(source.isDerived()); - setOrdered(source.getMultiplicityDetail()); - setReadOnly(source.isReadOnly()); - - final String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); - } - - Iterator subsettedIterator = source.subsettedPropertyIterator(); - - while (subsettedIterator.hasNext()) { - IAssociationEnd sub = (IAssociationEnd) subsettedIterator.next(); - addSubsettedProperty(new Reference(sub)); - } - - Iterator redefinedProperties = source.redefinedPropertyIterator(); - - while (redefinedProperties.hasNext()) { - IAssociationEnd rdp = (IAssociationEnd) redefinedProperties.next(); - addRedefinedProperty(new Reference(rdp)); - } - - setAggregationKind(source.getAggregationKind()); - } - - public Property(IAssociationClass associationClass, IModelElement type) { - this.sourceModelElement = null; - - this.type = ModelElement.TYPE_PROPERTY; - this.id = associationClass.getId() + type.getId(); - setName(null); - setDescription(null); - - if (type != null) - setPropertyType(new Reference(type)); - - setCardinality("0..*"); - } - - @Override - public String getId() { - return getSourceModelElement().getId(); - } - - @Override - public IModelElement getSourceModelElement() { - return this.sourceModelElement; - } - - @Override - public String getOntoUMLType() { - return this.type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description); - ; - } - - public Reference getPropertyType() { - return propertyType; - } - - public void setPropertyType(Reference propertyType) { - this.propertyType = propertyType; - } - - public String getCardinality() { - return cardinality; - } - - public void setCardinality(String cardinality) { - this.cardinality = cardinality; - } - - public boolean isDerived() { - return isDerived; - } - - public void setDerived(boolean isDerived) { - this.isDerived = isDerived; - } - - public boolean isOrdered() { - return isOrdered; - } - - public void setOrdered(boolean isOrdered) { - this.isOrdered = isOrdered; - } - - public void setOrdered(IMultiplicity multiplicity) { - this.isOrdered = (multiplicity != null) ? multiplicity.isOrdered() : false; - } - - public boolean isReadOnly() { - return isReadOnly; - } - - public void setReadOnly(boolean isReadOnly) { - this.isReadOnly = isReadOnly; - } - - public List getStereotypes() { - return this.stereotypes; - } - - public void setStereotypes(List stereotypes) { - this.stereotypes = stereotypes; - } - - public String getStereotype(int position) { - return this.stereotypes.get(position); - } - - public void addStereotype(String name) { - if (this.stereotypes == null) - this.stereotypes = new ArrayList(); - - this.stereotypes.add(name); - } - - public void removeStereotype(String name) { - if (this.stereotypes != null && this.stereotypes.contains(name)) - this.stereotypes.remove(name); - } - - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } - - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } - - public List getSubsettedProperties() { - return subsettedProperties; - } - - public void setSubsettedProperties(List subsettedProperties) { - this.subsettedProperties = subsettedProperties; - } - - public void addSubsettedProperty(Reference ref) { - if (this.subsettedProperties == null) - this.subsettedProperties = new ArrayList(); - - this.subsettedProperties.add(ref); - } - - public void removeSubsettedProperty(Reference ref) { - if (this.subsettedProperties != null && this.subsettedProperties.contains(ref)) - this.subsettedProperties.remove(ref); - } - - public List getRedefinedProperties() { - return redefinedProperties; - } - - public void setRedefinedProperties(List redefinedPropeties) { - this.redefinedProperties = redefinedPropeties; - } - - public void addRedefinedProperty(Reference ref) { - if (this.redefinedProperties == null) - this.redefinedProperties = new ArrayList(); - - this.redefinedProperties.add(ref); - } - - public void removeRedefinedProperty(Reference ref) { - if (this.redefinedProperties != null && this.redefinedProperties.contains(ref)) - this.redefinedProperties.remove(ref); - } - - public String getAggregationKind() { - return aggregationKind; - } - - public void setAggregationKind(int aggregation) { - switch (aggregation) { - case 0: - this.aggregationKind = "NONE"; - break; - case 1: - this.aggregationKind = "SHARED"; - break; - case 2: - this.aggregationKind = "COMPOSITE"; - break; - default: - } - } - - public void setAggregationKind(String aggregationKind) { - if (aggregationKind == null) { - this.aggregationKind = null; - return; - } - - switch (aggregationKind.toUpperCase()) { - case "NONE": - this.aggregationKind = "NONE"; - return; - case "COMPOSITED": - this.aggregationKind = "COMPOSITE"; - return; - case "SHARED": - this.aggregationKind = "SHARED"; - return; - default: - this.aggregationKind = null; - } - } - - public String getType() { - return type; - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/PropertyDescription.java b/src/main/java/it/unibz/inf/ontouml/vp/model/PropertyDescription.java new file mode 100644 index 00000000..1b84033c --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/PropertyDescription.java @@ -0,0 +1,67 @@ +package it.unibz.inf.ontouml.vp.model; + +import com.vp.plugin.model.IAssociationEnd; +import com.vp.plugin.model.IMultiplicity; +import com.vp.plugin.model.ITaggedValueContainer; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import it.unibz.inf.ontouml.vp.model.uml.Property; + +public class PropertyDescription { + + private IAssociationEnd associationEnd; + final boolean isDerived; // must invert + final boolean isReadOnly; // must invert + final String aggregationKind; // must invert + final String multiplicity; // must invert + final String name; // must invert + final IMultiplicity multiplicityDetail; // must invert + final ITaggedValueContainer taggedValues; // I don't know + final IAssociationEnd[] redefinedProperties; // must invert + final IAssociationEnd[] subsettedProperties; // must invert + + public PropertyDescription(IAssociationEnd associationEnd) { + this.associationEnd = associationEnd; + + aggregationKind = associationEnd.getAggregationKind(); + multiplicityDetail = associationEnd.getMultiplicityDetail(); + multiplicity = associationEnd.getMultiplicity(); + name = associationEnd.getName(); + taggedValues = associationEnd.getTaggedValues(); + isDerived = associationEnd.isDerived(); + isReadOnly = associationEnd.isReadOnly(); + redefinedProperties = associationEnd.toRedefinedPropertyArray(); + subsettedProperties = associationEnd.toSubsettedPropertyArray(); + } + + public void copyTo(IAssociationEnd associationEnd) { + associationEnd.setAggregationKind(aggregationKind); + associationEnd.setName(name); + associationEnd.setMultiplicity(multiplicity); + + ModelElement.setDerived(associationEnd, isDerived); + + if (multiplicityDetail != null) { + ModelElement.setOrdered(associationEnd, multiplicityDetail.isOrdered()); + } + + if (taggedValues != null) { + associationEnd.setTaggedValues((ITaggedValueContainer) taggedValues.duplicate()); + } + + Property.removeRedefinedProperties(associationEnd); + Property.removeSubsettedProperties(associationEnd); + Property.addRedefinedProperties(associationEnd, redefinedProperties); + Property.addSubsettedProperties(associationEnd, subsettedProperties); + } + + public void partialCopyTo(IAssociationEnd associationEnd) { + associationEnd.setName(name); + + ModelElement.setDerived(associationEnd, isDerived); + + Property.removeRedefinedProperties(associationEnd); + Property.removeSubsettedProperties(associationEnd); + Property.addRedefinedProperties(associationEnd, redefinedProperties); + Property.addSubsettedProperties(associationEnd, subsettedProperties); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/Reference.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Reference.java deleted file mode 100644 index 14e2f9c6..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Reference.java +++ /dev/null @@ -1,45 +0,0 @@ -package it.unibz.inf.ontouml.vp.model; - -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.model.IModelElement; - -/** - * - * Implementation of ModelElement to handle IModelElement objects - * which are referred by other elements in the model. - * They are serialized as ontouml-schema/Reference. - * - * @author Claudenir Fonseca - * @author Tiago Prince Sales - * @author Victor Viola - * - */ - -public class Reference { - - @SerializedName("type") - @Expose - private final String type; - - @SerializedName("id") - @Expose - private final String id; - - public Reference(IModelElement element) { - this.id = element.getId(); - this.type = ModelElement.toOntoUMLSchemaType(element); - - if(this.type == null) { - System.out.println("Broken reference on ModelElement.toOntoUMLSchemaType(element)"); - } - } - - public String getType() { - return type; - } - - public String getId() { - return id; - } -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/ServerRequest.java b/src/main/java/it/unibz/inf/ontouml/vp/model/ServerRequest.java new file mode 100644 index 00000000..d4aef0f8 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/ServerRequest.java @@ -0,0 +1,17 @@ +package it.unibz.inf.ontouml.vp.model; + +public class ServerRequest implements Runnable { + + private boolean doStop = false; + + public synchronized void doStop() { + this.doStop = true; + } + + protected synchronized boolean keepRunning() { + return this.doStop == false; + } + + @Override + public void run() {} +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Association.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Association.java new file mode 100644 index 00000000..c8f21101 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Association.java @@ -0,0 +1,530 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.diagram.IDiagramElement; +import com.vp.plugin.diagram.connector.IAssociationUIModel; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IAssociationEnd; +import com.vp.plugin.model.IClass; +import it.unibz.inf.ontouml.vp.model.AssociationModelDescription; +import it.unibz.inf.ontouml.vp.model.PropertyDescription; +import it.unibz.inf.ontouml.vp.utils.Stereotype; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +/** + * Implementation of ModelElement to handle IAssociation objects to be serialized as + * ontouml-schema/Association + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class Association implements ModelElement { + + private final IAssociation sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description; + + @SerializedName("properties") + @Expose + private List properties; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; + + @SerializedName("stereotypes") + @Expose + private List stereotypes; + + @SerializedName("isAbstract") + @Expose + private boolean isAbstract; + + @SerializedName("isDerived") + @Expose + private boolean isDerived; + + public Association(IAssociation source) { + this.sourceModelElement = source; + + this.type = ModelElement.TYPE_RELATION; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + addProperty(new Property((IAssociationEnd) source.getFromEnd())); + addProperty(new Property((IAssociationEnd) source.getToEnd())); + + String[] stereotypes = source.toStereotypeArray(); + for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { + addStereotype(stereotypes[i]); + } + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + setAbstract(source.isAbstract()); + setDerived(source.isDerived()); + } + + public Association(IAssociation source, HashSet modelElements) { + this.sourceModelElement = source; + + this.type = ModelElement.TYPE_RELATION; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + if (modelElements.contains(source.getFromEnd().getId())) { + addProperty(new Property((IAssociationEnd) source.getFromEnd())); + } + + if (modelElements.contains(source.getToEnd().getId())) { + addProperty(new Property((IAssociationEnd) source.getToEnd())); + } + + String[] stereotypes = source.toStereotypeArray(); + for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { + addStereotype(stereotypes[i]); + } + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + setAbstract(source.isAbstract()); + setDerived(source.isDerived()); + } + + @Override + public String getId() { + return getSourceModelElement().getId(); + } + + @Override + public IAssociation getSourceModelElement() { + return this.sourceModelElement; + } + + @Override + public String getOntoUMLType() { + return this.type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + } + + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } + + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } + + public List getStereotypes() { + return this.stereotypes; + } + + public void setStereotypes(List stereotypes) { + this.stereotypes = stereotypes; + } + + public String getStereotype(int position) { + return this.stereotypes.get(position); + } + + public void addStereotype(String name) { + if (this.stereotypes == null) { + this.stereotypes = new ArrayList(); + } + + this.stereotypes.add(name); + } + + public void removeStereotype(String name) { + + if (this.stereotypes.contains(name)) { + this.stereotypes.remove(name); + } + } + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + public Property getProperty(int position) { + return this.properties.get(position); + } + + public void addProperty(Property property) { + if (this.properties == null) { + this.properties = new ArrayList(); + } + + this.properties.add(property); + } + + public void removeProperty(Property property) { + + if (this.properties.contains(property)) { + this.properties.remove(property); + } + } + + public boolean isAbstract() { + return this.isAbstract; + } + + public void setAbstract(boolean isAbstract) { + this.isAbstract = isAbstract; + } + + public boolean isDerived() { + return this.isDerived; + } + + public void setDerived(boolean isDerived) { + this.isDerived = isDerived; + } + + public static IClass getSource(IAssociation association) { + return (IClass) association.getFrom(); + } + + public static IClass getTarget(IAssociation association) { + return (IClass) association.getTo(); + } + + public static void setSource(IAssociation association, IClass newSource) { + association.setFrom(newSource); + } + + public static void setTarget(IAssociation association, IClass newTarget) { + association.setTo(newTarget); + } + + public static IAssociationEnd getSourceEnd(IAssociation association) { + return (IAssociationEnd) association.getFromEnd(); + } + + public static IAssociationEnd getTargetEnd(IAssociation association) { + return (IAssociationEnd) association.getToEnd(); + } + + public static void invertAssociation( + IAssociation association, boolean keepAllAssociationEndPropertiesInPlace) { + final IClass originalSource = getSource(association); + final IClass originalTarget = getTarget(association); + final IAssociationEnd originalSourceEnd = getSourceEnd(association); + final IAssociationEnd originalTargetEnd = getTargetEnd(association); + final PropertyDescription sourceEndDescription = new PropertyDescription(originalSourceEnd); + final PropertyDescription targetEndDescription = new PropertyDescription(originalTargetEnd); + final List originalAssociationsDecriptions = + retrieveAndDeleteAssociationModels(association); + + setSource(association, originalTarget); + setTarget(association, originalSource); + + if (keepAllAssociationEndPropertiesInPlace) { + sourceEndDescription.copyTo(originalTargetEnd); + targetEndDescription.copyTo(originalSourceEnd); + } else { + sourceEndDescription.partialCopyTo(originalTargetEnd); + targetEndDescription.partialCopyTo(originalSourceEnd); + } + + setNavigability(association); + + for (AssociationModelDescription originalAssociationsDecription : + originalAssociationsDecriptions) { + originalAssociationsDecription.recreateInvertedAssociationModel(); + } + } + + private static List retrieveAndDeleteAssociationModels( + IAssociation association) { + final IDiagramElement[] associationModels = association.getDiagramElements(); + final List associationModelsDecriptions = new ArrayList<>(); + + for (int i = 0; associationModels != null && i < associationModels.length; i++) { + final IAssociationUIModel associationModel = (IAssociationUIModel) associationModels[i]; + final AssociationModelDescription associationModelDescription = + new AssociationModelDescription(associationModel); + + associationModelsDecriptions.add(associationModelDescription); + associationModelDescription.deleteAssociationModel(); + } + + return associationModelsDecriptions; + } + + public static void setNavigability(IAssociation association) { + if (!Association.isOntoumlAssociation(association)) { + return; + } + + final IAssociationEnd sourceEnd = getSourceEnd(association); + final IAssociationEnd targetEnd = getTargetEnd(association); + + sourceEnd.setNavigable(IAssociationEnd.NAVIGABLE_NAV_UNSPECIFIED); + + if (IAssociationEnd.AGGREGATION_KIND_NONE.equals(targetEnd.getAggregationKind())) { + targetEnd.setNavigable(IAssociationEnd.NAVIGABLE_NAV_NAVIGABLE); + } else { + targetEnd.setNavigable(IAssociationEnd.NAVIGABLE_NAV_UNSPECIFIED); + } + } + + public static void setDefaultAggregationKind(IAssociation association, boolean forceOverride) { + final String stereotype = ModelElement.getUniqueStereotypeName(association); + final IAssociationEnd sourceEnd = getSourceEnd(association); + final IAssociationEnd targetEnd = getTargetEnd(association); + String aggregationKind = IAssociationEnd.AGGREGATION_KIND_NONE; + + switch (stereotype) { + case Stereotype.MEMBER_OF: + aggregationKind = IAssociationEnd.AGGREGATION_KIND_SHARED; + break; + case Stereotype.COMPONENT_OF: + case Stereotype.SUB_COLLECTION_OF: + case Stereotype.SUB_QUANTITY_OF: + case Stereotype.PARTICIPATIONAL: + aggregationKind = IAssociationEnd.AGGREGATION_KIND_COMPOSITED; + break; + default: + if (hasValidStereotype(association)) { + // When there is a non-parthood stereotype we must remove any aggregation kind + sourceEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); + targetEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); + } + // We don't interfere where there is not stereotype + return; + } + + if (forceOverride) { + sourceEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); + targetEnd.setAggregationKind(aggregationKind); + } else { + // By not forcing override we keep user-defined aggregation (e.g., "shared") + final String currentAggregationkind = targetEnd.getAggregationKind(); + + if (IAssociationEnd.AGGREGATION_KIND_NONE.equals(currentAggregationkind)) { + sourceEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); + targetEnd.setAggregationKind(aggregationKind); + } + } + } + + public static void setAggregationKind(IAssociation association, String aggregationKind) { + final IAssociationEnd sourceEnd = getSourceEnd(association); + final IAssociationEnd targetEnd = getTargetEnd(association); + + sourceEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); + targetEnd.setAggregationKind(aggregationKind); + } + + public static void setDefaultMultiplicity(IAssociation association, boolean forceOverride) { + final IClass source = getSource(association); + final IClass target = getTarget(association); + final IAssociationEnd sourceEnd = getSourceEnd(association); + final IAssociationEnd targetEnd = getTargetEnd(association); + final String stereotype = ModelElement.getUniqueStereotypeName(association); + final String sourceStereotype = ModelElement.getUniqueStereotypeName(source); + final String targetStereotype = ModelElement.getUniqueStereotypeName(target); + String sourceMultiplicity = IAssociationEnd.MULTIPLICITY_UNSPECIFIED; + String targetMultiplicity = IAssociationEnd.MULTIPLICITY_UNSPECIFIED; + boolean sourceMustBeReadOnly = false; + boolean targetMustBeReadOnly = false; + + switch (stereotype) { + case Stereotype.CHARACTERIZATION: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; // Source: Characterized end + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; // Target: Mode/Quality end + targetMustBeReadOnly = true; + break; + + case Stereotype.COMPARATIVE: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; + break; + + case Stereotype.COMPONENT_OF: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; + break; + + case Stereotype.MATERIAL: + if (Stereotype.ROLE.equals(targetStereotype) + || Stereotype.ROLE_MIXIN.equals(targetStereotype)) { + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + } else { + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; + } + if (Stereotype.ROLE.equals(sourceStereotype) + || Stereotype.ROLE_MIXIN.equals(sourceStereotype)) { + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + } else { + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; + } + break; + + case Stereotype.EXTERNAL_DEPENDENCE: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; // Source: Mode/Quality end + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; // Target: Dependee end + targetMustBeReadOnly = true; + break; + + case Stereotype.MEDIATION: + if (Stereotype.ROLE.equals(targetStereotype) + || Stereotype.ROLE_MIXIN.equals(targetStereotype)) { + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + } else { + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; + } + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; + targetMustBeReadOnly = true; + break; + + case Stereotype.MEMBER_OF: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + break; + + case Stereotype.SUB_COLLECTION_OF: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; + break; + + case Stereotype.SUB_QUANTITY_OF: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; + sourceMustBeReadOnly = true; + break; + + case Stereotype.CREATION: + case Stereotype.TERMINATION: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; // Source: Endurant end + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; // Target: Event end + sourceMustBeReadOnly = true; + targetMustBeReadOnly = true; + break; + + case Stereotype.HISTORICAL_DEPENDENCE: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; // Source: Depender end + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; // Target: Dependee end + targetMustBeReadOnly = true; + break; + + case Stereotype.MANIFESTATION: + // Source: Mode/Quality/Relator end + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; // Target: Event end + sourceMustBeReadOnly = true; + break; + + case Stereotype.PARTICIPATION: + // Source: Endurant end (participant) + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + // Target: Event end + if (Stereotype.HISTORICAL_ROLE.equals(sourceStereotype) + || Stereotype.HISTORICAL_ROLE_MIXIN.equals(sourceStereotype)) { + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + } else { + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; + } + sourceMustBeReadOnly = true; + break; + + case Stereotype.PARTICIPATIONAL: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; + sourceMustBeReadOnly = true; + targetMustBeReadOnly = true; + break; + + case Stereotype.INSTANTIATION: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_MANY; // Source: lower order type + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE_TO_MANY; // Target: higher order type + break; + + case Stereotype.BRINGS_ABOUT: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; // Source: event + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; // Target: situation + sourceMustBeReadOnly = true; + targetMustBeReadOnly = true; + break; + + case Stereotype.TRIGGERS: + sourceMultiplicity = IAssociationEnd.MULTIPLICITY_ONE; // Source: situation + targetMultiplicity = IAssociationEnd.MULTIPLICITY_ZERO_TO_ONE; // Target: event + sourceMustBeReadOnly = true; + break; + + default: + return; + } + + if (forceOverride) { + sourceEnd.setMultiplicity(sourceMultiplicity); + targetEnd.setMultiplicity(targetMultiplicity); + } else { + if (IAssociationEnd.MULTIPLICITY_UNSPECIFIED.equals(sourceEnd.getMultiplicity())) { + sourceEnd.setMultiplicity(sourceMultiplicity); + } + if (IAssociationEnd.MULTIPLICITY_UNSPECIFIED.equals(targetEnd.getMultiplicity())) { + targetEnd.setMultiplicity(targetMultiplicity); + } + } + + if (sourceMustBeReadOnly) { + sourceEnd.setReadOnly(true); + } + + if (targetMustBeReadOnly) { + targetEnd.setReadOnly(true); + } + } + + public static boolean isOntoumlAssociation(IAssociation association) { + return (hasValidStereotype(association) || association.stereotypeCount() == 0) + && Class.hasValidStereotype(Association.getSource(association)) + && Class.hasValidStereotype(Association.getTarget(association)); + } + + public static boolean hasValidStereotype(IAssociation association) { + final String stereotype = ModelElement.getUniqueStereotypeName(association); + return Stereotype.getOntoUMLAssociationStereotypeNames().contains(stereotype); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/AssociationClass.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/AssociationClass.java new file mode 100644 index 00000000..c72f5bab --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/AssociationClass.java @@ -0,0 +1,175 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.model.IAssociationClass; +import it.unibz.inf.ontouml.vp.utils.Stereotype; +import java.util.ArrayList; +import java.util.List; + +/** + * Implementation of ModelElement to handle IAssociationClass objects to be serialized as + * ontouml-schema/Association + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class AssociationClass implements ModelElement { + + private final IAssociationClass sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description; + + @SerializedName("properties") + @Expose + private List properties; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; + + @SerializedName("stereotypes") + @Expose + private List stereotypes; + + @SerializedName("isAbstract") + @Expose + private boolean isAbstract; + + @SerializedName("isDerived") + @Expose + private boolean isDerived; + + public AssociationClass(IAssociationClass source) { + this.sourceModelElement = source; + this.type = ModelElement.TYPE_ASSOCIATION_CLASS; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + Property sourceEnd = new Property(source, source.getFrom()); + Property targetEnd = new Property(source, source.getTo()); + + addStereotype(Stereotype.DERIVATION); + + addProperty(sourceEnd); + addProperty(targetEnd); + } + + @Override + public String getId() { + return getSourceModelElement().getId(); + } + + @Override + public IAssociationClass getSourceModelElement() { + return this.sourceModelElement; + } + + @Override + public String getOntoUMLType() { + return this.type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + } + + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } + + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } + + public List getStereotypes() { + return this.stereotypes; + } + + public void setStereotypes(List stereotypes) { + this.stereotypes = stereotypes; + } + + public String getStereotype(int position) { + return this.stereotypes.get(position); + } + + public void addStereotype(String name) { + if (this.stereotypes == null) this.stereotypes = new ArrayList(); + + this.stereotypes.add(name); + } + + public void removeStereotype(String name) { + + if (this.stereotypes.contains(name)) this.stereotypes.remove(name); + } + + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + public Property getProperty(int position) { + return this.properties.get(position); + } + + public void addProperty(Property property) { + if (this.properties == null) this.properties = new ArrayList(); + + this.properties.add(property); + } + + public void removeProperty(Property property) { + + if (this.properties.contains(property)) this.properties.remove(property); + } + + public boolean isAbstract() { + return this.isAbstract; + } + + public void setAbstract(boolean isAbstract) { + this.isAbstract = isAbstract; + } + + public boolean isDerived() { + return this.isDerived; + } + + public void setDerived(boolean isDerived) { + this.isDerived = isDerived; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Class.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Class.java new file mode 100644 index 00000000..42f86493 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Class.java @@ -0,0 +1,674 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.model.IAttribute; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IDataType; +import com.vp.plugin.model.IEnumerationLiteral; +import com.vp.plugin.model.IGeneralization; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.ISimpleRelationship; +import com.vp.plugin.model.ITaggedValue; +import com.vp.plugin.model.ITaggedValueContainer; +import it.unibz.inf.ontouml.vp.utils.RestrictedTo; +import it.unibz.inf.ontouml.vp.utils.Stereotype; +import it.unibz.inf.ontouml.vp.utils.StereotypesManager; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Implementation of ModelElement to handle IClass and IDataType objects to be serialized as + * ontouml-schema/Class + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class Class implements ModelElement { + + private final IModelElement sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description; + + @SerializedName("properties") + @Expose + private Set properties; + + @SerializedName("literals") + @Expose + private LinkedList literals; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; + + @SerializedName("stereotypes") + @Expose + private List stereotypes; + + @SerializedName("isAbstract") + @Expose + private boolean isAbstract; + + @SerializedName("isDerived") + @Expose + private boolean isDerived; + + @SerializedName("allowed") + @Expose + private JsonArray restrictedTo; + + @SerializedName("isExtensional") + @Expose + private JsonElement isExtensional; + + @SerializedName("isPowertype") + @Expose + private JsonElement isPowertype; + + @SerializedName("order") + @Expose + private String order; + + private Class(IModelElement source) { + this.sourceModelElement = source; + this.type = ModelElement.TYPE_CLASS; + this.id = source.getId(); + this.properties = null; + this.stereotypes = null; + this.literals = null; + } + + public Class(IClass source) { + this((IModelElement) source); + + final IAttribute[] attributes = source.toAttributeArray(); + for (int i = 0; attributes != null && i < attributes.length; i++) { + addProperties(new Property(attributes[i])); + } + + final String[] stereotypes = source.toStereotypeArray(); + for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { + addStereotype(stereotypes[i]); + } + + if (this.stereotypes != null && this.stereotypes.contains(Stereotype.ENUMERATION)) { + IEnumerationLiteral[] literalArray = source.toEnumerationLiteralArray(); + for (int i = 0; literalArray != null && i < literalArray.length; i++) + addLiteral(new Literal(literalArray[i])); + } + + setAbstract(source.isAbstract()); + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + + if (source.getName().trim().startsWith("/")) { + setName(source.getName().substring(1)); + this.isDerived = true; + } else { + setName(source.getName().trim()); + } + + setDescription(source.getDescription()); + + loadTags(source); + } + + public Class(IDataType source) { + this((IModelElement) source); + + addStereotype(Stereotype.DATATYPE); + setAbstract(false); + setDerived(false); + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + + if (source.getName().trim().startsWith("/")) { + setName(source.getName().substring(1)); + this.isDerived = true; + } else { + setName(source.getName().trim()); + } + + // TODO: change this to apply only to default VP datatypes + if (restrictedTo == null) { + restrictedTo = new JsonArray(); + restrictedTo.add("abstract"); + } + } + + public Class(IClass source, HashSet modelElements) { + this((IModelElement) source); + + final IAttribute[] attributes = source.toAttributeArray(); + for (int i = 0; attributes != null && i < attributes.length; i++) { + if (modelElements.contains(attributes[i].getId())) addProperties(new Property(attributes[i])); + } + + final String[] stereotypes = source.toStereotypeArray(); + for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { + addStereotype(stereotypes[i]); + } + + if (this.stereotypes != null && this.stereotypes.contains(Stereotype.ENUMERATION)) { + IEnumerationLiteral[] literalArray = source.toEnumerationLiteralArray(); + for (int i = 0; literalArray != null && i < literalArray.length; i++) + addLiteral(new Literal(literalArray[i])); + } + + setAbstract(source.isAbstract()); + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + + if (source.getName().trim().startsWith("/")) { + setName(source.getName().substring(1)); + this.isDerived = true; + } else { + setName(source.getName().trim()); + } + + setDescription(source.getDescription()); + + loadTags(source); + } + + private void loadTags(IClass source) { + if (source.getTaggedValues() != null) { + final JsonParser parser = new JsonParser(); + + if (hasRestrictedTo(source)) { + String restrictedTo = getRestrictedTo(source); + + if (restrictedTo == null) { + this.restrictedTo = null; + } else { + restrictedTo = restrictedTo.trim().replaceAll(" +", ",").replaceAll(",", "\",\""); + + final JsonElement restrictedToArray = + !restrictedTo.equals("") + ? parser.parse("[\"" + restrictedTo + "\"]") + : parser.parse("[]"); + this.restrictedTo = + restrictedToArray.isJsonArray() && ((JsonArray) restrictedToArray).size() > 0 + ? (JsonArray) restrictedToArray + : null; + } + } + + if (hasIsExtensional(source)) { + this.isExtensional = parser.parse("" + isExtensional(source)); + } else { + this.isExtensional = parser.parse("null"); + } + + if (hasIsPowertype(source)) { + this.isPowertype = parser.parse("" + isPowertype(source)); + } else { + this.isPowertype = parser.parse("null"); + } + + if (hasOrder(source)) { + this.order = getOrder(source); + } + } + } + + @Override + public IModelElement getSourceModelElement() { + return this.sourceModelElement; + } + + @Override + public String getId() { + return getSourceModelElement().getId(); + } + + @Override + public String getOntoUMLType() { + return this.type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } + + public Set getProperties() { + return properties; + } + + public void addProperties(Property property) { + if (this.properties == null) this.properties = new HashSet(); + + this.properties.add(property); + } + + public void removeProperties(Property property) { + if (this.properties != null && this.properties.contains(property)) + this.properties.remove(property); + } + + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } + + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } + + public List getStereotypes() { + return this.stereotypes; + } + + public void setStereotypes(List stereotypes) { + this.stereotypes = stereotypes; + } + + public String getStereotype(int position) { + return this.stereotypes.get(position); + } + + public void addStereotype(String name) { + if (this.stereotypes == null) this.stereotypes = new ArrayList(); + + this.stereotypes.add(name); + } + + public void removeStereotype(String name) { + if (this.stereotypes != null && this.stereotypes.contains(name)) this.stereotypes.remove(name); + } + + public boolean isAbstract() { + return this.isAbstract; + } + + public void setAbstract(boolean isAbstract) { + this.isAbstract = isAbstract; + } + + public boolean isDerived() { + return this.isDerived; + } + + public void setDerived(boolean isDerived) { + this.isDerived = isDerived; + } + + public LinkedList getLiterals() { + return literals; + } + + public void setLiterals(LinkedList literals) { + this.literals = literals; + } + + public void addLiteral(Literal literal) { + if (getLiterals() == null) { + setLiterals(new LinkedList()); + } + + this.literals.add(literal); + } + + public static Set getParents(IClass _class) { + final Set parents = new HashSet(); + final ISimpleRelationship[] relationships = _class.toToRelationshipArray(); + + for (int i = 0; relationships != null && i < relationships.length; i++) { + if (relationships[i] instanceof IGeneralization) { + final IGeneralization generalization = (IGeneralization) relationships[i]; + final IModelElement parent = Generalization.getGeneral(generalization); + + if (parent instanceof IClass) { + parents.add((IClass) parent); + } + } + } + + return parents; + } + + public static Set getChildren(IClass _class) { + final Set children = new HashSet(); + final ISimpleRelationship[] relationships = _class.toFromRelationshipArray(); + + for (int i = 0; relationships != null && i < relationships.length; i++) { + if (relationships[i] instanceof IGeneralization) { + final IGeneralization generalization = (IGeneralization) relationships[i]; + final IModelElement child = Generalization.getSpecific(generalization); + + if (child instanceof IClass) { + children.add((IClass) child); + } + } + } + + return children; + } + + public static Set getAncestors(IClass _class) { + final Set ancestors = new HashSet(); + final Set parents = getChildren(_class); + + for (IClass parent : parents) { + ancestors.addAll(getDescendants(parent)); + ancestors.add(parent); + } + + return ancestors; + } + + public static Set getDescendants(IClass _class) { + final Set descendants = new HashSet(); + final Set children = getChildren(_class); + + for (IClass child : children) { + descendants.addAll(getDescendants(child)); + descendants.add(child); + } + + return descendants; + } + + public static void applyOnChildren(IClass _class, Consumer function) { + final Set children = getChildren(_class); + + for (IClass child : children) { + function.accept(child); + } + } + + public static void applyOnParents(IClass _class, Consumer function) { + final Set parents = getParents(_class); + + for (IClass parent : parents) { + function.accept(parent); + } + } + + public static void applyOnDescendants(IClass _class, Function function) { + final Set children = getChildren(_class); + + for (IClass child : children) { + final boolean shouldContinue = function.apply(child); + if (shouldContinue) { + applyOnDescendants(child, function); + } + } + } + + public static void applyOnAncestors(IClass _class, Function function) { + final Set parents = getParents(_class); + + for (IClass parent : parents) { + final boolean shouldContinue = function.apply(parent); + if (shouldContinue) { + applyOnAncestors(parent, function); + } + } + } + + public static void setRestrictedTo(IClass _class, String restrictions) { + if (_class.getTaggedValues() == null) { + return; + } + + System.out.println("WILL TRY TO SET VALUE: " + restrictions); + + Iterator values = _class.getTaggedValues().taggedValueIterator(); + + while (values != null && values.hasNext()) { + final ITaggedValue value = (ITaggedValue) values.next(); + + if (value.getName().equals(StereotypesManager.PROPERTY_RESTRICTED_TO)) { + final String notNull = restrictions != null ? restrictions : ""; + final List sortList = Arrays.asList(notNull.split("\\s+")); + Collections.sort(sortList); + final Set noDuplicates = new LinkedHashSet<>(sortList); + final String newRestrictions = noDuplicates.toString().replaceAll("[\\[\\],]", "").trim(); + final String currentRestrictions = + value.getValueAsString() != null ? value.getValueAsString() : ""; + + if (!currentRestrictions.equals(newRestrictions)) { + value.setValue(newRestrictions); + } + + System.out.println("NEW VALUE: " + value.getValueAsText()); + + return; + } + } + } + + private static void setDefaultRestrictedTo(IClass element, String stereotypeName) { + String currentRestrictedTo = getRestrictedTo(element); + + if (RestrictedTo.shouldOverrideRestrictedTo(stereotypeName, currentRestrictedTo)) { + final String defaultNature = RestrictedTo.getDefaultRestrictedTo(stereotypeName); + setRestrictedTo(element, defaultNature); + } + } + + public static void setDefaultRestrictedTo(IClass _class) { + setDefaultRestrictedTo(_class, ModelElement.getUniqueStereotypeName(_class)); + } + + public static String getRestrictedTo(IClass _class) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue restrictedTo = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_RESTRICTED_TO) + : null; + + return restrictedTo != null ? restrictedTo.getValueAsString() : null; + } + + public static String getRestrictedTo(Set classes) { + String classesRestrictions = ""; + + for (IClass _class : classes) { + final String _classRestrictions = getRestrictedTo(_class); + if (_classRestrictions != null) { + classesRestrictions += " " + _classRestrictions; + } + } + + classesRestrictions = + Arrays.stream(classesRestrictions.split("\\s+")) + .distinct() + .collect(Collectors.joining(" ")); + + return !classesRestrictions.equals("") ? classesRestrictions : null; + } + + public static List getRestrictedToList(String restrictedTo) { + if (restrictedTo == null || restrictedTo.equals("")) return Collections.emptyList(); + + return Arrays.asList(restrictedTo.split("\\s+")); + } + + public static List getRestrictedToList(IClass _class) { + return getRestrictedToList(getRestrictedTo(_class)); + } + + public static boolean hasRestrictedTo(IClass _class) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue restrictedTo = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_RESTRICTED_TO) + : null; + + return restrictedTo != null; + } + + public static String getOrder(IClass _class) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue order = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_ORDER) + : null; + + return order != null ? order.getValueAsString() : null; + } + + public static Optional getOrderOr(IClass _class) { + return Optional.ofNullable(getOrder(_class)); + } + + public static void setOrder(IClass _class, String newOrder) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue order = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_ORDER) + : null; + + if (order != null) { + order.setValue(newOrder); + } + } + + public static boolean hasOrder(IClass _class) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue order = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_ORDER) + : null; + + return order != null; + } + + public static boolean isPowertype(IClass _class) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue isPowertype = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_IS_POWERTYPE) + : null; + final String isPowertypeValue = isPowertype != null ? isPowertype.getValueAsString() : ""; + + return Boolean.parseBoolean(isPowertypeValue); + } + + public static void setIsPowertype(IClass _class, boolean isPowertypeValue) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue isPowertype = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_IS_POWERTYPE) + : null; + + if (isPowertype != null) { + isPowertype.setValue(isPowertypeValue); + } + } + + public static boolean hasIsPowertype(IClass _class) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue isPowertype = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_IS_POWERTYPE) + : null; + + return isPowertype != null; + } + + public static boolean isExtensional(IClass _class) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue isExtensional = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_IS_EXTENSIONAL) + : null; + final String isExtensionalValue = isExtensional != null ? isExtensional.getValueAsString() : ""; + + return Boolean.parseBoolean(isExtensionalValue); + } + + public static void setIsExtensional(IClass _class, boolean isExtensionalValue) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue isExtensional = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_IS_EXTENSIONAL) + : null; + + if (isExtensional != null) { + isExtensional.setValue(isExtensionalValue); + } + } + + public static boolean hasIsExtensional(IClass _class) { + final ITaggedValueContainer container = _class.getTaggedValues(); + final ITaggedValue isExtensional = + container != null + ? container.getTaggedValueByName(StereotypesManager.PROPERTY_IS_EXTENSIONAL) + : null; + + return isExtensional != null; + } + + public static boolean hasValidStereotype(IClass _class) { + final String stereotype = ModelElement.getUniqueStereotypeName(_class); + return Stereotype.getOntoUMLClassStereotypeNames().contains(stereotype); + } + + public static boolean isRestrictedToEditable(IClass _class) { + final String stereotype = ModelElement.getUniqueStereotypeName(_class); + return RestrictedTo.isRestrictedToEditable(stereotype); + } + + public static boolean isAbstractEditable(IClass _class) { + final String stereotype = ModelElement.getUniqueStereotypeName(_class); + return stereotype == null || !Stereotype.isNonSortal(stereotype); + } + + public static boolean isCollective(IClass _class) { + final String stereotype = ModelElement.getUniqueStereotypeName(_class); + return Stereotype.COLLECTIVE.equals(stereotype); + } + + public static boolean isType(IClass _class) { + final String stereotype = ModelElement.getUniqueStereotypeName(_class); + return Stereotype.TYPE.equals(stereotype); + } + + public static boolean hasCollectiveNature(IClass _class) { + return RestrictedTo.COLLECTIVE.equals(getRestrictedTo(_class)); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Generalization.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Generalization.java new file mode 100644 index 00000000..22954d0e --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Generalization.java @@ -0,0 +1,126 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.model.IGeneralization; +import com.vp.plugin.model.IModelElement; + +/** + * Implementation of ModelElement to handle IGeneralization objects to be serialized as + * ontouml-schema/Generalization + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class Generalization implements ModelElement { + + private final IGeneralization sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; + + @SerializedName("general") + @Expose + private Reference general; + + @SerializedName("specific") + @Expose + private Reference specific; + + public Generalization(IGeneralization source) { + this.sourceModelElement = source; + + this.type = ModelElement.TYPE_GENERALIZATION; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + setGeneral(new Reference(source.getFrom())); + setSpecific(new Reference(source.getTo())); + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } + + @Override + public String getId() { + return getSourceModelElement() != null ? getSourceModelElement().getId() : null; + } + + @Override + public IGeneralization getSourceModelElement() { + return this.sourceModelElement; + } + + @Override + public String getOntoUMLType() { + return this.type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } + + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } + + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } + + public Reference getGeneral() { + return general; + } + + public void setGeneral(Reference general) { + this.general = general; + } + + public Reference getSpecific() { + return specific; + } + + public void setSpecific(Reference specific) { + this.specific = specific; + } + + public static IModelElement getGeneral(IGeneralization generalization) { + return generalization.getFrom(); + } + + public static IModelElement getSpecific(IGeneralization generalization) { + return generalization.getTo(); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/GeneralizationSet.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/GeneralizationSet.java new file mode 100644 index 00000000..06fdd2d2 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/GeneralizationSet.java @@ -0,0 +1,183 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.model.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +/** + * Implementation of ModelElement to handle IGeneralizationSet objects to be serialized as + * ontouml-schema/GeneralizationSet + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class GeneralizationSet implements ModelElement { + + private final IGeneralizationSet sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; + + @SerializedName("categorizer") + @Expose + private Reference categorizer; + + @SerializedName("generalizations") + @Expose + private List generalizations; + + @SerializedName("isDisjoint") + @Expose + private boolean isDisjoint; + + @SerializedName("isComplete") + @Expose + private boolean isComplete; + + public GeneralizationSet(IGeneralizationSet source) { + this.sourceModelElement = source; + + this.type = ModelElement.TYPE_GENERALIZATION_SET; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + setComplete(source.isCovering()); + setDisjoint(source.isDisjoint()); + + if (source.getPowerType() != null) setCategorizer(new Reference(source.getPowerType())); + + final IGeneralization[] generalizations = source.toGeneralizationArray(); + for (int i = 0; generalizations != null && i < generalizations.length; i++) + addGeneralization(new Reference(generalizations[i])); + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } + + public GeneralizationSet(IGeneralizationSet source, HashSet idElements) { + this.sourceModelElement = source; + + this.type = ModelElement.TYPE_GENERALIZATION_SET; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + setComplete(source.isCovering()); + setDisjoint(source.isDisjoint()); + + if (source.getPowerType() != null) setCategorizer(new Reference(source.getPowerType())); + + final IGeneralization[] generalizations = source.toGeneralizationArray(); + for (int i = 0; generalizations != null && i < generalizations.length; i++) { + if (idElements.contains(generalizations[i].getId())) + addGeneralization(new Reference(generalizations[i])); + } + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } + + @Override + public String getId() { + return getSourceModelElement().getId(); + } + + @Override + public IModelElement getSourceModelElement() { + return this.sourceModelElement; + } + + @Override + public String getOntoUMLType() { + return type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } + + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } + + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } + + public boolean isDisjoint() { + return isDisjoint; + } + + public void setDisjoint(boolean isDisjoint) { + this.isDisjoint = isDisjoint; + } + + public boolean isComplete() { + return isComplete; + } + + public void setComplete(boolean isComplete) { + this.isComplete = isComplete; + } + + public Reference getCategorizer() { + return this.categorizer; + } + + public void setCategorizer(Reference categorizer) { + this.categorizer = categorizer; + } + + public List getGeneralizations() { + return generalizations; + } + + public void setGeneralizations(List generalizations) { + this.generalizations = generalizations; + } + + public void addGeneralization(Reference ref) { + if (this.generalizations == null) this.generalizations = new ArrayList(); + + this.generalizations.add(ref); + } + + public void removeGeneralization(Reference ref) { + if (this.generalizations != null && this.generalizations.contains(ref)) + this.generalizations.remove(ref); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Literal.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Literal.java new file mode 100644 index 00000000..649901b2 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Literal.java @@ -0,0 +1,80 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.model.IEnumerationLiteral; + +public class Literal implements ModelElement { + + private final IEnumerationLiteral sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; + + public Literal(IEnumerationLiteral source) { + this.sourceModelElement = source; + this.type = ModelElement.TYPE_LITERAL; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } + + @Override + public IEnumerationLiteral getSourceModelElement() { + return this.sourceModelElement; + } + + @Override + public String getId() { + return getSourceModelElement().getId(); + } + + @Override + public String getOntoUMLType() { + return this.type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } + + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } + + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Model.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Model.java new file mode 100644 index 00000000..fb0cf77c --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Model.java @@ -0,0 +1,361 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IAssociationClass; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IDataType; +import com.vp.plugin.model.IGeneralization; +import com.vp.plugin.model.IGeneralizationSet; +import com.vp.plugin.model.IModel; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.IPackage; +import com.vp.plugin.model.IProject; +import com.vp.plugin.model.factory.IModelElementFactory; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; + +/** + * Implementation of ModelElement to handle IModel objects to be serialized as + * ontouml-schema/Package + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class Model implements ModelElement { + + private final IModel sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description = null; + + @SerializedName("contents") + @Expose + private List contents; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments = null; + + /** + * Constructs a model to contain all project's model elements independent of a IModelElement + * . + */ + public Model() { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + final String[] rootLevelElements = { + IModelElementFactory.MODEL_TYPE_PACKAGE, + IModelElementFactory.MODEL_TYPE_MODEL, + IModelElementFactory.MODEL_TYPE_CLASS, + IModelElementFactory.MODEL_TYPE_DATA_TYPE + }; + final String[] anyLevelElements = { + IModelElementFactory.MODEL_TYPE_GENERALIZATION, + IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET, + IModelElementFactory.MODEL_TYPE_ASSOCIATION, + IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS + }; + + this.sourceModelElement = null; + this.type = ModelElement.TYPE_PACKAGE; + this.id = project.getId(); + this.setName(project.getName()); + this.addModelElements(project.toModelElementArray(rootLevelElements)); + this.addModelElements(project.toAllLevelModelElementArray(anyLevelElements)); + } + + /** Constructs a model based on the model elements defined by the user */ + public Model(HashSet idElements) { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + final String[] rootLevelElements = { + IModelElementFactory.MODEL_TYPE_PACKAGE, + IModelElementFactory.MODEL_TYPE_MODEL, + IModelElementFactory.MODEL_TYPE_CLASS, + IModelElementFactory.MODEL_TYPE_DATA_TYPE + }; + final String[] anyLevelElements = { + IModelElementFactory.MODEL_TYPE_GENERALIZATION, + IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET, + IModelElementFactory.MODEL_TYPE_ASSOCIATION, + IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS + }; + + this.sourceModelElement = null; + this.type = ModelElement.TYPE_PACKAGE; + this.id = project.getId(); + this.setName(project.getName()); + + if (idElements == null) return; + + if (containsDiagramModel(idElements)) { + HashSet modelElements = new HashSet(); + + Iterator ite = idElements.iterator(); + // add only valid elements + while (ite.hasNext()) { + String id = ite.next(); + + if (project.getModelElementById(id) == null) continue; + else modelElements.add(project.getModelElementById(id)); + } + + IModelElement[] elementsArray = new IModelElement[modelElements.size()]; + modelElements.toArray(elementsArray); + + addModelElements(elementsArray, idElements); + } else { + addModelElements(project.toModelElementArray(rootLevelElements), idElements); + addModelElements(project.toAllLevelModelElementArray(anyLevelElements), idElements); + } + } + + /** + * Constructs a model based on a IModelElement and which is serialized as a Package + * in OntoUML Schema. + */ + public Model(IModel source) { + this.sourceModelElement = source; + this.type = ModelElement.TYPE_PACKAGE; + this.id = source.getId(); + this.setName(source.getName()); + this.addModelElements(source.toChildArray()); + } + + public Model(IModel source, HashSet idElements) { + this.sourceModelElement = source; + this.type = ModelElement.TYPE_PACKAGE; + this.id = source.getId(); + this.setName(source.getName()); + + IModelElement[] childArray = source.toChildArray(); + + if (childArray == null) return; + + for (int i = 0; i < childArray.length; i++) { + if (idElements.contains(childArray[i].getId())) { + this.addModelElement(childArray[i], idElements); + } + } + } + + @Override + public String getId() { + return getSourceModelElement() != null ? getSourceModelElement().getId() : null; + } + + @Override + public IModel getSourceModelElement() { + return this.sourceModelElement; + } + + public String getOntoUMLType() { + return type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + } + + public List getElements() { + return contents; + } + + public void setElements(List elementsList) { + this.contents = elementsList; + } + + public void addElement(ModelElement element) { + if (this.contents == null) this.contents = new ArrayList(); + + this.contents.add(element); + } + + public boolean removeElement(ModelElement element) { + return this.contents.remove(element); + } + + private void addModelElement(IModelElement projectElement, HashSet idElements) { + + switch (projectElement.getModelType()) { + case IModelElementFactory.MODEL_TYPE_PACKAGE: + addElement(new Package((IPackage) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_MODEL: + addElement(new Model((IModel) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_CLASS: + addElement(new Class((IClass) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_DATA_TYPE: + addElement(new Class((IDataType) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_GENERALIZATION: + IGeneralization gen = (IGeneralization) projectElement; + IModelElement fromElement = gen.getFrom(); + + if (fromElement == null) break; + + String fromType = fromElement.getModelType(); + + if (fromType == null) break; + + boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + + if (!isFromClass && !isFromAssociation) break; + + IModelElement toElement = gen.getTo(); + + if (toElement == null) break; + + String toType = toElement.getModelType(); + + if (toType == null) break; + + boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + + if (!isToClass && !isToAssociation) break; + + addElement(new Generalization((IGeneralization) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + addElement(new Association((IAssociation) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: + addElement(new GeneralizationSet((IGeneralizationSet) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: + addElement(new AssociationClass((IAssociationClass) projectElement)); + } + } + + private void addModelElements(IModelElement[] modelElements, HashSet idElements) { + for (int i = 0; modelElements != null && i < modelElements.length; i++) { + final IModelElement projectElement = modelElements[i]; + + if (!idElements.contains(projectElement.getId())) continue; + + addModelElement(projectElement, idElements); + } + } + + private void addModelElements(IModelElement[] modelElements) { + for (int i = 0; modelElements != null && i < modelElements.length; i++) { + final IModelElement projectElement = modelElements[i]; + + switch (projectElement.getModelType()) { + case IModelElementFactory.MODEL_TYPE_PACKAGE: + addElement(new Package((IPackage) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_MODEL: + addElement(new Model((IModel) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_CLASS: + addElement(new Class((IClass) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_DATA_TYPE: + addElement(new Class((IDataType) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_GENERALIZATION: + IGeneralization gen = (IGeneralization) projectElement; + IModelElement fromElement = gen.getFrom(); + + if (fromElement == null) break; + + String fromType = fromElement.getModelType(); + + if (fromType == null) break; + + boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + + if (!isFromClass && !isFromAssociation) break; + + IModelElement toElement = gen.getTo(); + + if (toElement == null) break; + + String toType = toElement.getModelType(); + + if (toType == null) break; + + boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + + if (!isToClass && !isToAssociation) break; + + addElement(new Generalization((IGeneralization) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + addElement(new Association((IAssociation) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: + addElement(new GeneralizationSet((IGeneralizationSet) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: + addElement(new AssociationClass((IAssociationClass) projectElement)); + } + } + } + + private static boolean containsDiagramModel(HashSet idElements) { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + + Iterator ite = idElements.iterator(); + + while (ite.hasNext()) { + String id = ite.next(); + + if (project.getDiagramById(id) == null) continue; + else return true; + } + + return false; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/ModelElement.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/ModelElement.java new file mode 100644 index 00000000..2f94735a --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/ModelElement.java @@ -0,0 +1,426 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.DiagramManager; +import com.vp.plugin.diagram.IDiagramElement; +import com.vp.plugin.diagram.IDiagramUIModel; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IAssociationEnd; +import com.vp.plugin.model.IAttribute; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.IMultiplicity; +import com.vp.plugin.model.IStereotype; +import com.vp.plugin.model.ITaggedValue; +import com.vp.plugin.model.ITaggedValueContainer; +import com.vp.plugin.model.factory.IModelElementFactory; +import it.unibz.inf.ontouml.vp.utils.StereotypesManager; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.function.Consumer; + +/** + * @author Victor Viola + * @author Claudenir Fonseca + */ +public interface ModelElement { + + public static final String TYPE_PACKAGE = "Package"; + public static final String TYPE_CLASS = "Class"; + public static final String TYPE_RELATION = "Relation"; + public static final String TYPE_ASSOCIATION_CLASS = "Relation"; + public static final String TYPE_GENERALIZATION = "Generalization"; + public static final String TYPE_GENERALIZATION_SET = "GeneralizationSet"; + public static final String TYPE_PROPERTY = "Property"; + public static final String TYPE_LITERAL = "Literal"; + + static String getUniqueStereotypeName(IModelElement element) { + return element.stereotypeCount() == 1 ? element.toStereotypeModelArray()[0].getName() : null; + } + + static IStereotype getUniqueStereotype(IModelElement element) { + return element.stereotypeCount() == 1 ? element.toStereotypeModelArray()[0] : null; + } + + static boolean hasUniqueStereotype(IModelElement element) { + return getUniqueStereotype(element) != null; + } + + /** @return IModelElement on which the object is based. */ + public IModelElement getSourceModelElement(); + + /** @return object's type in OntoUML Schema. */ + public String getOntoUMLType(); + + /** @return object's ID (based on a IModelElement). */ + public String getId(); + + /** + * Returns Visual Paradigm's link to the related model element. This method removes the project's + * name which originally start the link returned. + * + * @param modelElement + * @return a link identify a IModelElement in Visual Paradigm following the pattern + * "vpp://modelelement/Cd.WKPaAUB22rwx4". + */ + public static String getModelElementURI(IModelElement modelElement) { + if (modelElement == null) return null; + + final String link = + ApplicationManager.instance().getProjectManager().getLink(modelElement, false); + + return link.substring(link.indexOf(".vpp:") + 1); + } + + /** + * Returns serialized JSON string of the whole project in OntoUML Schema. + * + * @param pretty - true if return string should be indented. + * @return serialized version JSON of whole project in OntoUML Schema. + */ + public static String generateModel(boolean pretty) { + final Model model = new Model(); + + if (pretty) { + return new GsonBuilder() + .excludeFieldsWithoutExposeAnnotation() + .serializeNulls() + .setPrettyPrinting() + .create() + .toJson(model); + } else { + return new GsonBuilder() + .excludeFieldsWithoutExposeAnnotation() + .serializeNulls() + .create() + .toJson(model); + } + } + + public static String generateModel(HashSet elements, boolean pretty) { + + final Model model = new Model(elements); + if (pretty) { + return new GsonBuilder() + .excludeFieldsWithoutExposeAnnotation() + .serializeNulls() + .setPrettyPrinting() + .create() + .toJson(model); + } else { + return new GsonBuilder() + .excludeFieldsWithoutExposeAnnotation() + .serializeNulls() + .create() + .toJson(model); + } + } + + public static String safeGetString(String s) { + if (s != null && s.length() != 0) return s; + return null; + } + + public static String toOntoUMLSchemaType(IModelElement element) { + switch (element.getModelType()) { + case IModelElementFactory.MODEL_TYPE_MODEL: + case IModelElementFactory.MODEL_TYPE_PACKAGE: + return TYPE_PACKAGE; + case IModelElementFactory.MODEL_TYPE_CLASS: + case IModelElementFactory.MODEL_TYPE_DATA_TYPE: + return TYPE_CLASS; + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: + return TYPE_RELATION; + case IModelElementFactory.MODEL_TYPE_GENERALIZATION: + return TYPE_GENERALIZATION; + case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: + return TYPE_GENERALIZATION_SET; + case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_END: + return TYPE_PROPERTY; + case IModelElementFactory.MODEL_TYPE_ENUMERATION_LITERAL: + return TYPE_LITERAL; + } + + return null; + } + + public static JsonObject transformPropertyAssignments(IModelElement sourceElement) { + ITaggedValueContainer lContainer = sourceElement.getTaggedValues(); + if (lContainer == null) return null; + + JsonObject obj = new JsonObject(); + ITaggedValue[] lTaggedValues = lContainer.toTaggedValueArray(); + List ignoredClassValues = + Arrays.asList( + new String[] { + StereotypesManager.PROPERTY_RESTRICTED_TO, StereotypesManager.PROPERTY_IS_EXTENSIONAL, + StereotypesManager.PROPERTY_IS_POWERTYPE, StereotypesManager.PROPERTY_ORDER + }); + + for (int i = 0; lTaggedValues != null && i < lTaggedValues.length; i++) { + if (ignoredClassValues.contains(lTaggedValues[i].getName())) { + continue; + } + + switch (lTaggedValues[i].getType()) { + case 1: + JsonObject referenceTag = new JsonObject(); + + if (lTaggedValues[i].getValueAsElement() != null) { + referenceTag.addProperty( + "type", ModelElement.toOntoUMLSchemaType(lTaggedValues[i].getValueAsElement())); + referenceTag.addProperty("id", lTaggedValues[i].getValueAsElement().getId()); + } else { + referenceTag = null; + } + obj.add(lTaggedValues[i].getName(), referenceTag); + break; + case 5: + obj.addProperty( + lTaggedValues[i].getName(), Integer.parseInt((String) lTaggedValues[i].getValue())); + break; + case 6: + obj.addProperty( + lTaggedValues[i].getName(), Float.parseFloat((String) lTaggedValues[i].getValue())); + break; + case 7: + obj.addProperty( + lTaggedValues[i].getName(), + Boolean.parseBoolean((String) lTaggedValues[i].getValue())); + break; + default: + obj.addProperty(lTaggedValues[i].getName(), (String) lTaggedValues[i].getValueAsString()); + } + } + + if (obj.size() == 0) return null; + + return obj; + } + + public static boolean isAbstract(IModelElement element) { + final String elementType = element.getModelType(); + + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + return ((IAssociation) element).isAbstract(); + + case IModelElementFactory.MODEL_TYPE_CLASS: + return ((IClass) element).isAbstract(); + + default: + throw new UnsupportedOperationException( + "This operation is not supported for elements of type " + elementType); + } + } + + public static void setAbstract(IModelElement element, boolean isAbstract) { + final String elementType = element.getModelType(); + + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + ((IAssociation) element).setAbstract(isAbstract); + break; + + case IModelElementFactory.MODEL_TYPE_CLASS: + ((IClass) element).setAbstract(isAbstract); + break; + + default: + throw new UnsupportedOperationException( + "This operation is not supported for elements of type " + elementType); + } + } + + public static boolean isDerived(IModelElement element) { + final String elementType = element.getModelType(); + + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + return ((IAssociation) element).isDerived(); + + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_END: + return ((IAssociationEnd) element).isDerived(); + + case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: + return ((IAttribute) element).isDerived(); + + case IModelElementFactory.MODEL_TYPE_CLASS: + return element.getName().trim().startsWith("/"); + + default: + throw new UnsupportedOperationException( + "This operation is not supported for elements of type " + elementType); + } + } + + public static void setDerived(IModelElement element, boolean isDerived) { + final String elementType = element.getModelType(); + + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + ((IAssociation) element).setDerived(isDerived); + break; + + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_END: + ((IAssociationEnd) element).setDerived(isDerived); + break; + + case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: + ((IAttribute) element).setDerived(isDerived); + break; + + case IModelElementFactory.MODEL_TYPE_CLASS: + { + final String currentName = element.getName() != null ? element.getName().trim() : ""; + + if (isDerived(element)) { + element.setName(currentName.substring(1)); + } else { + element.setName("/" + currentName); + } + break; + } + + default: + throw new UnsupportedOperationException( + "This operation is not supported for elements of type " + elementType); + } + } + + public static boolean isOrdered(IModelElement element) { + final String elementType = element.getModelType(); + + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_END: + { + final IAssociationEnd associationEnd = (IAssociationEnd) element; + final IMultiplicity multiplicity = associationEnd.getMultiplicityDetail(); + return multiplicity != null ? multiplicity.isOrdered() : false; + } + + case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: + { + final IAttribute attribute = (IAttribute) element; + final IMultiplicity multiplicity = attribute.getMultiplicityDetail(); + return multiplicity != null ? multiplicity.isOrdered() : false; + } + + default: + throw new UnsupportedOperationException( + "This operation is not supported for elements of type " + elementType); + } + } + + public static void setOrdered(IModelElement element, boolean isOrdered) { + final String elementType = element.getModelType(); + IMultiplicity multiplicity = null; + + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_END: + { + final IAssociationEnd associationEnd = (IAssociationEnd) element; + multiplicity = associationEnd.getMultiplicityDetail(); + + if (multiplicity == null) { + multiplicity = IModelElementFactory.instance().createMultiplicity(); + associationEnd.setMultiplicityDetail(multiplicity); + } + break; + } + + case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: + { + final IAttribute attribute = (IAttribute) element; + multiplicity = attribute.getMultiplicityDetail(); + + if (multiplicity == null) { + multiplicity = IModelElementFactory.instance().createMultiplicity(); + attribute.setMultiplicityDetail(multiplicity); + } + break; + } + + default: + throw new UnsupportedOperationException( + "This operation is not supported for elements of type " + elementType); + } + + multiplicity.setOrdered(isOrdered); + } + + public static boolean isReadOnly(IModelElement element) { + final String elementType = element.getModelType(); + + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_END: + { + return ((IAssociationEnd) element).isReadOnly(); + } + + case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: + { + return ((IAttribute) element).isReadOnly(); + } + + default: + throw new UnsupportedOperationException( + "This operation is not supported for elements of type " + elementType); + } + } + + public static void setReadOnly(IModelElement element, boolean isReadOnly) { + final String elementType = element.getModelType(); + + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_END: + { + ((IAssociationEnd) element).setReadOnly(isReadOnly); + break; + } + + case IModelElementFactory.MODEL_TYPE_ATTRIBUTE: + { + ((IAttribute) element).setReadOnly(isReadOnly); + break; + } + + default: + throw new UnsupportedOperationException( + "This operation is not supported for elements of type " + elementType); + } + } + + @SuppressWarnings("unchecked") + public static void forEachSelectedElement( + T element, Consumer consumer) { + if (element == null) { + return; + } + + final String selectedElementType = element.getModelType(); + final DiagramManager dm = ApplicationManager.instance().getDiagramManager(); + final IDiagramUIModel diagram = dm.getActiveDiagram(); + final IDiagramElement[] selectedDiagramElements = + diagram != null ? diagram.getSelectedDiagramElement() : null; + + if (diagram == null || selectedDiagramElements == null) { + consumer.accept(element); + return; + } + + Arrays.stream(selectedDiagramElements) + .map(selectedDiagramElement -> selectedDiagramElement.getModelElement()) + .filter( + selectedElement -> + selectedElement != null + && selectedElementType.equals(selectedElement.getModelType())) + .forEach((Consumer) consumer); + ; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Package.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Package.java new file mode 100644 index 00000000..e1b1fb04 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Package.java @@ -0,0 +1,212 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.model.*; +import com.vp.plugin.model.factory.IModelElementFactory; +import java.util.HashSet; +import java.util.LinkedList; + +/** + * Implementation of ModelElement to handle IPackage objects to be serialized as + * ontouml-schema/Package + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class Package implements ModelElement { + + private final IPackage sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; + + @SerializedName("contents") + @Expose + private LinkedList contents; + + public Package(IPackage source) { + this.sourceModelElement = source; + this.type = ModelElement.TYPE_PACKAGE; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + final IModelElement[] children = source.toChildArray(); + for (int i = 0; children != null && i < children.length; i++) { + final IModelElement child = children[i]; + + switch (child.getModelType()) { + case IModelElementFactory.MODEL_TYPE_PACKAGE: + addElement(new Package((IPackage) child)); + break; + case IModelElementFactory.MODEL_TYPE_MODEL: + addElement(new Model((IModel) child)); + break; + case IModelElementFactory.MODEL_TYPE_CLASS: + addElement(new Class((IClass) child)); + break; + } + } + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } + + public Package(IPackage source, HashSet idElements) { + this.sourceModelElement = source; + this.type = ModelElement.TYPE_PACKAGE; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + IModelElement[] childArray = source.toChildArray(); + + if (childArray == null) return; + + for (int i = 0; i < childArray.length; i++) { + if (idElements.contains(childArray[i].getId())) { + addModelElement(childArray[i], idElements); + } + } + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } + + @Override + public IPackage getSourceModelElement() { + return sourceModelElement; + } + + @Override + public String getId() { + return getSourceModelElement().getId(); + } + + @Override + public String getOntoUMLType() { + return this.type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } + + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } + + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } + + public LinkedList getContents() { + return contents; + } + + public void setContents(LinkedList contents) { + this.contents = contents; + } + + public void addElement(ModelElement element) { + if (getContents() == null) { + setContents(new LinkedList()); + } + + this.contents.add(element); + } + + private void addModelElement(IModelElement projectElement, HashSet idElements) { + + switch (projectElement.getModelType()) { + case IModelElementFactory.MODEL_TYPE_PACKAGE: + addElement(new Package((IPackage) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_MODEL: + addElement(new Model((IModel) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_CLASS: + addElement(new Class((IClass) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_DATA_TYPE: + addElement(new Class((IDataType) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_GENERALIZATION: + IGeneralization gen = (IGeneralization) projectElement; + IModelElement fromElement = gen.getFrom(); + + if (fromElement == null) break; + + String fromType = fromElement.getModelType(); + + if (fromType == null) break; + + boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + + if (!isFromClass && !isFromAssociation) break; + + IModelElement toElement = gen.getTo(); + + if (toElement == null) break; + + String toType = toElement.getModelType(); + + if (toType == null) break; + + boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + + if (!isToClass && !isToAssociation) break; + + addElement(new Generalization((IGeneralization) projectElement)); + break; + + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + addElement(new Association((IAssociation) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: + addElement(new GeneralizationSet((IGeneralizationSet) projectElement, idElements)); + break; + + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: + addElement(new AssociationClass((IAssociationClass) projectElement)); + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Property.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Property.java new file mode 100644 index 00000000..c3b221e2 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Property.java @@ -0,0 +1,455 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.JsonObject; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.model.IAssociationClass; +import com.vp.plugin.model.IAssociationEnd; +import com.vp.plugin.model.IAttribute; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.IMultiplicity; +import com.vp.plugin.model.factory.IModelElementFactory; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Implementation of ModelElement to handle IAtrribute and IAssociationEnd objects to be serialized + * as ontouml-schema/Property + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class Property implements ModelElement { + + private final IModelElement sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + @SerializedName("name") + @Expose + private String name; + + @SerializedName("description") + @Expose + private String description; + + @SerializedName("propertyType") + @Expose + private Reference propertyType; + + @SerializedName("cardinality") + @Expose + private String cardinality; + + @SerializedName("isDerived") + @Expose + private boolean isDerived; + + @SerializedName("isOrdered") + @Expose + private boolean isOrdered; + + @SerializedName("isReadOnly") + @Expose + private boolean isReadOnly; + + @SerializedName("stereotypes") + @Expose + private List stereotypes; + + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; + + @SerializedName("subsettedProperties") + @Expose + private List subsettedProperties; + + @SerializedName("redefinedProperties") + @Expose + private List redefinedProperties; + + @SerializedName("aggregationKind") + @Expose + private String aggregationKind; + + private Property(IModelElement source) { + this.sourceModelElement = source; + + this.type = ModelElement.TYPE_PROPERTY; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); + + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } + + public Property(IAttribute source) { + this((IModelElement) source); + + IModelElement reference = source.getTypeAsElement(); + if (reference != null) { + setPropertyType(new Reference(reference)); + } else { + System.out.println( + "Attribute " + + source.getParent().getName() + + "::" + + source.getName() + + " type is a non-standard string: " + + source.getTypeAsString()); + } + + if (!((source.getMultiplicity()).equals(IAttribute.MULTIPLICITY_UNSPECIFIED))) { + setCardinality(source.getMultiplicity()); + } + + setOrdered(ModelElement.isOrdered(source)); + setDerived(source.isDerived()); + setReadOnly(source.isReadOnly()); + + final String[] stereotypes = source.toStereotypeArray(); + for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { + addStereotype(stereotypes[i]); + } + + Iterator subsettedIterator = source.subsettedPropertyIterator(); + while (subsettedIterator.hasNext()) { + IAttribute atr = (IAttribute) subsettedIterator.next(); + addSubsettedProperty(new Reference(atr)); + } + + Iterator redefinedProperties = source.redefinedPropertyIterator(); + while (redefinedProperties.hasNext()) { + IAttribute rdp = (IAttribute) redefinedProperties.next(); + addRedefinedProperty(new Reference(rdp)); + } + + setAggregationKind(source.getAggregation()); + setDerived(source.isDerived()); + } + + public Property(IAssociationEnd source) { + this((IModelElement) source); + + IModelElement reference = source.getTypeAsElement(); + if (reference != null) { + setPropertyType(new Reference(reference)); + } else { + if (source != null && source.getParent() != null) { + System.out.println( + "Association End " + + source.getParent().getName() + + "::" + + source.getName() + + " type is a non-standard string: " + + source.getTypeAsString()); + } else { + System.out.println("Strange..."); + } + } + + if (!((source.getMultiplicity()).equals(IAttribute.MULTIPLICITY_UNSPECIFIED))) { + setCardinality(source.getMultiplicity()); + } + + setOrdered(ModelElement.isOrdered(source)); + setDerived(source.isDerived()); + setReadOnly(source.isReadOnly()); + + final String[] stereotypes = source.toStereotypeArray(); + for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { + addStereotype(stereotypes[i]); + } + + Iterator subsettedIterator = source.subsettedPropertyIterator(); + + while (subsettedIterator.hasNext()) { + IAssociationEnd sub = (IAssociationEnd) subsettedIterator.next(); + addSubsettedProperty(new Reference(sub)); + } + + Iterator redefinedProperties = source.redefinedPropertyIterator(); + + while (redefinedProperties.hasNext()) { + IAssociationEnd rdp = (IAssociationEnd) redefinedProperties.next(); + addRedefinedProperty(new Reference(rdp)); + } + + setAggregationKind(source.getAggregationKind()); + } + + public Property(IAssociationClass associationClass, IModelElement type) { + this.sourceModelElement = null; + + this.type = ModelElement.TYPE_PROPERTY; + this.id = associationClass.getId() + type.getId(); + setName(null); + setDescription(null); + + if (type != null) { + setPropertyType(new Reference(type)); + } + + setCardinality("0..*"); + } + + public static String getTypeStereotype(IAssociationEnd associationEnd) { + String noStereotype = ""; + + try { + final IModelElement type = associationEnd.getTypeAsElement(); + + if (!type.getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS)) { + return noStereotype; + } + + final String[] stereotypes = ((IClass) type).toStereotypeArray(); + + if (stereotypes != null && stereotypes.length == 1) { + return stereotypes[0]; + } + + return noStereotype; + } catch (Exception e) { + return noStereotype; + } + } + + @Override + public String getId() { + return getSourceModelElement().getId(); + } + + @Override + public IModelElement getSourceModelElement() { + return this.sourceModelElement; + } + + @Override + public String getOntoUMLType() { + return this.type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } + + public Reference getPropertyType() { + return propertyType; + } + + public void setPropertyType(Reference propertyType) { + this.propertyType = propertyType; + } + + public String getCardinality() { + return cardinality; + } + + public void setCardinality(String cardinality) { + this.cardinality = cardinality; + } + + public boolean isDerived() { + return isDerived; + } + + public void setDerived(boolean isDerived) { + this.isDerived = isDerived; + } + + public boolean isOrdered() { + return isOrdered; + } + + public void setOrdered(boolean isOrdered) { + this.isOrdered = isOrdered; + } + + public void setOrdered(IMultiplicity multiplicity) { + this.isOrdered = (multiplicity != null) ? multiplicity.isOrdered() : false; + } + + public boolean isReadOnly() { + return isReadOnly; + } + + public void setReadOnly(boolean isReadOnly) { + this.isReadOnly = isReadOnly; + } + + public List getStereotypes() { + return this.stereotypes; + } + + public void setStereotypes(List stereotypes) { + this.stereotypes = stereotypes; + } + + public String getStereotype(int position) { + return this.stereotypes.get(position); + } + + public void addStereotype(String name) { + if (this.stereotypes == null) { + this.stereotypes = new ArrayList(); + } + + this.stereotypes.add(name); + } + + public void removeStereotype(String name) { + if (this.stereotypes != null && this.stereotypes.contains(name)) { + this.stereotypes.remove(name); + } + } + + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } + + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } + + public List getSubsettedProperties() { + return subsettedProperties; + } + + public void setSubsettedProperties(List subsettedProperties) { + this.subsettedProperties = subsettedProperties; + } + + public void addSubsettedProperty(Reference ref) { + if (this.subsettedProperties == null) { + this.subsettedProperties = new ArrayList(); + } + + this.subsettedProperties.add(ref); + } + + public void removeSubsettedProperty(Reference ref) { + if (this.subsettedProperties != null && this.subsettedProperties.contains(ref)) { + this.subsettedProperties.remove(ref); + } + } + + public List getRedefinedProperties() { + return redefinedProperties; + } + + public void setRedefinedProperties(List redefinedPropeties) { + this.redefinedProperties = redefinedPropeties; + } + + public void addRedefinedProperty(Reference ref) { + if (this.redefinedProperties == null) { + this.redefinedProperties = new ArrayList(); + } + + this.redefinedProperties.add(ref); + } + + public void removeRedefinedProperty(Reference ref) { + if (this.redefinedProperties != null && this.redefinedProperties.contains(ref)) { + this.redefinedProperties.remove(ref); + } + } + + public String getAggregationKind() { + return aggregationKind; + } + + public void setAggregationKind(int aggregation) { + switch (aggregation) { + case 0: + this.aggregationKind = "NONE"; + break; + case 1: + this.aggregationKind = "SHARED"; + break; + case 2: + this.aggregationKind = "COMPOSITE"; + break; + default: + } + } + + public void setAggregationKind(String aggregationKind) { + if (aggregationKind == null) { + this.aggregationKind = null; + return; + } + + switch (aggregationKind.toUpperCase()) { + case "NONE": + this.aggregationKind = "NONE"; + return; + case "COMPOSITED": + this.aggregationKind = "COMPOSITE"; + return; + case "SHARED": + this.aggregationKind = "SHARED"; + return; + default: + this.aggregationKind = null; + } + } + + public String getType() { + return type; + } + + public static void removeRedefinedProperties(IAssociationEnd associationEnd) { + final IAssociationEnd[] redefinedProperties = associationEnd.toRedefinedPropertyArray(); + + for (int i = 0; redefinedProperties != null && i < redefinedProperties.length; i++) { + associationEnd.removeRedefinedProperty(redefinedProperties[i]); + } + } + + public static void removeSubsettedProperties(IAssociationEnd associationEnd) { + final IAssociationEnd[] subsettedProperties = associationEnd.toSubsettedPropertyArray(); + + for (int i = 0; subsettedProperties != null && i < subsettedProperties.length; i++) { + associationEnd.removeSubsettedProperty(subsettedProperties[i]); + } + } + + public static void addRedefinedProperties( + IAssociationEnd associationEnd, IAssociationEnd[] redefinedProperties) { + for (int i = 0; redefinedProperties != null && i < redefinedProperties.length; i++) { + associationEnd.addRedefinedProperty(redefinedProperties[i]); + } + } + + public static void addSubsettedProperties( + IAssociationEnd associationEnd, IAssociationEnd[] subsettedProperties) { + for (int i = 0; subsettedProperties != null && i < subsettedProperties.length; i++) { + associationEnd.addSubsettedProperty(subsettedProperties[i]); + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Reference.java b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Reference.java new file mode 100644 index 00000000..25eb1d9e --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/uml/Reference.java @@ -0,0 +1,41 @@ +package it.unibz.inf.ontouml.vp.model.uml; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import com.vp.plugin.model.IModelElement; + +/** + * Implementation of ModelElement to handle IModelElement objects which are referred by other + * elements in the model. They are serialized as ontouml-schema/Reference. + * + * @author Claudenir Fonseca + * @author Tiago Prince Sales + * @author Victor Viola + */ +public class Reference { + + @SerializedName("type") + @Expose + private final String type; + + @SerializedName("id") + @Expose + private final String id; + + public Reference(IModelElement element) { + this.id = element.getId(); + this.type = ModelElement.toOntoUMLSchemaType(element); + + if (this.type == null) { + System.out.println("Broken reference on ModelElement.toOntoUMLSchemaType(element)"); + } + } + + public String getType() { + return type; + } + + public String getId() { + return id; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/ActionIdManager.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/ActionIdManager.java new file mode 100644 index 00000000..519a15f6 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/ActionIdManager.java @@ -0,0 +1,325 @@ +package it.unibz.inf.ontouml.vp.utils; + +public final class ActionIdManager { + + // Class stereotypes (ordered as in plugin.xml) + public static final String TYPE = "it.unibz.inf.ontouml.vp.addTypeStereotype"; + + public static final String HISTORICAL_ROLE = + "it.unibz.inf.ontouml.vp.addHistoricalRoleStereotype"; + public static final String HISTORICAL_ROLE_MIXIN = + "it.unibz.inf.ontouml.vp.addHistoricalRoleMixinStereotype"; + public static final String EVENT = "it.unibz.inf.ontouml.vp.addEventStereotype"; + public static final String SITUATION = "it.unibz.inf.ontouml.vp.addSituationStereotype"; + + public static final String ENUMERATION = "it.unibz.inf.ontouml.vp.addEnumerationStereotype"; + public static final String DATATYPE = "it.unibz.inf.ontouml.vp.addDatatypeStereotype"; + public static final String ABSTRACT = "it.unibz.inf.ontouml.vp.addAbstractStereotype"; + + public static final String SUBKIND = "it.unibz.inf.ontouml.vp.addSubkindStereotype"; + public static final String ROLE_MIXIN = "it.unibz.inf.ontouml.vp.addRoleMixinStereotype"; + public static final String ROLE = "it.unibz.inf.ontouml.vp.addRoleStereotype"; + public static final String RELATOR = "it.unibz.inf.ontouml.vp.addRelatorStereotype"; + public static final String QUANTITY = "it.unibz.inf.ontouml.vp.addQuantityStereotype"; + public static final String QUALITY = "it.unibz.inf.ontouml.vp.addQualityStereotype"; + public static final String PHASE_MIXIN = "it.unibz.inf.ontouml.vp.addPhaseMixinStereotype"; + public static final String PHASE = "it.unibz.inf.ontouml.vp.addPhaseStereotype"; + public static final String MODE = "it.unibz.inf.ontouml.vp.addModeStereotype"; + public static final String MIXIN = "it.unibz.inf.ontouml.vp.addMixinStereotype"; + public static final String KIND = "it.unibz.inf.ontouml.vp.addKindStereotype"; + public static final String COLLECTIVE = "it.unibz.inf.ontouml.vp.addCollectiveStereotype"; + public static final String CATEGORY = "it.unibz.inf.ontouml.vp.addCategoryStereotype"; + + // Association stereotypes (ordered as in plugin.xml) + public static final String INSTANTIATION = "it.unibz.inf.ontouml.vp.addInstantiationStereotype"; + + public static final String TERMINATION = "it.unibz.inf.ontouml.vp.addTerminationStereotype"; + public static final String PARTICIPATIONAL = + "it.unibz.inf.ontouml.vp.addParticipationalStereotype"; + public static final String PARTICIPATION = "it.unibz.inf.ontouml.vp.addParticipationStereotype"; + public static final String HISTORICAL_DEPENDENCE = + "it.unibz.inf.ontouml.vp.addHistoricalDependenceStereotype"; + public static final String CREATION = "it.unibz.inf.ontouml.vp.addCreationStereotype"; + public static final String MANIFESTATION = "it.unibz.inf.ontouml.vp.addManifestationStereotype"; + + public static final String BRINGS_ABOUT = "it.unibz.inf.ontouml.vp.addBringsAboutStereotype"; + public static final String TRIGGERS = "it.unibz.inf.ontouml.vp.addTriggersStereotype"; + + public static final String SUB_QUANTITY_OF = "it.unibz.inf.ontouml.vp.addSubQuantityStereotype"; + public static final String SUB_COLLECTION_OF = + "it.unibz.inf.ontouml.vp.addSubCollectionStereotype"; + public static final String MEMBER_OF = "it.unibz.inf.ontouml.vp.addMemberOfStereotype"; + public static final String MEDIATION = "it.unibz.inf.ontouml.vp.addMediationStereotype"; + public static final String MATERIAL = "it.unibz.inf.ontouml.vp.addMaterialStereotype"; + public static final String EXTERNAL_DEPENDENCE = + "it.unibz.inf.ontouml.vp.addExternalDependenceStereotype"; + public static final String COMPONENT_OF = "it.unibz.inf.ontouml.vp.addComponentOfStereotype"; + public static final String COMPARATIVE = "it.unibz.inf.ontouml.vp.addComparativeStereotype"; + public static final String CHARACTERIZATION = + "it.unibz.inf.ontouml.vp.addCharacterizationStereotype"; + + // Attribute stereotypes (ordered as in plugin.xml) + public static final String END = "it.unibz.inf.ontouml.vp.addEndStereotype"; + public static final String BEGIN = "it.unibz.inf.ontouml.vp.addBeginStereotype"; + + // //Fixed Menu ActionIds + public static final String TYPE_FIXED = "it.unibz.inf.ontouml.vp.addTypeStereotype.fixedMenu"; + + public static final String HISTORICAL_ROLE_FIXED = + "it.unibz.inf.ontouml.vp.addHistoricalRoleStereotype.fixedMenu"; + public static final String HISTORICAL_ROLE_MIXIN_FIXED = + "it.unibz.inf.ontouml.vp.addHistoricalRoleMixinStereotype.fixedMenu"; + public static final String EVENT_FIXED = "it.unibz.inf.ontouml.vp.addEventStereotype.fixedMenu"; + public static final String SITUATION_FIXED = + "it.unibz.inf.ontouml.vp.addSituationStereotype.fixedMenu"; + + public static final String ENUMERATION_FIXED = + "it.unibz.inf.ontouml.vp.addEnumerationStereotype.fixedMenu"; + public static final String DATATYPE_FIXED = + "it.unibz.inf.ontouml.vp.addDatatypeStereotype.fixedMenu"; + public static final String ABSTRACT_FIXED = + "it.unibz.inf.ontouml.vp.addAbstractStereotype.fixedMenu"; + + public static final String SUBKIND_FIXED = + "it.unibz.inf.ontouml.vp.addSubkindStereotype.fixedMenu"; + public static final String ROLE_MIXIN_FIXED = + "it.unibz.inf.ontouml.vp.addRoleMixinStereotype.fixedMenu"; + public static final String ROLE_FIXED = "it.unibz.inf.ontouml.vp.addRoleStereotype.fixedMenu"; + public static final String RELATOR_FIXED = + "it.unibz.inf.ontouml.vp.addRelatorStereotype.fixedMenu"; + public static final String QUANTITY_FIXED = + "it.unibz.inf.ontouml.vp.addQuantityStereotype.fixedMenu"; + public static final String QUALITY_FIXED = + "it.unibz.inf.ontouml.vp.addQualityStereotype.fixedMenu"; + public static final String PHASE_MIXIN_FIXED = + "it.unibz.inf.ontouml.vp.addPhaseMixinStereotype.fixedMenu"; + public static final String PHASE_FIXED = "it.unibz.inf.ontouml.vp.addPhaseStereotype.fixedMenu"; + public static final String MODE_FIXED = "it.unibz.inf.ontouml.vp.addModeStereotype.fixedMenu"; + public static final String MIXIN_FIXED = "it.unibz.inf.ontouml.vp.addMixinStereotype.fixedMenu"; + public static final String KIND_FIXED = "it.unibz.inf.ontouml.vp.addKindStereotype.fixedMenu"; + public static final String COLLECTIVE_FIXED = + "it.unibz.inf.ontouml.vp.addCollectiveStereotype.fixedMenu"; + public static final String CATEGORY_FIXED = + "it.unibz.inf.ontouml.vp.addCategoryStereotype.fixedMenu"; + + // Association stereotypes (ordered as in plugin.xml) + public static final String INSTANTIATION_FIXED = + "it.unibz.inf.ontouml.vp.addInstantiationStereotype.fixedMenu"; + + public static final String TERMINATION_FIXED = + "it.unibz.inf.ontouml.vp.addTerminationStereotype.fixedMenu"; + public static final String PARTICIPATIONAL_FIXED = + "it.unibz.inf.ontouml.vp.addParticipationalStereotype.fixedMenu"; + public static final String PARTICIPATION_FIXED = + "it.unibz.inf.ontouml.vp.addParticipationStereotype.fixedMenu"; + public static final String HISTORICAL_DEPENDENCE_FIXED = + "it.unibz.inf.ontouml.vp.addHistoricalDependenceStereotype.fixedMenu"; + public static final String CREATION_FIXED = + "it.unibz.inf.ontouml.vp.addCreationStereotype.fixedMenu"; + public static final String MANIFESTATION_FIXED = + "it.unibz.inf.ontouml.vp.addManifestationStereotype.fixedMenu"; + + public static final String BRINGS_ABOUT_FIXED = + "it.unibz.inf.ontouml.vp.addBringsStereotype.fixedMenu"; + public static final String TRIGGERS_FIXED = + "it.unibz.inf.ontouml.vp.addTriggersStereotype.fixedMenu"; + + public static final String SUB_QUANTITY_OF_FIXED = + "it.unibz.inf.ontouml.vp.addSubQuantityStereotype.fixedMenu"; + public static final String SUB_COLLECTION_OF_FIXED = + "it.unibz.inf.ontouml.vp.addSubCollectionStereotype.fixedMenu"; + public static final String MEMBER_OF_FIXED = + "it.unibz.inf.ontouml.vp.addMemberOfStereotype.fixedMenu"; + public static final String MEDIATION_FIXED = + "it.unibz.inf.ontouml.vp.addMediationStereotype.fixedMenu"; + public static final String MATERIAL_FIXED = + "it.unibz.inf.ontouml.vp.addMaterialStereotype.fixedMenu"; + public static final String EXTERNAL_DEPENDENCE_FIXED = + "it.unibz.inf.ontouml.vp.addExternalDependenceStereotype.fixedMenu"; + public static final String COMPONENT_OF_FIXED = + "it.unibz.inf.ontouml.vp.addComponentOfStereotype.fixedMenu"; + public static final String COMPARATIVE_FIXED = + "it.unibz.inf.ontouml.vp.addComparativeStereotype.fixedMenu"; + public static final String CHARACTERIZATION_FIXED = + "it.unibz.inf.ontouml.vp.addCharacterizationStereotype.fixedMenu"; + + // Attribute stereotypes (ordered as in plugin.xml) + public static final String END_FIXED = "it.unibz.inf.ontouml.vp.addEndStereotype.fixedMenu"; + public static final String BEGIN_FIXED = "it.unibz.inf.ontouml.vp.addBeginStereotype.fixedMenu"; + + // Properties menu options IDs + public static final String CLASS_PROPERTY_SET_RESTRICTED_TO = + "it.unibz.inf.ontouml.vp.ClassProperties.restrictedTo"; + public static final String CLASS_PROPERTY_SET_IS_EXTENSIONAL = + "it.unibz.inf.ontouml.vp.ClassProperties.isExtensional"; + public static final String CLASS_PROPERTY_SET_IS_DERIVED = + "it.unibz.inf.ontouml.vp.ClassProperties.isDerived"; + public static final String CLASS_PROPERTY_SET_IS_ABSTRACT = + "it.unibz.inf.ontouml.vp.ClassProperties.isAbstract"; + public static final String CLASS_PROPERTY_SET_IS_POWERTYPE = + "it.unibz.inf.ontouml.vp.ClassProperties.isPowertype"; + public static final String CLASS_PROPERTY_SET_ORDER = + "it.unibz.inf.ontouml.vp.ClassProperties.order"; + + public static final String ASSOCIATION_PROPERTY_SET_IS_ABSTRACT = + "it.unibz.inf.ontouml.vp.AssociationProperties.isAbstract"; + public static final String ASSOCIATION_PROPERTY_SET_IS_DERIVED = + "it.unibz.inf.ontouml.vp.AssociationProperties.isDerived"; + public static final String ASSOCIATION_PROPERTY_SOURCE_SET_IS_DERIVED = + "it.unibz.inf.ontouml.vp.AssociationProperties.Source.isDerived"; + public static final String ASSOCIATION_PROPERTY_SOURCE_SET_IS_ORDERED = + "it.unibz.inf.ontouml.vp.AssociationProperties.Source.isOrdered"; + public static final String ASSOCIATION_PROPERTY_SOURCE_SET_IS_READ_ONLY = + "it.unibz.inf.ontouml.vp.AssociationProperties.Source.isReadOnly"; + public static final String ASSOCIATION_PROPERTY_TARGET_SET_IS_DERIVED = + "it.unibz.inf.ontouml.vp.AssociationProperties.Target.isDerived"; + public static final String ASSOCIATION_PROPERTY_TARGET_SET_IS_ORDERED = + "it.unibz.inf.ontouml.vp.AssociationProperties.Target.isOrdered"; + public static final String ASSOCIATION_PROPERTY_TARGET_SET_IS_READ_ONLY = + "it.unibz.inf.ontouml.vp.AssociationProperties.Target.isReadOnly"; + + public static final String ATTRIBUTE_PROPERTY_SET_IS_DERIVED = + "it.unibz.inf.ontouml.vp.AttributeProperties.isDerived"; + public static final String ATTRIBUTE_PROPERTY_SET_IS_ORDERED = + "it.unibz.inf.ontouml.vp.AttributeProperties.isOrdered"; + public static final String ATTRIBUTE_PROPERTY_SET_IS_READ_ONLY = + "it.unibz.inf.ontouml.vp.AttributeProperties.isReadOnly"; + + public static final String ASSOCIATION_ACTION_INVERT_ASSOCIATION = + "it.unibz.inf.ontouml.vp.AssociationActions.invertAssociation"; + + public static String classStereotypeToActionID(String stereotype) { + switch (stereotype) { + case Stereotype.TYPE: + return TYPE; + case Stereotype.HISTORICAL_ROLE: + return HISTORICAL_ROLE; + case Stereotype.HISTORICAL_ROLE_MIXIN: + return HISTORICAL_ROLE_MIXIN; + case Stereotype.EVENT: + return EVENT; + case Stereotype.SITUATION: + return SITUATION; + case Stereotype.CATEGORY: + return CATEGORY; + case Stereotype.MIXIN: + return MIXIN; + case Stereotype.ROLE_MIXIN: + return ROLE_MIXIN; + case Stereotype.PHASE_MIXIN: + return PHASE_MIXIN; + case Stereotype.KIND: + return KIND; + case Stereotype.COLLECTIVE: + return COLLECTIVE; + case Stereotype.QUANTITY: + return QUANTITY; + case Stereotype.RELATOR: + return RELATOR; + case Stereotype.QUALITY: + return QUALITY; + case Stereotype.MODE: + return MODE; + case Stereotype.SUBKIND: + return SUBKIND; + case Stereotype.ROLE: + return ROLE; + case Stereotype.PHASE: + return PHASE; + case Stereotype.ENUMERATION: + return ENUMERATION; + case Stereotype.DATATYPE: + return DATATYPE; + case Stereotype.ABSTRACT: + return ABSTRACT; + default: + return null; + } + } + + public static String associationStereotypeToActionID(String stereotype) { + switch (stereotype) { + case Stereotype.INSTANTIATION: + return INSTANTIATION; + case Stereotype.TERMINATION: + return TERMINATION; + case Stereotype.PARTICIPATIONAL: + return PARTICIPATIONAL; + case Stereotype.PARTICIPATION: + return PARTICIPATION; + case Stereotype.HISTORICAL_DEPENDENCE: + return HISTORICAL_DEPENDENCE; + case Stereotype.CREATION: + return CREATION; + case Stereotype.MANIFESTATION: + return MANIFESTATION; + case Stereotype.BRINGS_ABOUT: + return BRINGS_ABOUT; + case Stereotype.TRIGGERS: + return TRIGGERS; + case Stereotype.SUB_QUANTITY_OF: + return SUB_QUANTITY_OF; + case Stereotype.SUB_COLLECTION_OF: + return SUB_COLLECTION_OF; + case Stereotype.MEMBER_OF: + return MEMBER_OF; + case Stereotype.MEDIATION: + return MEDIATION; + case Stereotype.MATERIAL: + return MATERIAL; + case Stereotype.EXTERNAL_DEPENDENCE: + return EXTERNAL_DEPENDENCE; + case Stereotype.COMPONENT_OF: + return COMPONENT_OF; + case Stereotype.COMPARATIVE: + return COMPARATIVE; + case Stereotype.CHARACTERIZATION: + return CHARACTERIZATION; + default: + return null; + } + } + + public static String getActionLabelById(String actionId) { + switch (actionId) { + case INSTANTIATION: + return "Instantiation"; + case TERMINATION: + return "Termination"; + case PARTICIPATIONAL: + return "Participational"; + case PARTICIPATION: + return "Participation"; + case HISTORICAL_DEPENDENCE: + return "HistoricalDependence"; + case CREATION: + return "Creation"; + case MANIFESTATION: + return "Manifestation"; + case BRINGS_ABOUT: + return "BringsAbout"; + case TRIGGERS: + return "Triggers"; + case SUB_QUANTITY_OF: + return "SubQuantityOf"; + case SUB_COLLECTION_OF: + return "SubCollectionOf"; + case MEMBER_OF: + return "MemberOf"; + case MEDIATION: + return "Mediation"; + case MATERIAL: + return "Material"; + case EXTERNAL_DEPENDENCE: + return "ExternalDependence"; + case COMPONENT_OF: + return "ComponentOf"; + case COMPARATIVE: + return "Comparative"; + case CHARACTERIZATION: + return "Characterization"; + default: + throw new UnsupportedOperationException("Unexpected action id value: " + actionId); + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/CollectionAdapter.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/CollectionAdapter.java deleted file mode 100644 index 42c9cf46..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/CollectionAdapter.java +++ /dev/null @@ -1,29 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -import java.lang.reflect.Type; -import java.util.Collection; - -// TODO Check whether this class is indeed necessary. -public class CollectionAdapter implements JsonSerializer> { - - @Override - public JsonElement serialize(Collection src, Type typeOfSrc, JsonSerializationContext context) { - if (src == null || src.isEmpty()) - return null; - - JsonArray array = new JsonArray(); - - for (Object child : src) { - JsonElement element = context.serialize(child); - array.add(element); - } - - return array; - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/Configurations.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/Configurations.java deleted file mode 100644 index c20bf234..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/Configurations.java +++ /dev/null @@ -1,156 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonSyntaxException; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.model.IProject; -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; - -/** - * - * OntoUML Plugin configuration utility, allows persisting - * user preferences on the functionalities enabled by the plugin. - * - * @author Claudenir Fonseca - * - */ -public class Configurations { - - private static final String CONFIG_FILE_NAME = ".ontouml.config.json"; - - private static Configurations instance; - - @SerializedName("projects") - @Expose() - private List projects; - - private Configurations() { - this.projects = new ArrayList(); - } - - private List getProjectConfigurationsList() { - return projects; - } - - private boolean addProjectConfigurations(ProjectConfigurations projectConfigurations) { - return getProjectConfigurationsList().add(projectConfigurations); - } - - /** - * - * Returns singleton instance of the class. - * - * @return configurations - * - */ - public static Configurations getInstance() { - if(instance == null) { - final ApplicationManager application = ApplicationManager.instance(); - final File workspace = application.getWorkspaceLocation(); - final File configurationsFile = new File(workspace, CONFIG_FILE_NAME); - - if(configurationsFile.exists()) { - String json = ""; - try { - json = new String(Files.readAllBytes(configurationsFile.toPath())); - Gson gson = new Gson(); - instance = gson.fromJson(json, Configurations.class); - } - catch (Exception e) { - if(e instanceof IOException) - application.getViewManager().showMessage("Unable to load configuration file (" + OntoUMLPlugin.PLUGIN_NAME + ").\n"); - else if(e instanceof JsonSyntaxException ) - application.getViewManager().showMessage("Configuration file ill-formed (" + OntoUMLPlugin.PLUGIN_NAME + ").\n"); - else - application.getViewManager().showMessage("Unknown error while reading configuration file (" + OntoUMLPlugin.PLUGIN_NAME + ").\n"); - - e.printStackTrace(); - } - } - - if(instance==null) - instance = new Configurations(); - } - - return instance; - } - - /** - * - * Persists user preferences on Visual Paradigm's workspace. - * - */ - public void save() { - final ApplicationManager application = ApplicationManager.instance(); - final File workspace = application.getWorkspaceLocation(); - final File configurationsFile = new File(workspace, CONFIG_FILE_NAME); - final FileWriter fw; - final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); - final String json = gson.toJson(this); - - try { - if(!configurationsFile.exists()) { - configurationsFile.createNewFile(); - } - - fw = new FileWriter(configurationsFile); - fw.write(json); - fw.close(); - } catch (IOException e) { - application.getViewManager().showMessage("Unable save " - + OntoUMLPlugin.PLUGIN_NAME - + " configurations."); - e.printStackTrace(); - } - } - - /** - * - * Retrieves the configurations of the current project. - * - * @return current project's configurations. - * - */ - public ProjectConfigurations getProjectConfigurations() { - final IProject current = ApplicationManager.instance().getProjectManager().getProject(); - - return getProjectConfigurations(current.getId()); - } - - /** - * - * Retrieves the project configurations given the provided ID. - * If no previous configurations is present, a new instance of - * ProjectConfigurations is returned with default - * settings. - * - * @param projectId - Interest project's ID. - * - * @return current project's configurations. - * - * - */ - public ProjectConfigurations getProjectConfigurations(String projectId) { - for (ProjectConfigurations projectConfigurations : getProjectConfigurationsList()) { - if(projectConfigurations.getId().equals(projectId)) { - return projectConfigurations; - } - } - - ProjectConfigurations projectConfigurations = new ProjectConfigurations(projectId); - addProjectConfigurations(projectConfigurations); - - return projectConfigurations; - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLConstraintsManager.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLConstraintsManager.java new file mode 100644 index 00000000..4edacbe0 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLConstraintsManager.java @@ -0,0 +1,143 @@ +package it.unibz.inf.ontouml.vp.utils; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.VPPluginInfo; +import com.vp.plugin.model.IClass; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.model.uml.Class; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class OntoUMLConstraintsManager { + + private static final Type mapOfListsType = + new TypeToken>>() {}.getType(); + + private static String GENERALIZATION_CONSTRAINTS_FILENAME = "generalization_constraints.json"; + private static String ASSOCIATION_CONSTRAINTS_FILENAME = "association_constraints_nature.json"; + + private static String ALLOWED_SUBCLASSES = "allowedSubClassesFor"; + private static String ALLOWED_SUPERCLASSES = "allowedSuperClassesFor"; + + private static Map> allowedSuperClassesFor, allowedSubClassesFor; + + private static Map> associationConstraints; + + private static void loadConstraints() { + try { + final ApplicationManager app = ApplicationManager.instance(); + final VPPluginInfo pluginInfo = app.getPluginInfo(OntoUMLPlugin.PLUGIN_ID); + + File generalizationsConstraintsFile = + new File(pluginInfo.getPluginDir(), GENERALIZATION_CONSTRAINTS_FILENAME); + File associationConstraintsFile = + new File(pluginInfo.getPluginDir(), ASSOCIATION_CONSTRAINTS_FILENAME); + + final JsonParser parser = new JsonParser(); + final JsonObject gConstraintsObject = + parser.parse(new FileReader(generalizationsConstraintsFile)).getAsJsonObject(); + final JsonObject aConstraintsObject = + parser.parse(new FileReader(associationConstraintsFile)).getAsJsonObject(); + + final Gson gson = new Gson(); + allowedSubClassesFor = + gson.fromJson(gConstraintsObject.getAsJsonObject(ALLOWED_SUBCLASSES), mapOfListsType); + allowedSuperClassesFor = + gson.fromJson(gConstraintsObject.getAsJsonObject(ALLOWED_SUPERCLASSES), mapOfListsType); + associationConstraints = gson.fromJson(aConstraintsObject, mapOfListsType); + + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public static List getAllowedActionsBasedOnParent(IClass parrentClass) { + if (allowedSuperClassesFor == null || allowedSubClassesFor == null) { + loadConstraints(); + } + + final String parentClassStereotype = ModelElement.getUniqueStereotypeName(parrentClass); + List allowedStereotypes = allowedSubClassesFor.get(parentClassStereotype); + + if (allowedStereotypes == null) { + allowedStereotypes = new ArrayList<>(); + } + + return allowedStereotypes.stream() + .map(allowedStereotype -> ActionIdManager.classStereotypeToActionID(allowedStereotype)) + .collect(Collectors.toList()); + } + + public static List getAllowedActionsBasedOnChild(IClass childClass) { + if (allowedSuperClassesFor == null || allowedSubClassesFor == null) { + loadConstraints(); + } + + final String childClassStereotype = ModelElement.getUniqueStereotypeName(childClass); + List allowedStereotypes = allowedSuperClassesFor.get(childClassStereotype); + + if (allowedStereotypes == null) { + allowedStereotypes = new ArrayList<>(); + } + + return allowedStereotypes.stream() + .map(allowedStereotype -> ActionIdManager.classStereotypeToActionID(allowedStereotype)) + .collect(Collectors.toList()); + } + + public static List getAllowedActionsBasedOnSourceAndTarget( + IClass sourceClass, IClass targetClass) { + if (associationConstraints == null) { + loadConstraints(); + } + + final List sourceRestrictions = Class.getRestrictedToList(sourceClass); + final List targetRestrictions = Class.getRestrictedToList(targetClass); + final List> listsOfAllowedStereotypes = new ArrayList<>(); + + for (String sourceRestriction : sourceRestrictions) { + for (String targetRestriction : targetRestrictions) { + final List allowedStereotypes = + associationConstraints.get(sourceRestriction + ":" + targetRestriction); + + if (allowedStereotypes != null) { + listsOfAllowedStereotypes.add(allowedStereotypes); + } + } + } + + List intersectingAllowedStereotypes = new ArrayList<>(); + + for (List allowedStereotypes : listsOfAllowedStereotypes) { + if (allowedStereotypes.isEmpty()) { + return allowedStereotypes; + } + + if (intersectingAllowedStereotypes.isEmpty()) { + intersectingAllowedStereotypes.addAll(allowedStereotypes); + } else { + intersectingAllowedStereotypes = + intersectingAllowedStereotypes.stream() + .filter(allowedStereotypes::contains) + .distinct() + .collect(Collectors.toList()); + } + } + + return intersectingAllowedStereotypes.stream() + .map( + allowedStereotype -> ActionIdManager.associationStereotypeToActionID(allowedStereotype)) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLServerUtils.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLServerUtils.java deleted file mode 100644 index 6cdc3fa9..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLServerUtils.java +++ /dev/null @@ -1,233 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.SocketException; -import java.net.URL; -import java.util.stream.Collectors; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.vp.plugin.view.IDialogHandler; - -/** - * - * Class responsible for making requests to the OntoUML Server based on standard - * end points and configured server URL. - * - * @author Claudenir Fonseca - * @author Victor Viola - * - */ -public class OntoUMLServerUtils { - - private static final String TRANSFORM_GUFO_SERVICE_ENDPOINT = "/v1/transform/gufo"; - private static final String VERIFICATION_SERVICE_ENDPOINT = "/v1/verify"; - private static final String USER_MESSAGE_BAD_REQUEST = "There was a internal plugin error and the verification could not be completed."; - private static final String USER_MESSAGE_NOT_FOUND = "Unable to reach the server."; - private static final String USER_MESSAGE_INTERNAL_ERROR = "Internal server error."; - private static final String USER_MESSAGE_UNKNOWN_ERROR_REQUEST = "Error sending model verification to the server."; - private static final String USER_MESSAGE_UNKNOWN_ERROR_RESPONSE = "Error receiving model verification response."; - - public static BufferedReader transformToGUFO(String model, String baseIRI, String format, String uriFormatBy, - String inverse, String object, String analysis, String packages, String elementMapping, - String packageMapping, IDialogHandler loading) throws Exception { - final JsonObject optionsObj = new JsonObject(); - - boolean createObjectProperty = !Boolean.parseBoolean(object); - boolean createInverses = Boolean.parseBoolean(inverse); - boolean preAnalysis = Boolean.parseBoolean(analysis); - boolean prefixPackages = Boolean.parseBoolean(packages); - - optionsObj.addProperty("baseIRI", baseIRI); - optionsObj.addProperty("format", format); - optionsObj.addProperty("uriFormatBy", uriFormatBy); - optionsObj.addProperty("createInverses", createInverses); - optionsObj.addProperty("createObjectProperty", createObjectProperty); - optionsObj.addProperty("preAnalysis", preAnalysis); - optionsObj.addProperty("prefixPackages", prefixPackages); - optionsObj.add("customElementMapping", new Gson().fromJson(elementMapping, JsonObject.class)); - optionsObj.add("customPackageMapping", new Gson().fromJson(packageMapping, JsonObject.class)); - - final JsonObject bodyObj = new JsonObject(); - bodyObj.add("options", optionsObj); - bodyObj.add("model", new JsonParser().parse(model).getAsJsonObject()); - - final GsonBuilder builder = new GsonBuilder(); - final Gson gson = builder.serializeNulls().setPrettyPrinting().create(); - final String body = gson.toJson(bodyObj); - - final ProjectConfigurations configurations = Configurations.getInstance().getProjectConfigurations(); - final String url; - - if (configurations.isCustomServerEnabled()) { - url = configurations.getServerURL() + TRANSFORM_GUFO_SERVICE_ENDPOINT; - } else { - url = ProjectConfigurations.DEFAULT_SERVER_URL + TRANSFORM_GUFO_SERVICE_ENDPOINT; - } - - loading.shown(); - - try { - final HttpURLConnection request = request(url, body); - final BufferedReader responseReader = request.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST - ? new BufferedReader(new InputStreamReader(request.getInputStream())) - : new BufferedReader(new InputStreamReader(request.getErrorStream())); - - loading.canClosed(); - - switch (request.getResponseCode()) { - case HttpURLConnection.HTTP_OK: - if (!request.getContentType().equals("text/html")) { - return responseReader; - } else { - if (ViewUtils.exportToGUFOIssueDialogWithOption("Server not found.", - HttpURLConnection.HTTP_NOT_FOUND)) - return transformToGUFO(model, baseIRI, format, uriFormatBy, inverse, object, analysis, packages, - elementMapping, packageMapping, loading); - - System.out.println(responseReader.lines().collect(Collectors.joining())); - new Exception("Server not found.").printStackTrace(); - return null; - } - case HttpURLConnection.HTTP_BAD_REQUEST: - ViewUtils.exportToGUFOIssueDialog("Unable to transform the model due to an unexpected error." - + "\nPlease check the model for any syntactical errors." - + "\n\nWarning: partially exporting models to gUFO may introduce syntactical errors."); - System.out.println(responseReader.lines().collect(Collectors.joining())); - new Exception("Unable to transform the model due to an unexpected error." - + "\nPlease check the model for any syntactical errors." - + "\n\nWarning: partially exporting models to gUFO may introduce syntactical errors.").printStackTrace(); - return null; - case HttpURLConnection.HTTP_NOT_FOUND: - if (ViewUtils.exportToGUFOIssueDialogWithOption("Server not found.", HttpURLConnection.HTTP_NOT_FOUND)) - return transformToGUFO(model, baseIRI, format, uriFormatBy, inverse, object, analysis, packages, - elementMapping, packageMapping, loading); - - System.out.println(responseReader.lines().collect(Collectors.joining())); - new Exception("Server not found.").printStackTrace(); - return null; - case HttpURLConnection.HTTP_INTERNAL_ERROR: - if (ViewUtils.exportToGUFOIssueDialogWithOption("Server error.", HttpURLConnection.HTTP_INTERNAL_ERROR)) - return transformToGUFO(model, baseIRI, format, uriFormatBy, inverse, object, analysis, packages, - elementMapping, packageMapping, loading); - - System.out.println(responseReader.lines().collect(Collectors.joining())); - new Exception("Server error.").printStackTrace(); - return null; - default: - ViewUtils.exportToGUFOIssueDialog("Unexpected error."); - throw new Exception("Unknown error"); - } - } catch (MalformedURLException e) { - ViewUtils.exportToGUFOIssueDialog("Server error."); - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return null; - } - - public static String requestModelVerification(String serializedModel, IDialogHandler loading) { - final ProjectConfigurations configurations = Configurations.getInstance().getProjectConfigurations(); - final String url; - - if (configurations.isCustomServerEnabled()) { - url = configurations.getServerURL() + VERIFICATION_SERVICE_ENDPOINT; - } else { - url = ProjectConfigurations.DEFAULT_SERVER_URL + VERIFICATION_SERVICE_ENDPOINT; - } - - loading.shown(); - - try { - - final HttpURLConnection request = request(url, serializedModel); - final StringBuilder response = new StringBuilder(); - final BufferedReader reader = request.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST - ? new BufferedReader(new InputStreamReader(request.getInputStream())) - : new BufferedReader(new InputStreamReader(request.getErrorStream())); - - String line = null; - - while ((line = reader.readLine()) != null) { - response.append(line.trim()); - } - - reader.close(); - - loading.canClosed(); - - switch (request.getResponseCode()) { - case HttpURLConnection.HTTP_OK: - if (!request.getContentType().equals("text/html")) { - return response.toString(); - } else { - if (ViewUtils.verificationFailedDialogWithOption(USER_MESSAGE_NOT_FOUND, - HttpURLConnection.HTTP_NOT_FOUND)) - return requestModelVerification(serializedModel, loading); - } - case HttpURLConnection.HTTP_BAD_REQUEST: - ViewUtils.verificationFailedDialog(USER_MESSAGE_BAD_REQUEST); - return null; - case HttpURLConnection.HTTP_NOT_FOUND: - if (ViewUtils.verificationFailedDialogWithOption(USER_MESSAGE_NOT_FOUND, - HttpURLConnection.HTTP_NOT_FOUND)) - return requestModelVerification(serializedModel, loading); - - return null; - case HttpURLConnection.HTTP_INTERNAL_ERROR: - if (ViewUtils.verificationFailedDialogWithOption(USER_MESSAGE_INTERNAL_ERROR, - HttpURLConnection.HTTP_INTERNAL_ERROR)) - return requestModelVerification(serializedModel, loading); - - return null; - default: - ViewUtils.verificationFailedDialog(USER_MESSAGE_UNKNOWN_ERROR_RESPONSE); - return null; - } - - } catch (SocketException e) { - loading.canClosed(); - ViewUtils.verificationFailedDialog(USER_MESSAGE_NOT_FOUND); - e.printStackTrace(); - } catch (IOException e) { - loading.canClosed(); - ViewUtils.verificationFailedDialog(USER_MESSAGE_UNKNOWN_ERROR_RESPONSE); - e.printStackTrace(); - } catch (Exception e) { - loading.canClosed(); - ViewUtils.verificationFailedDialog(USER_MESSAGE_UNKNOWN_ERROR_REQUEST); - e.printStackTrace(); - } - - return null; - } - - private static HttpURLConnection request(String urlString, String body) throws MalformedURLException, IOException { - final URL url = new URL(urlString); - final HttpURLConnection request = (HttpURLConnection) url.openConnection(); - - request.setRequestMethod("POST"); - request.setRequestProperty("Content-Type", "application/json"); - request.setReadTimeout(60000); - request.setDoOutput(true); - - final OutputStream requestStream = request.getOutputStream(); - final byte[] requestBody = body.getBytes(); - - requestStream.write(requestBody, 0, requestBody.length); - requestStream.flush(); - requestStream.close(); - - return request; - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/ProjectConfigurations.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/ProjectConfigurations.java deleted file mode 100644 index ea9715ba..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/ProjectConfigurations.java +++ /dev/null @@ -1,467 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -import java.util.HashSet; - -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; - -/** - * - * Class that captures user preferences for a given project and enables JSON serialization. - * - * @author Claudenir Fonseca - * @author Victor Viola - * - */ -/** - * @author Victor Viola - * - */ -public class ProjectConfigurations { - - public static final boolean DEFAULT_IS_PLUGIN_ENABLED = true; - public static final boolean DEFAULT_IS_CUSTOM_SERVER_ENABLED = false; - public static final boolean DEFAULT_IS_EXPORT_ENABLED = true; - public static final boolean DEFAULT_IS_AUTOMATIC_COLORING_ENABLED = true; - public static final boolean DEFAULT_IS_AUTOMATIC_MODELLING_ENABLED = true; - public static final String DEFAULT_SERVER_URL = "http://api.ontouml.org"; - public static final String DEFAULT_EXPORT_PATH = System.getProperty("user.home"); - public static final String DEFAULT_EXPORT_FILENAME = ""; - public static final String DEFAULT_GUFO_EXPORT_PATH = System.getProperty("user.home"); - public static final String DEFAULT_GUFO_EXPORT_FILENAME = ""; - - @SerializedName("projectId") - @Expose() - private String id; - - @SerializedName("isOntoUMLPluginEnabled") - @Expose() - private boolean isOntoUMLPluginEnabled; - - @SerializedName("serverURL") - @Expose() - private String serverURL; - - @SerializedName("isCustomServerEnabled") - @Expose() - private boolean isCustomServerEnabled; - - @SerializedName("exportFolderPath") - @Expose() - private String exportFolderPath; - - @SerializedName("exportFileName") - @Expose() - private String exportFileName; - - @SerializedName("exportGUFOFolderPath") - @Expose() - private String exportGUFOFolderPath; - - @SerializedName("exportGUFOFileName") - @Expose() - private String exportGUFOFileName; - - @SerializedName("exportGUFOIRI") - @Expose() - private String exportGUFOIRI; - - @SerializedName("exportGUFOFormat") - @Expose() - private String exportGUFOFormat; - - @SerializedName("exportGUFOURIFormat") - @Expose() - private String exportGUFOURIFormat; - - @SerializedName("exportGUFOElementsDiagramTree") - @Expose() - private HashSet exportGUFOElementsDiagramTree; - - @SerializedName("exportGUFOElementsPackageTree") - @Expose() - private HashSet exportGUFOElementsPackageTree; - - @SerializedName("exportGUFOInverseBox") - @Expose() - private String exportGUFOInverseBox; - - @SerializedName("exportGUFOObjectBox") - @Expose() - private String exportGUFOObjectBox; - - @SerializedName("exportGUFOAnalysisBox") - @Expose() - private String exportGUFOAnalysisBox; - - @SerializedName("exportGUFOPackagesBox") - @Expose() - private String exportGUFOPackagesBox; - - @SerializedName("exportGUFOElementMapping") - @Expose() - private String exportGUFOElementMapping; - - @SerializedName("exportGUFOPackageMapping") - @Expose() - private String exportGUFOPackageMapping; - - @SerializedName("isExportEnabled") - @Expose() - private boolean isModelExportEnabled; - - @SerializedName("isAutomaticColoringEnabled") - @Expose() - private boolean isAutomaticColoringEnabled; - - @SerializedName("isSmartModellingEnabled") - @Expose() - private boolean isSmartModellingEnabled; - - /** - * - * Constructor without args to be called when deserializing project settings. - * - */ - public ProjectConfigurations() { - this.id = ""; - this.setDefaultValues(); - } - - /** - * - * Initializes an instance of ProjectConfigurations with default settings. - * - * @param projectId - String containing the ID of the project related to initialized configuration. - * - */ - public ProjectConfigurations(String projectId) { - this.id = projectId; - this.setDefaultValues(); - } - - /** - * - * Resets default project configurations. - * By default, none of the options are enabled and the server's URL is the plugin's defaults. - * - */ - public void setDefaultValues() { - this.isOntoUMLPluginEnabled = ProjectConfigurations.DEFAULT_IS_PLUGIN_ENABLED; - - this.isCustomServerEnabled = ProjectConfigurations.DEFAULT_IS_CUSTOM_SERVER_ENABLED; - this.serverURL = ProjectConfigurations.DEFAULT_SERVER_URL; - - this.isModelExportEnabled = ProjectConfigurations.DEFAULT_IS_EXPORT_ENABLED; - this.exportFolderPath = ProjectConfigurations.DEFAULT_EXPORT_PATH; - this.exportFileName = ProjectConfigurations.DEFAULT_EXPORT_FILENAME; - this.exportGUFOFolderPath = ProjectConfigurations.DEFAULT_GUFO_EXPORT_PATH; - this.exportGUFOFileName = ProjectConfigurations.DEFAULT_GUFO_EXPORT_FILENAME; - - this.isAutomaticColoringEnabled = ProjectConfigurations.DEFAULT_IS_AUTOMATIC_COLORING_ENABLED; - this.isSmartModellingEnabled = ProjectConfigurations.DEFAULT_IS_AUTOMATIC_MODELLING_ENABLED; - } - - /** - * - * Returns the related project's ID. - * - * @return project's ID. - * - */ - public String getId() { - return id; - } - - /** - * - * Checks if OntoUMLPlugin is enabled for the related project. - * - * @return true if plugin is enabled. - * - */ - public boolean isOntoUMLPluginEnabled() { - return isOntoUMLPluginEnabled; - } - - /** - * - * Sets if OntoUMLPlugin is enabled for the related project. - * - * @param isOntoUMLPluginEnabled - * - */ - public void setOntoUMLPluginEnabled(boolean isOntoUMLPluginEnabled) { - this.isOntoUMLPluginEnabled = isOntoUMLPluginEnabled; - } - - /** - * - * Returns OntoUML Server URL. - * - * @return serverURL - * - */ - public String getServerURL() { - return serverURL; - } - - /** - * - * Sets OntoUML Server URL. - * - * @param serverURL - * - */ - public void setServerURL(String serverURL) { - this.serverURL = serverURL; - } - - /** - * - * Checks if a custom server URL must be used. - * - * @return true if plugin is enabled and a custom server is enabled. - * - * @see {@link #isOntoUMLPluginEnabled()} - * - */ - public boolean isCustomServerEnabled() { - return isOntoUMLPluginEnabled() && isCustomServerEnabled; - } - - /** - * - * Sets if a custom server URL must be used. - * - * @param isCustomServerEnabled - * - */ - public void setCustomServerEnabled(boolean isCustomServerEnabled) { - this.isCustomServerEnabled = isCustomServerEnabled; - } - - /** - * - * Returns automatic export folders path as a String. - * - * @return exportFolderPath - * - */ - public String getExportFolderPath() { - return exportFolderPath; - } - - - /** - * - * Sets automatic export folders path from a String. - * - * @param exportFolderPath - * - */ - public void setExportFolderPath(String exportFolderPath) { - this.exportFolderPath = exportFolderPath; - } - - - /** - * - * Returns automatic export filename as a String. - * - * @return exportFileName - * - */ - public String getExportFilename() { - return exportFileName; - } - - /** - * - * Sets automatic export filename from a String. - * - * @param exportFileName - * - */ - public void setExportFilename(String exportFileName) { - this.exportFileName = exportFileName; - } - - public void setExportGUFOFolderPath(String exportFolderPath) { - this.exportGUFOFolderPath = exportFolderPath; - } - - public String getExportGUFOFolderPath() { - return exportGUFOFolderPath; - } - - public void setExportGUFOFilename(String exportFilename) { - this.exportGUFOFileName = exportFilename; - } - - public String getExportGUFOFilename() { - return exportGUFOFileName; - } - - public String getExportGUFOIRI() { - return exportGUFOIRI; - } - - public void setExportGUFOIRI(String exportGUFOIRI) { - this.exportGUFOIRI = exportGUFOIRI; - } - - public String getExportGUFOFormat() { - return exportGUFOFormat; - } - - public void setExportGUFOFormat(String exportGUFOFormat) { - this.exportGUFOFormat = exportGUFOFormat; - } - - public String getExportGUFOURIFormat() { - return exportGUFOURIFormat; - } - - public void setExportGUFOURIFormat(String exportGUFOURIFormat) { - this.exportGUFOURIFormat = exportGUFOURIFormat; - } - - public HashSet getExportGUFOElementsDiagramTree() { - return exportGUFOElementsDiagramTree; - } - - public void setExportGUFOElementsDiagramTree(HashSet exportGUFOElementsDiagramTree) { - this.exportGUFOElementsDiagramTree = exportGUFOElementsDiagramTree; - } - - public HashSet getExportGUFOElementsPackageTree() { - return exportGUFOElementsPackageTree; - } - - public void setExportGUFOElementsPackageTree(HashSet exportGUFOElementsPackageTree) { - this.exportGUFOElementsPackageTree = exportGUFOElementsPackageTree; - } - - public String getExportGUFOInverseBox() { - return exportGUFOInverseBox; - } - - public void setExportGUFOInverseBox(String exportGUFOInverseBox) { - this.exportGUFOInverseBox = exportGUFOInverseBox; - } - - public String getExportGUFOObjectBox() { - return exportGUFOObjectBox; - } - - public void setExportGUFOObjectBox(String exportGUFOObjectBox) { - this.exportGUFOObjectBox = exportGUFOObjectBox; - } - - public String getExportGUFOAnalysisBox() { - return exportGUFOAnalysisBox; - } - - public void setExportGUFOAnalysisBox(String exportGUFOAnalysisBox) { - this.exportGUFOAnalysisBox = exportGUFOAnalysisBox; - } - - public String getExportGUFOPackagesBox() { - return exportGUFOPackagesBox; - } - - public void setExportGUFOPackagesBox(String exportGUFOPackagesBox) { - this.exportGUFOPackagesBox = exportGUFOPackagesBox; - } - - public String getExportGUFOElementMapping() { - return exportGUFOElementMapping; - } - - public void setExportGUFOElementMapping(String exportGUFOElementMapping) { - this.exportGUFOElementMapping = exportGUFOElementMapping; - } - - public String getExportGUFOPackageMapping() { - return exportGUFOPackageMapping; - } - - public void setExportGUFOPackageMapping(String exportGUFOPackageMapping) { - this.exportGUFOPackageMapping = exportGUFOPackageMapping; - } - - /** - * - * Checks if an export folder is set for automatic model export. - * - * @return true if plugin is enabled and automatic model export is enabled. - * - * @see {@link #isOntoUMLPluginEnabled()} - * - */ - public boolean isModelExportEnabled() { - return isOntoUMLPluginEnabled() && isModelExportEnabled; - } - - /** - * - * Sets if automatic model export is enabled. - * - * param isModelExportEnabled - * - */ - public void setModelExportEnabled(boolean isModelExportEnabled) { - this.isModelExportEnabled = isModelExportEnabled; - } - - /** - * - * Checks if model elements should be automatically painted with the default color profile. - * - * @return true if plugin is enabled and automatic model element coloring is enabled. - * - * @see {@link #isOntoUMLPluginEnabled()} - * - */ - public boolean isAutomaticColoringEnabled() { - return isOntoUMLPluginEnabled() && isAutomaticColoringEnabled; - } - - /** - * - * Sets if model elements should be automatically painted with the default color profile. - * - * @param isAutomaticColoringEnabled - * - */ - public void setAutomaticColoringEnabled(boolean isAutomaticColoringEnabled) { - this.isAutomaticColoringEnabled = isAutomaticColoringEnabled; - } - - /** - * - * Checks if class stereotypes should be automatically disabled.. - * - * @return true if plugin is enabled and smart modelling is enabled. - * - * @see {@link #isOntoUMLPluginEnabled()} - * - */ - public boolean isSmartModellingEnabled() { - return isOntoUMLPluginEnabled() && isSmartModellingEnabled; - } - - /** - * - * Sets if class stereotypes should be automatically disabled. - * - * @param isSmartModellingEnabled - * - */ - public void setSmartModellingEnabled(boolean isSmartModellingEnabled) { - this.isSmartModellingEnabled = isSmartModellingEnabled; - } - - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/RestrictedTo.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/RestrictedTo.java new file mode 100644 index 00000000..93750d52 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/RestrictedTo.java @@ -0,0 +1,168 @@ +package it.unibz.inf.ontouml.vp.utils; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class RestrictedTo { + + // Ontological natures + public static final String FUNCTIONAL_COMPLEX = "functional-complex"; + public static final String COLLECTIVE = "collective"; + public static final String QUANTITY = "quantity"; + public static final String RELATOR = "relator"; + public static final String INTRINSIC_MODE = "intrinsic-mode"; + public static final String EXTRINSIC_MODE = "extrinsic-mode"; + public static final String QUALITY = "quality"; + public static final String EVENT = "event"; + public static final String SITUATION = "situation"; + public static final String TYPE = "type"; + public static final String ABSTRACT = "abstract"; + + public static List getRestrictionsList() { + return Arrays.asList( + COLLECTIVE, + EVENT, + SITUATION, + INTRINSIC_MODE, + EXTRINSIC_MODE, + FUNCTIONAL_COMPLEX, + QUALITY, + QUANTITY, + RELATOR, + TYPE, + ABSTRACT); + } + + public static List possibleRestrictedToValues(String stereotype) { + if (stereotype == null) return Collections.emptyList(); + + switch (stereotype) { + case Stereotype.TYPE: + return Collections.singletonList(TYPE); + case Stereotype.EVENT: + return Collections.singletonList(EVENT); + case Stereotype.SITUATION: + return Collections.singletonList(SITUATION); + case Stereotype.KIND: + return Collections.singletonList(FUNCTIONAL_COMPLEX); + case Stereotype.COLLECTIVE: + return Collections.singletonList(COLLECTIVE); + case Stereotype.QUANTITY: + return Collections.singletonList(QUANTITY); + case Stereotype.RELATOR: + return Collections.singletonList(RELATOR); + case Stereotype.QUALITY: + return Collections.singletonList(QUALITY); + case Stereotype.MODE: + return Arrays.asList(INTRINSIC_MODE, EXTRINSIC_MODE); + case Stereotype.ENUMERATION: + case Stereotype.DATATYPE: + case Stereotype.ABSTRACT: + return Collections.singletonList(ABSTRACT); + case Stereotype.CATEGORY: + case Stereotype.MIXIN: + case Stereotype.ROLE_MIXIN: + case Stereotype.PHASE_MIXIN: + case Stereotype.HISTORICAL_ROLE_MIXIN: + case Stereotype.SUBKIND: + case Stereotype.ROLE: + case Stereotype.PHASE: + case Stereotype.HISTORICAL_ROLE: + return Arrays.asList( + FUNCTIONAL_COMPLEX, + COLLECTIVE, + QUANTITY, + INTRINSIC_MODE, + EXTRINSIC_MODE, + QUALITY, + RELATOR); + default: + return Collections.emptyList(); + } + } + + public static boolean shouldOverrideRestrictedTo(String stereotype, String restrictedTo) { + switch (stereotype) { + case Stereotype.TYPE: + case Stereotype.EVENT: + case Stereotype.SITUATION: + case Stereotype.KIND: + case Stereotype.COLLECTIVE: + case Stereotype.QUANTITY: + case Stereotype.RELATOR: + case Stereotype.QUALITY: + case Stereotype.MODE: + case Stereotype.ENUMERATION: + case Stereotype.DATATYPE: + case Stereotype.ABSTRACT: + return true; + case Stereotype.CATEGORY: + case Stereotype.MIXIN: + case Stereotype.ROLE_MIXIN: + case Stereotype.PHASE_MIXIN: + case Stereotype.HISTORICAL_ROLE_MIXIN: + return (restrictedTo.contains(ABSTRACT) + || restrictedTo.contains(EVENT) + || restrictedTo.contains(TYPE) + || restrictedTo.contains(SITUATION)); + case Stereotype.SUBKIND: + case Stereotype.ROLE: + case Stereotype.PHASE: + case Stereotype.HISTORICAL_ROLE: + default: + return false; + } + } + + public static String getDefaultRestrictedTo(String stereotype) { + switch (stereotype) { + case Stereotype.TYPE: + return TYPE; + case Stereotype.EVENT: + return EVENT; + case Stereotype.SITUATION: + return SITUATION; + case Stereotype.CATEGORY: + case Stereotype.MIXIN: + case Stereotype.ROLE_MIXIN: + case Stereotype.PHASE_MIXIN: + case Stereotype.HISTORICAL_ROLE_MIXIN: + case Stereotype.KIND: + return FUNCTIONAL_COMPLEX; + case Stereotype.COLLECTIVE: + return COLLECTIVE; + case Stereotype.QUANTITY: + return QUANTITY; + case Stereotype.RELATOR: + return RELATOR; + case Stereotype.QUALITY: + return QUALITY; + case Stereotype.MODE: + return INTRINSIC_MODE; + case Stereotype.ENUMERATION: + case Stereotype.DATATYPE: + case Stereotype.ABSTRACT: + return ABSTRACT; + case Stereotype.SUBKIND: + case Stereotype.ROLE: + case Stereotype.PHASE: + case Stereotype.HISTORICAL_ROLE: + default: + return ""; + } + } + + public static boolean isRestrictedToEditable(String stereotype) { + final List customizableRestrictedToStereotypes = + Arrays.asList( + Stereotype.CATEGORY, + Stereotype.MIXIN, + Stereotype.MODE, + Stereotype.PHASE_MIXIN, + Stereotype.ROLE_MIXIN, + Stereotype.HISTORICAL_ROLE_MIXIN); + + return customizableRestrictedToStereotypes.contains(stereotype); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/ServerRequest.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/ServerRequest.java deleted file mode 100644 index c2bc3eec..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/ServerRequest.java +++ /dev/null @@ -1,18 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -public class ServerRequest implements Runnable { - - private boolean doStop = false; - - public synchronized void doStop() { - this.doStop = true; - } - - protected synchronized boolean keepRunning() { - return this.doStop == false; - } - - @Override - public void run() {} - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoring.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoring.java deleted file mode 100644 index f6ea8c51..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoring.java +++ /dev/null @@ -1,164 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -import java.awt.Color; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.diagram.IDiagramElement; -import com.vp.plugin.diagram.shape.IClassUIModel; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.IProject; -import com.vp.plugin.model.factory.IModelElementFactory; - -import it.unibz.inf.ontouml.vp.model.Class; - -/** - * Implementation of the coloring feature - * - * @author Victor Viola - * @author Claudenir Fonseca - * @author Tiago Prince Sales - */ -public class SmartColoring { - - public static final Color COLOR_FOR_ABSTRACT = new Color(255, 255, 255); - public static final Color COLOR_FOR_COLLECTIVE = new Color(255, 218, 221); - public static final Color COLOR_FOR_COLLECTIVE_DARK = new Color(255, 153, 163); - public static final Color COLOR_FOR_EVENT = new Color(252, 252, 212); - public static final Color COLOR_FOR_SITUATION = new Color(252, 252, 212); - public static final Color COLOR_FOR_MODE = new Color(192, 237, 255); - public static final Color COLOR_FOR_MODE_DARK = new Color(112, 215, 255); - public static final Color COLOR_FOR_FUNCTIONAL_COMPLEX = new Color(255, 218, 221); - public static final Color COLOR_FOR_FUNCTIONAL_COMPLEX_DARK = new Color(255, 153, 163); - public static final Color COLOR_FOR_QUALITY = new Color(192, 237, 255); - public static final Color COLOR_FOR_QUALITY_DARK = new Color(112, 215, 255); - public static final Color COLOR_FOR_QUANTITY = new Color(255, 218, 221); - public static final Color COLOR_FOR_QUANTITY_DARK = new Color(255, 153, 163); - public static final Color COLOR_FOR_RELATOR = new Color(211, 255, 211); - public static final Color COLOR_FOR_RELATOR_DARK = new Color(153, 255, 153); - public static final Color COLOR_FOR_TYPE = new Color(211, 211, 252); - public static final Color COLOR_FOR_NON_SPECIFIC = new Color(224, 224, 224); - - /** - * Runs twice over the diagram and paint all the elements. - */ - public static void paintAll() { - if (!Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled()) { - return; - } - - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - final IModelElement[] modelElements = project - .toAllLevelModelElementArray(IModelElementFactory.MODEL_TYPE_CLASS); - - for (int j = 0; modelElements != null && j < modelElements.length; j++) { - SmartColoring.paint((IClass) modelElements[j]); - } - } - - /** - * Paints occurrences of a class based on the "restrictTo" meta-property. - * Affects class occurrences in all diagrams. No effect whenever auto-coloring - * is disabled or color is null. - * - * @param _class - */ - public static void paint(IClass _class) { - if (!Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled()) { - return; - } - - final Color defaultColor = getColor(_class); - - if (defaultColor == null) { - return; - } - - for (IDiagramElement classView : _class.getDiagramElements()) { - if (classView instanceof IClassUIModel) { - ((IClassUIModel) classView).getFillColor().setColor1(defaultColor); - } - } - } - - public static void paint(IClassUIModel classDiagramElement) { - final IClass _class = classDiagramElement.getModelElement() instanceof IClass - ? (IClass) classDiagramElement.getModelElement() - : null; - final Color defaultColor = getColor(_class); - - if (defaultColor != null) { - classDiagramElement.getFillColor().setColor1(defaultColor); - } - } - - /** - * Returns the color of a class based on its nature - * - * @param _class the class to be painted - * @return the color of the class - */ - private static Color getColor(IClass _class) { - final String stereotype = StereotypeUtils.getUniqueStereotypeName(_class); - String restrictedTo = Class.getRestrictedTo(_class); - - if (restrictedTo == null || restrictedTo.isEmpty()) { - final Set allStereotypes = StereotypeUtils.getOntoUMLClassStereotypeNames(); - - if (!allStereotypes.contains(stereotype)) { - return null; - } else { - return COLOR_FOR_NON_SPECIFIC; - } - } - - final Set ultimateSortalStereotypes = StereotypeUtils.getUltimateSortalStereotypeNames(); - - switch (restrictedTo) { - case StereotypeUtils.RESTRICTED_TO_ABSTRACT: - return COLOR_FOR_ABSTRACT; - case StereotypeUtils.RESTRICTED_TO_COLLECTIVE: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_COLLECTIVE_DARK : COLOR_FOR_COLLECTIVE; - case StereotypeUtils.RESTRICTED_TO_EVENT: - return COLOR_FOR_EVENT; - case StereotypeUtils.RESTRICTED_TO_SITUATION: - return COLOR_FOR_SITUATION; - case StereotypeUtils.RESTRICTED_TO_MODE: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_MODE_DARK : COLOR_FOR_MODE; - case StereotypeUtils.RESTRICTED_TO_FUNCTIONAL_COMPLEX: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_FUNCTIONAL_COMPLEX_DARK - : COLOR_FOR_FUNCTIONAL_COMPLEX; - case StereotypeUtils.RESTRICTED_TO_QUALITY: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_QUALITY_DARK : COLOR_FOR_QUALITY; - case StereotypeUtils.RESTRICTED_TO_QUANTITY: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_QUANTITY_DARK : COLOR_FOR_QUANTITY; - case StereotypeUtils.RESTRICTED_TO_RELATOR: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_RELATOR_DARK : COLOR_FOR_RELATOR; - case StereotypeUtils.RESTRICTED_TO_TYPE: - return COLOR_FOR_TYPE; - } - - final List restrictedToList = Arrays.stream(restrictedTo.split("\\s+")).map(s -> s.trim()) - .collect(Collectors.toList()); - - final List objectNatures = Arrays.asList(StereotypeUtils.RESTRICTED_TO_FUNCTIONAL_COMPLEX, - StereotypeUtils.RESTRICTED_TO_COLLECTIVE, StereotypeUtils.RESTRICTED_TO_QUANTITY); - - if (objectNatures.containsAll(restrictedToList)) { - return COLOR_FOR_FUNCTIONAL_COMPLEX; - } - - final List intrinsicNature = Arrays.asList(StereotypeUtils.RESTRICTED_TO_MODE, - StereotypeUtils.RESTRICTED_TO_QUALITY); - - if (intrinsicNature.containsAll(restrictedToList)) { - return COLOR_FOR_MODE; - } - - return COLOR_FOR_NON_SPECIFIC; - } -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoringUtils.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoringUtils.java new file mode 100644 index 00000000..40f2e50e --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoringUtils.java @@ -0,0 +1,154 @@ +package it.unibz.inf.ontouml.vp.utils; + +import com.vp.plugin.diagram.IDiagramElement; +import com.vp.plugin.diagram.shape.IClassUIModel; +import com.vp.plugin.model.IClass; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.uml.Class; +import it.unibz.inf.ontouml.vp.model.uml.ModelElement; +import java.awt.Color; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Implementation of the coloring feature + * + * @author Victor Viola + * @author Claudenir Fonseca + * @author Tiago Prince Sales + */ +public class SmartColoringUtils { + + private static final Color GREEN = new Color(153, 255, 153); + private static final Color LIGHT_GREEN = new Color(211, 255, 211); + private static final Color PINK = new Color(255, 153, 163); + private static final Color LIGHT_PINK = new Color(255, 218, 221); + private static final Color BLUE = new Color(112, 215, 255); + private static final Color LIGHT_BLUE = new Color(192, 237, 255); + private static final Color WHITE = new Color(255, 255, 255); + private static final Color YELLOW = new Color(252, 252, 212); + private static final Color ORANGE = new Color(252, 224, 192); + private static final Color PURPLE = new Color(211, 211, 252); + private static final Color GREY = new Color(224, 224, 224); + + private static final Color COLOR_RELATOR = GREEN; + private static final Color COLOR_RELATOR_ALTERNATIVE = LIGHT_GREEN; + private static final Color COLOR_EXTRINSIC_MODE = GREEN; + private static final Color COLOR_EXTRINSIC_MODE_ALTERNATIVE = LIGHT_GREEN; + private static final Color COLOR_FUNCTIONAL_COMPLEX = PINK; + private static final Color COLOR_FUNCTIONAL_COMPLEX_ALTERNATIVE = LIGHT_PINK; + private static final Color COLOR_COLLECTIVE = PINK; + private static final Color COLOR_COLLECTIVE_ALTERNATIVE = LIGHT_PINK; + private static final Color COLOR_QUANTITY = PINK; + private static final Color COLOR_QUANTITY_ALTERNATIVE = LIGHT_PINK; + private static final Color COLOR_INTRINSIC_MODE = BLUE; + private static final Color COLOR_INTRINSIC_MODE_ALTERNATIVE = LIGHT_BLUE; + private static final Color COLOR_QUALITY = BLUE; + private static final Color COLOR_QUALITY_ALTERNATIVE = LIGHT_BLUE; + private static final Color COLOR_ABSTRACT = WHITE; + private static final Color COLOR_EVENT = YELLOW; + private static final Color COLOR_SITUATION = ORANGE; + private static final Color COLOR_TYPE = PURPLE; + private static final Color COLOR_NON_SPECIFIC = GREY; + + private static final Map mainColorMap; + private static final Map alternativeColorMap; + + static { + mainColorMap = new HashMap<>(); + mainColorMap.put(RestrictedTo.RELATOR, COLOR_RELATOR); + mainColorMap.put(RestrictedTo.EXTRINSIC_MODE, COLOR_EXTRINSIC_MODE); + mainColorMap.put(RestrictedTo.INTRINSIC_MODE, COLOR_INTRINSIC_MODE); + mainColorMap.put(RestrictedTo.QUALITY, COLOR_QUALITY); + mainColorMap.put(RestrictedTo.FUNCTIONAL_COMPLEX, COLOR_FUNCTIONAL_COMPLEX); + mainColorMap.put(RestrictedTo.COLLECTIVE, COLOR_COLLECTIVE); + mainColorMap.put(RestrictedTo.QUANTITY, COLOR_QUANTITY); + mainColorMap.put(RestrictedTo.EVENT, COLOR_EVENT); + mainColorMap.put(RestrictedTo.SITUATION, COLOR_SITUATION); + mainColorMap.put(RestrictedTo.ABSTRACT, COLOR_ABSTRACT); + mainColorMap.put(RestrictedTo.TYPE, COLOR_TYPE); + + alternativeColorMap = new HashMap<>(); + alternativeColorMap.put(RestrictedTo.RELATOR, COLOR_RELATOR_ALTERNATIVE); + alternativeColorMap.put(RestrictedTo.EXTRINSIC_MODE, COLOR_EXTRINSIC_MODE_ALTERNATIVE); + alternativeColorMap.put(RestrictedTo.INTRINSIC_MODE, COLOR_INTRINSIC_MODE_ALTERNATIVE); + alternativeColorMap.put(RestrictedTo.QUALITY, COLOR_QUALITY_ALTERNATIVE); + alternativeColorMap.put(RestrictedTo.FUNCTIONAL_COMPLEX, COLOR_FUNCTIONAL_COMPLEX_ALTERNATIVE); + alternativeColorMap.put(RestrictedTo.COLLECTIVE, COLOR_COLLECTIVE_ALTERNATIVE); + alternativeColorMap.put(RestrictedTo.QUANTITY, COLOR_QUANTITY_ALTERNATIVE); + alternativeColorMap.put(RestrictedTo.EVENT, COLOR_EVENT); + alternativeColorMap.put(RestrictedTo.SITUATION, COLOR_SITUATION); + alternativeColorMap.put(RestrictedTo.ABSTRACT, COLOR_ABSTRACT); + alternativeColorMap.put(RestrictedTo.TYPE, COLOR_TYPE); + } + + /** + * Returns the color of a class based on its nature + * + * @param _class the class to be painted + * @return the color of the class + */ + private static Color getColor(IClass _class) { + final String stereotype = ModelElement.getUniqueStereotypeName(_class); + final List restrictedTo = Class.getRestrictedToList(_class); + + final List allStereotypes = Stereotype.getOntoUMLClassStereotypeNames(); + if (restrictedTo.isEmpty()) { + return allStereotypes.contains(stereotype) ? COLOR_NON_SPECIFIC : null; + } + + final boolean isUltimateSortal = + Stereotype.getUltimateSortalStereotypeNames().contains(stereotype); + if (restrictedTo.size() == 1) { + String nature = restrictedTo.get(0); + return isUltimateSortal ? mainColorMap.get(nature) : alternativeColorMap.get(nature); + } + + final List differentColors = + restrictedTo.stream() + .map(s -> isUltimateSortal ? mainColorMap.get(s) : alternativeColorMap.get(s)) + .distinct() + .collect(Collectors.toList()); + + return differentColors.size() == 1 ? differentColors.get(0) : COLOR_NON_SPECIFIC; + } + + /** + * Paints occurrences of a class based on the "restrictTo" meta-property. Affects class + * occurrences in all diagrams. No effect whenever auto-coloring is disabled or color is + * null. + * + * @param _class + */ + public static void paint(IClass _class) { + if (!Configurations.getInstance().getProjectConfigurations().isAutomaticColoringEnabled()) { + return; + } + + final Color defaultColor = getColor(_class); + + if (defaultColor == null) { + return; + } + + for (IDiagramElement classView : _class.getDiagramElements()) { + if (classView instanceof IClassUIModel) { + ((IClassUIModel) classView).getFillColor().setColor1(defaultColor); + } + } + } + + public static void paint(IClassUIModel classDiagramElement) { + final IClass _class = + classDiagramElement.getModelElement() instanceof IClass + ? (IClass) classDiagramElement.getModelElement() + : null; + final Color defaultColor = getColor(_class); + + if (defaultColor != null) { + classDiagramElement.getFillColor().setColor1(defaultColor); + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartModelling.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartModelling.java deleted file mode 100644 index ced12cf9..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartModelling.java +++ /dev/null @@ -1,324 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -import it.unibz.inf.ontouml.vp.features.constraints.AssociationConstraints; -import it.unibz.inf.ontouml.vp.features.constraints.ClassConstraints; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.AbstractMap.SimpleEntry; - -import com.vp.plugin.action.VPAction; -import com.vp.plugin.model.IAssociation; -import com.vp.plugin.model.IAssociationEnd; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.ISimpleRelationship; -import com.vp.plugin.model.factory.IModelElementFactory; - -public class SmartModelling { - - public static void setAggregationKind(IModelElement element) { - IAssociation association = (IAssociation) element; - IAssociationEnd compositionFromEnd = (IAssociationEnd) association.getFromEnd(); - IAssociationEnd compositionToEnd = (IAssociationEnd) association.getToEnd(); - - if (compositionToEnd.getAggregationKind().equals(IAssociationEnd.AGGREGATION_KIND_NONE)) { - compositionToEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_COMPOSITED); - } - - compositionFromEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); - - return; - } - - public static void removeAggregationKind(IModelElement element) { - IAssociationEnd compositionFromEnd = (IAssociationEnd) ((IAssociation) element).getFromEnd(); - IAssociationEnd compositionToEnd = (IAssociationEnd) ((IAssociation) element).getToEnd(); - - compositionFromEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); - compositionToEnd.setAggregationKind(IAssociationEnd.AGGREGATION_KIND_NONE); - - return; - } - - private static boolean setCardinalityIfEmpty(IAssociationEnd end, String cardinality) { - - if (end.getMultiplicity() == null || end.getMultiplicity().equals("Unspecified")) { - end.setMultiplicity(cardinality); - return true; - } else { - return false; - } - } - - private static String getTypeStereotype(IAssociationEnd associationEnd) { - String noStereotype = ""; - - try { - final IModelElement type = associationEnd.getTypeAsElement(); - - if (!type.getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS)) - return noStereotype; - - final String[] stereotypes = ((IClass) type).toStereotypeArray(); - - if (stereotypes != null && stereotypes.length == 1) - return stereotypes[0]; - - return noStereotype; - } catch (Exception e) { - return noStereotype; - } - } - - public static void setAssociationMetaProperties(IAssociation association) { - - IAssociationEnd source = (IAssociationEnd) association.getFromEnd(); - IAssociationEnd target = (IAssociationEnd) association.getToEnd(); - - if (source == null || target == null) - return; - - String sourceStereotype = getTypeStereotype(source); - String targetStereotype = getTypeStereotype(target); - - String[] stereotypes = association.toStereotypeArray(); - - if (stereotypes == null || stereotypes.length != 1) - return; - - switch (stereotypes[0]) { - case StereotypeUtils.STR_CHARACTERIZATION: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_COMPARATIVE: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "0..*"); - association.setDerived(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_COMPONENT_OF: - setCardinalityIfEmpty(source, "1..*"); - setCardinalityIfEmpty(target, "1"); - setAggregationKind(association); - return; - case StereotypeUtils.STR_MATERIAL: - if (targetStereotype.equals(StereotypeUtils.STR_ROLE) || targetStereotype.equals(StereotypeUtils.STR_ROLE_MIXIN)) - setCardinalityIfEmpty(source, "1..*"); - else - setCardinalityIfEmpty(source, "0..*"); - - if (sourceStereotype.equals(StereotypeUtils.STR_ROLE) || sourceStereotype.equals(StereotypeUtils.STR_ROLE_MIXIN)) - setCardinalityIfEmpty(target, "1..*"); - else - setCardinalityIfEmpty(target, "0..*"); - - association.setDerived(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_EXTERNAL_DEPENDENCE: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "1..*"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_MEDIATION: - if (targetStereotype.equals(StereotypeUtils.STR_ROLE) || targetStereotype.equals(StereotypeUtils.STR_ROLE_MIXIN)) - setCardinalityIfEmpty(source, "1..*"); - else - setCardinalityIfEmpty(source, "0..*"); - - setCardinalityIfEmpty(target, "1"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_MEMBER_OF: - setCardinalityIfEmpty(source, "1..*"); - setCardinalityIfEmpty(target, "1..*"); - setAggregationKind(association); - return; - case StereotypeUtils.STR_SUB_COLLECTION_OF: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - setAggregationKind(association); - return; - case StereotypeUtils.STR_SUB_QUANTITY_OF: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - source.setReadOnly(true); - setAggregationKind(association); - return; - case StereotypeUtils.STR_CREATION: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - source.setReadOnly(true); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_HISTORICAL_DEPENDENCE: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "1"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_MANIFESTATION: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "1..*"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_PARTICIPATION: - if ( - targetStereotype.equals(StereotypeUtils.STR_HISTORICAL_ROLE) || - targetStereotype.equals(StereotypeUtils.STR_HISTORICAL_ROLE_MIXIN) - ) - setCardinalityIfEmpty(source, "1..*"); - else - setCardinalityIfEmpty(source, "0..*"); - - setCardinalityIfEmpty(target, "1..*"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_PARTICIPATIONAL: - setCardinalityIfEmpty(source, "1..*"); - setCardinalityIfEmpty(target, "1"); - source.setReadOnly(true); - target.setReadOnly(true); - setAggregationKind(association); - return; - case StereotypeUtils.STR_TERMINATION: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - source.setReadOnly(true); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypeUtils.STR_INSTANTIATION: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "1..*"); - source.setReadOnly(true); - target.setReadOnly(true); - removeAggregationKind(association); - return; - } - } - - public static void setClassMetaProperties(IClass _class) { - if (_class == null) - return; - - String[] stereotypes = _class.toStereotypeArray(); - - if (stereotypes == null || stereotypes.length != 1) - return; - - switch (stereotypes[0]) { - case StereotypeUtils.STR_CATEGORY: - _class.setAbstract(true); - break; - case StereotypeUtils.STR_ROLE_MIXIN: - _class.setAbstract(true); - break; - case StereotypeUtils.STR_PHASE_MIXIN: - _class.setAbstract(true); - break; - case StereotypeUtils.STR_MIXIN: - _class.setAbstract(true); - break; - } - } - - public static void manageAssociationStereotypes(IAssociation association, VPAction action) { - - if (!association.getFrom().getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS)) - return; - - if (!association.getTo().getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS)) - return; - - final IClass source = (IClass) association.getFrom(); - final IClass target = (IClass) association.getTo(); - - final ArrayList sourceStereotypes = new ArrayList(Arrays.asList(source.toStereotypeArray())); - final ArrayList targetStereotypes = new ArrayList(Arrays.asList(target.toStereotypeArray())); - - if (sourceStereotypes.size() != 1 || targetStereotypes.size() != 1) { - // if any end has more than 1 stereotypes nothing is allowed - action.setEnabled(false); - return; - } - - // continue if both ends has ONLY ONE stereotype in both ends - final String sourceStereotype = sourceStereotypes.get(0); - final String targetStereotype = targetStereotypes.get(0); -// final ArrayList allowedCombinations = AssociationConstraints.allowedCombinations.get(new SimpleEntry(sourceStereotype, targetStereotype)); - final List allowedCombinations = AssociationConstraints.getAllowedActionIDs(sourceStereotype, targetStereotype); - - if (allowedCombinations == null || !allowedCombinations.contains(action.getActionId())) - action.setEnabled(false); - - return; - } - - public static void manageClassStereotypes(IClass _class, VPAction action) { - - final ISimpleRelationship[] relationshipsTo = _class.toToRelationshipArray(); - final ISimpleRelationship[] relationshipsFrom = _class.toFromRelationshipArray(); - - for (int i = 0; relationshipsTo != null && i < relationshipsTo.length; i++) { - final ISimpleRelationship relationshipTo = relationshipsTo[i]; - final String relationshipTypeTo = relationshipTo.getModelType(); - final String superClassType = relationshipTo.getFrom() != null ? relationshipTo.getFrom().getModelType() : ""; - - if (!(relationshipTypeTo.equals(IModelElementFactory.MODEL_TYPE_GENERALIZATION)) || !(superClassType.equals(IModelElementFactory.MODEL_TYPE_CLASS))) - continue; - - final IClass superClass = (IClass) relationshipTo.getFrom(); - final ArrayList superClassStereotypes = new ArrayList(Arrays.asList(superClass.toStereotypeArray())); - - if (superClassStereotypes.size()==0) - continue; - - if (superClassStereotypes.size() > 1) - action.setEnabled(false); - - final String superStereotype = superClassStereotypes.get(0); - final List allowedCombinationsSub = ClassConstraints.getAllowedActionIDsOnGeneral(superStereotype); - - if (allowedCombinationsSub == null || !allowedCombinationsSub.contains(action.getActionId())) - action.setEnabled(false); - } - - for (int i = 0; relationshipsFrom != null && i < relationshipsFrom.length; i++) { - final ISimpleRelationship relationshipFrom = relationshipsFrom[i]; - final String relationshipTypeFrom = relationshipFrom.getModelType(); - final String subClassType = relationshipFrom.getTo() != null ? relationshipFrom.getFrom().getModelType() : ""; - - if (!(relationshipTypeFrom.equals(IModelElementFactory.MODEL_TYPE_GENERALIZATION)) || !(subClassType.equals(IModelElementFactory.MODEL_TYPE_CLASS))) - continue; - - final IClass subClass = (IClass) relationshipFrom.getTo(); - final ArrayList subClassStereotypes = new ArrayList(Arrays.asList(subClass.toStereotypeArray())); - - if (subClassStereotypes.size()==0) - continue; - - if (subClassStereotypes.size() > 1) - action.setEnabled(false); - - final String subStereotype = subClassStereotypes.get(0); - final List allowedCombinationsSuper = ClassConstraints.getAllowedActionIDsOnSpecific(subStereotype); - - if (allowedCombinationsSuper == null || !allowedCombinationsSuper.contains(action.getActionId())) - action.setEnabled(false); - } - - return; - } - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/Stereotype.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/Stereotype.java new file mode 100644 index 00000000..1dfb8162 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/Stereotype.java @@ -0,0 +1,135 @@ +package it.unibz.inf.ontouml.vp.utils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Stereotype { + + // Class stereotypes + public static final String TYPE = "type"; + public static final String HISTORICAL_ROLE = "historicalRole"; + public static final String HISTORICAL_ROLE_MIXIN = "historicalRoleMixin"; + public static final String EVENT = "event"; + public static final String SITUATION = "situation"; + public static final String CATEGORY = "category"; + public static final String MIXIN = "mixin"; + public static final String ROLE_MIXIN = "roleMixin"; + public static final String PHASE_MIXIN = "phaseMixin"; + public static final String KIND = "kind"; + public static final String COLLECTIVE = "collective"; + public static final String QUANTITY = "quantity"; + public static final String RELATOR = "relator"; + public static final String QUALITY = "quality"; + public static final String MODE = "mode"; + public static final String SUBKIND = "subkind"; + public static final String ROLE = "role"; + public static final String PHASE = "phase"; + public static final String ENUMERATION = "enumeration"; + public static final String DATATYPE = "datatype"; + public static final String ABSTRACT = "abstract"; + + // Association stereotypes + public static final String MATERIAL = "material"; + public static final String DERIVATION = "derivation"; + public static final String COMPARATIVE = "comparative"; + public static final String MEDIATION = "mediation"; + public static final String CHARACTERIZATION = "characterization"; + public static final String EXTERNAL_DEPENDENCE = "externalDependence"; + public static final String COMPONENT_OF = "componentOf"; + public static final String MEMBER_OF = "memberOf"; + public static final String SUB_COLLECTION_OF = "subCollectionOf"; + public static final String SUB_QUANTITY_OF = "subQuantityOf"; + public static final String INSTANTIATION = "instantiation"; + public static final String TERMINATION = "termination"; + public static final String PARTICIPATIONAL = "participational"; + public static final String PARTICIPATION = "participation"; + public static final String HISTORICAL_DEPENDENCE = "historicalDependence"; + public static final String CREATION = "creation"; + public static final String MANIFESTATION = "manifestation"; + public static final String BRINGS_ABOUT = "bringsAbout"; + public static final String TRIGGERS = "triggers"; + + // Attribute stereotypes + public static final String BEGIN = "begin"; + public static final String END = "end"; + + public static List getOntoUMLClassStereotypeNames() { + return new ArrayList<>( + Arrays.asList( + TYPE, + HISTORICAL_ROLE, + HISTORICAL_ROLE_MIXIN, + EVENT, + SITUATION, + ENUMERATION, + DATATYPE, + ABSTRACT, + CATEGORY, + MIXIN, + ROLE_MIXIN, + PHASE_MIXIN, + KIND, + COLLECTIVE, + QUANTITY, + RELATOR, + QUALITY, + MODE, + SUBKIND, + ROLE, + PHASE)); + } + + public static List getOntoUMLAssociationStereotypeNames() { + return new ArrayList<>( + Arrays.asList( + INSTANTIATION, + TERMINATION, + PARTICIPATIONAL, + PARTICIPATION, + HISTORICAL_DEPENDENCE, + CREATION, + MANIFESTATION, + BRINGS_ABOUT, + TRIGGERS, + MATERIAL, + MEDIATION, + COMPARATIVE, + CHARACTERIZATION, + EXTERNAL_DEPENDENCE, + COMPONENT_OF, + MEMBER_OF, + SUB_COLLECTION_OF, + SUB_QUANTITY_OF)); + } + + public static List getOntoUMLAttributeStereotypeNames() { + return new ArrayList<>(Arrays.asList(BEGIN, END)); + } + + public static List getOntoUMLStereotypeNames() { + final List str_names = new ArrayList<>(); + + str_names.addAll(getOntoUMLAssociationStereotypeNames()); + str_names.addAll(getOntoUMLAttributeStereotypeNames()); + str_names.addAll(getOntoUMLClassStereotypeNames()); + + return str_names; + } + + public static List getNonSortalStereotypeNames() { + return new ArrayList<>(Arrays.asList(CATEGORY, MIXIN, ROLE_MIXIN, PHASE_MIXIN)); + } + + public static List getUltimateSortalStereotypeNames() { + return new ArrayList<>(Arrays.asList(KIND, COLLECTIVE, QUANTITY, RELATOR, QUALITY, MODE)); + } + + public static List getSortalStereotypeNames() { + return new ArrayList<>(Arrays.asList(SUBKIND, ROLE, PHASE, HISTORICAL_ROLE)); + } + + public static boolean isNonSortal(String stereotype) { + return getNonSortalStereotypeNames().contains(stereotype); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypeUtils.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypeUtils.java deleted file mode 100644 index e768ce25..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypeUtils.java +++ /dev/null @@ -1,567 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.IProject; -import com.vp.plugin.model.IStereotype; -import com.vp.plugin.model.ITaggedValue; -import com.vp.plugin.model.ITaggedValueContainer; -import com.vp.plugin.model.ITaggedValueDefinition; -import com.vp.plugin.model.ITaggedValueDefinitionContainer; -import com.vp.plugin.model.factory.IModelElementFactory; - -public class StereotypeUtils { - - public static Map STEREOTYPE_ELEMENTS = null; - - // Class stereotypes - public static final String STR_TYPE = "type"; - - public static final String STR_HISTORICAL_ROLE = "historicalRole"; - public static final String STR_HISTORICAL_ROLE_MIXIN = "historicalRoleMixin"; - public static final String STR_EVENT = "event"; - - public static final String STR_SITUATION = "situation"; - - public static final String STR_CATEGORY = "category"; - public static final String STR_MIXIN = "mixin"; - public static final String STR_ROLE_MIXIN = "roleMixin"; - public static final String STR_PHASE_MIXIN = "phaseMixin"; - - public static final String STR_KIND = "kind"; - public static final String STR_COLLECTIVE = "collective"; - public static final String STR_QUANTITY = "quantity"; - public static final String STR_RELATOR = "relator"; - public static final String STR_QUALITY = "quality"; - public static final String STR_MODE = "mode"; - - public static final String STR_SUBKIND = "subkind"; - public static final String STR_ROLE = "role"; - public static final String STR_PHASE = "phase"; - - public static final String STR_ENUMERATION = "enumeration"; - public static final String STR_DATATYPE = "datatype"; - - // Association stereotypes - public static final String STR_MATERIAL = "material"; - public static final String STR_DERIVATION = "derivation"; - public static final String STR_COMPARATIVE = "comparative"; - - public static final String STR_MEDIATION = "mediation"; - public static final String STR_CHARACTERIZATION = "characterization"; - public static final String STR_EXTERNAL_DEPENDENCE = "externalDependence"; - - public static final String STR_COMPONENT_OF = "componentOf"; - public static final String STR_MEMBER_OF = "memberOf"; - public static final String STR_SUB_COLLECTION_OF = "subCollectionOf"; - public static final String STR_SUB_QUANTITY_OF = "subQuantityOf"; - - public static final String STR_INSTANTIATION = "instantiation"; - - public static final String STR_TERMINATION = "termination"; - public static final String STR_PARTICIPATIONAL = "participational"; - public static final String STR_PARTICIPATION = "participation"; - public static final String STR_HISTORICAL_DEPENDENCE = "historicalDependence"; - public static final String STR_CREATION = "creation"; - public static final String STR_MANIFESTATION = "manifestation"; - - public static final String STR_BRINGS_ABOUT = "bringsAbout"; - public static final String STR_TRIGGERS = "triggers"; - - // Attribute stereotypes - public static final String STR_BEGIN = "begin"; - public static final String STR_END = "end"; - - // Ontological natures - public static final String RESTRICTED_TO_FUNCTIONAL_COMPLEX = "functional-complex"; - public static final String RESTRICTED_TO_COLLECTIVE = "collective"; - public static final String RESTRICTED_TO_QUANTITY = "quantity"; - public static final String RESTRICTED_TO_RELATOR = "relator"; - public static final String RESTRICTED_TO_MODE = "mode"; - public static final String RESTRICTED_TO_QUALITY = "quality"; - public static final String RESTRICTED_TO_EVENT = "event"; - public static final String RESTRICTED_TO_SITUATION = "situation"; - public static final String RESTRICTED_TO_TYPE = "type"; - public static final String RESTRICTED_TO_ABSTRACT = "abstract"; - - // Meta-properties names - public static final String PROPERTY_RESTRICTED_TO = "restrictedTo"; - public static final String PROPERTY_IS_EXTENSIONAL = "isExtensional"; - public static final String PROPERTY_IS_POWERTYPE = "isPowertype"; - public static final String PROPERTY_ORDER = "order"; - - public static List getOntoUMLTaggedValues() { - return Arrays.asList(PROPERTY_RESTRICTED_TO, PROPERTY_IS_EXTENSIONAL, - PROPERTY_IS_POWERTYPE, PROPERTY_ORDER); - } - - public static Set getOntoUMLClassStereotypeNames() { - final Set str_names = new HashSet<>(); - - str_names.add(STR_TYPE); - - str_names.add(STR_HISTORICAL_ROLE); - str_names.add(STR_HISTORICAL_ROLE_MIXIN); - str_names.add(STR_EVENT); - - str_names.add(STR_SITUATION); - - str_names.add(STR_ENUMERATION); - str_names.add(STR_DATATYPE); - - str_names.add(STR_CATEGORY); - str_names.add(STR_MIXIN); - str_names.add(STR_ROLE_MIXIN); - str_names.add(STR_PHASE_MIXIN); - str_names.add(STR_KIND); - str_names.add(STR_COLLECTIVE); - str_names.add(STR_QUANTITY); - str_names.add(STR_RELATOR); - str_names.add(STR_QUALITY); - str_names.add(STR_MODE); - str_names.add(STR_SUBKIND); - str_names.add(STR_ROLE); - str_names.add(STR_PHASE); - - return str_names; - } - - public static Set getOntoUMLAssociationStereotypeNames() { - final Set str_names = new HashSet<>(); - - str_names.add(STR_INSTANTIATION); - - str_names.add(STR_TERMINATION); - str_names.add(STR_PARTICIPATIONAL); - str_names.add(STR_PARTICIPATION); - str_names.add(STR_HISTORICAL_DEPENDENCE); - str_names.add(STR_CREATION); - str_names.add(STR_MANIFESTATION); - - str_names.add(STR_BRINGS_ABOUT); - str_names.add(STR_TRIGGERS); - - str_names.add(STR_MATERIAL); - str_names.add(STR_MEDIATION); - str_names.add(STR_COMPARATIVE); - str_names.add(STR_CHARACTERIZATION); - str_names.add(STR_EXTERNAL_DEPENDENCE); - str_names.add(STR_COMPONENT_OF); - str_names.add(STR_MEMBER_OF); - str_names.add(STR_SUB_COLLECTION_OF); - str_names.add(STR_SUB_QUANTITY_OF); - - return str_names; - } - - public static Set getOntoUMLAttributeStereotypeNames() { - final Set str_names = new HashSet<>(); - - str_names.add(STR_BEGIN); - str_names.add(STR_END); - - return str_names; - } - - public static Set getOntoUMLStereotypeNames() { - final Set str_names = new HashSet<>(); - - str_names.addAll(getOntoUMLAssociationStereotypeNames()); - str_names.addAll(getOntoUMLAttributeStereotypeNames()); - str_names.addAll(getOntoUMLClassStereotypeNames()); - - return str_names; - } - - public static Set getNonSortalStereotypeNames() { - final Set str_names = new HashSet(); - - str_names.add(STR_CATEGORY); - str_names.add(STR_MIXIN); - str_names.add(STR_ROLE_MIXIN); - str_names.add(STR_PHASE_MIXIN); - - return str_names; - } - - public static Set getUltimateSortalStereotypeNames() { - final Set str_names = new HashSet(); - - str_names.add(STR_KIND); - str_names.add(STR_COLLECTIVE); - str_names.add(STR_QUANTITY); - str_names.add(STR_RELATOR); - str_names.add(STR_QUALITY); - str_names.add(STR_MODE); - - return str_names; - } - - public static Set getSortalStereotypeNames() { - final Set str_names = new HashSet(); - - str_names.add(STR_SUBKIND); - str_names.add(STR_ROLE); - str_names.add(STR_PHASE); - str_names.add(STR_HISTORICAL_ROLE); - - return str_names; - } - - /** - * Method to be called whenever a project is opened to properly install all - * stereotypes. - */ - public static void generate() { - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - final IModelElement[] installedStereotypes = project.toAllLevelModelElementArray(IModelElementFactory.MODEL_TYPE_STEREOTYPE); - final Map stereotypesMap = new HashMap<>(); - final Set allStereotypeNames = getOntoUMLAssociationStereotypeNames(); - - allStereotypeNames.addAll(getOntoUMLAttributeStereotypeNames()); - allStereotypeNames.addAll(getOntoUMLClassStereotypeNames()); - - // Retrieves IStereotype objects for OntoUML elements - for (IModelElement stereotype : installedStereotypes){ - if (allStereotypeNames.contains(stereotype.getName())) { - stereotypesMap.put(stereotype.getName(), (IStereotype) stereotype); - } - } - - // Creates missing IStereotype objects for OntoUML classes - for (String ontoUMLClassStereotype : getOntoUMLClassStereotypeNames()) { - if (stereotypesMap.get(ontoUMLClassStereotype) == null) { - final IStereotype newStereotypeElement = IModelElementFactory.instance().createStereotype(); - newStereotypeElement.setName(ontoUMLClassStereotype); - newStereotypeElement.setBaseType(IModelElementFactory.MODEL_TYPE_CLASS); - stereotypesMap.put(ontoUMLClassStereotype, newStereotypeElement); - } - } - - for (String ontoUMLAssociationStereotype : getOntoUMLAssociationStereotypeNames()) { - if (stereotypesMap.get(ontoUMLAssociationStereotype) == null) { - final IStereotype newStereotypeElement = IModelElementFactory.instance().createStereotype(); - newStereotypeElement.setName(ontoUMLAssociationStereotype); - newStereotypeElement.setBaseType(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - stereotypesMap.put(ontoUMLAssociationStereotype, newStereotypeElement); - } - } - - for (String ontoUMLAttributeStereotype : getOntoUMLAttributeStereotypeNames()) { - if (stereotypesMap.get(ontoUMLAttributeStereotype) == null) { - final IStereotype newStereotypeElement = IModelElementFactory.instance().createStereotype(); - newStereotypeElement.setName(ontoUMLAttributeStereotype); - newStereotypeElement.setBaseType(IModelElementFactory.MODEL_TYPE_ATTRIBUTE); - stereotypesMap.put(ontoUMLAttributeStereotype, newStereotypeElement); - } - } - - // Checks and adds missing tagged value definitions to IStereotype objects - final Set taggedStereotypeNames = getOntoUMLClassStereotypeNames(); - - for (String stereotypeName : taggedStereotypeNames) { - final IStereotype stereotype = stereotypesMap.get(stereotypeName); - ITaggedValueDefinitionContainer definitionsContainer = stereotype.getTaggedValueDefinitions(); - - if (definitionsContainer == null) { - definitionsContainer = IModelElementFactory - .instance().createTaggedValueDefinitionContainer(); - } - - final ITaggedValueDefinition[] definitionsArray = definitionsContainer.toTaggedValueDefinitionArray(); - final Map definitions = new HashMap<>(); - - for (int j = 0; definitionsArray != null && j < definitionsArray.length; j++) { - definitions.put(definitionsArray[j].getName(), definitionsArray[j]); - } - - // Removes deprecated references to "allowed" - if (definitions.containsKey("allowed")) { - final ITaggedValueDefinition allowed = definitions.get("allowed"); - allowed.delete(); - } - - // Adds "restrictedTo" to all IStereotype objects - if (!definitions.containsKey(PROPERTY_RESTRICTED_TO)) { - final ITaggedValueDefinition restrictedTo = IModelElementFactory.instance().createTaggedValueDefinition(); - restrictedTo.setName(PROPERTY_RESTRICTED_TO); - restrictedTo.setType(ITaggedValueDefinition.TYPE_TEXT); - restrictedTo.setDefaultValue(getDefaultRestrictedTo(stereotypeName)); - restrictedTo.setTagDefStereotype(stereotype); - definitionsContainer.addTaggedValueDefinition(restrictedTo); - } - - // Adds "isExtensional" to all STR_COLLECTIVE IStereotype - if ( - stereotype.getName().equals(STR_COLLECTIVE) && - !definitions.containsKey(PROPERTY_IS_EXTENSIONAL) - ) { - final ITaggedValueDefinition isExtensional = IModelElementFactory.instance() - .createTaggedValueDefinition(); - isExtensional.setName(PROPERTY_IS_EXTENSIONAL); - isExtensional.setType(ITaggedValueDefinition.TYPE_BOOLEAN); - isExtensional.setDefaultValue("false"); - isExtensional.setTagDefStereotype(stereotype); - definitionsContainer.addTaggedValueDefinition(isExtensional); - } - - // Adds "isPowertype" to all STR_TYPE IStereotype - if ( - stereotype.getName().equals(STR_TYPE) && - !definitions.containsKey(PROPERTY_IS_POWERTYPE) - ) { - final ITaggedValueDefinition isPowertype = IModelElementFactory.instance() - .createTaggedValueDefinition(); - isPowertype.setName(PROPERTY_IS_POWERTYPE); - isPowertype.setType(ITaggedValueDefinition.TYPE_BOOLEAN); - isPowertype.setDefaultValue("false"); - isPowertype.setTagDefStereotype(stereotype); - definitionsContainer.addTaggedValueDefinition(isPowertype); - } - - // Adds "order" to all STR_TYPE IStereotype - if ( - stereotype.getName().equals(STR_TYPE) && - !definitions.containsKey(PROPERTY_ORDER) - ) { - final ITaggedValueDefinition order = IModelElementFactory.instance().createTaggedValueDefinition(); - order.setName(PROPERTY_ORDER); - order.setType(ITaggedValueDefinition.TYPE_TEXT); - order.setDefaultValue("2"); - order.setTagDefStereotype(stereotype); - definitionsContainer.addTaggedValueDefinition(order); - } - - stereotype.setTaggedValueDefinitions(definitionsContainer); - } - - // generated() is called when any project is "newed" (which includes opening) - // and may trigger a NullPointerException when the project is in fact new - // so we have to be sure that the map is null until it is properly updated - STEREOTYPE_ELEMENTS = stereotypesMap; - } - - public static String getRestrictions() { - return getRestrictionsList() - .stream() - .sorted() - .collect(Collectors.joining(" ")); - } - - public static List getRestrictionsList() { - return Arrays.asList(RESTRICTED_TO_COLLECTIVE, RESTRICTED_TO_EVENT, RESTRICTED_TO_SITUATION, RESTRICTED_TO_MODE, - RESTRICTED_TO_FUNCTIONAL_COMPLEX, RESTRICTED_TO_QUALITY, RESTRICTED_TO_QUANTITY, RESTRICTED_TO_RELATOR, - RESTRICTED_TO_TYPE, RESTRICTED_TO_ABSTRACT); - } - - public static void applyStereotype(IModelElement element, String stereotypeName) { - final IStereotype stereotype = getStereotype(stereotypeName); - - // TODO: check the necessity of throwing some exception here - if (stereotype == null || !element.getModelType().equals(stereotype.getBaseType())){ - return; - } - - System.out.println("\nStereotype: " + stereotype.getName()); - ITaggedValueDefinitionContainer definitionContainer = stereotype.getTaggedValueDefinitions(); - if (definitionContainer != null) { - Iterator iterator = definitionContainer.taggedValueDefinitionIterator(); - while (iterator != null && iterator.hasNext()) { - ITaggedValueDefinition definition = (ITaggedValueDefinition) iterator.next(); - System.out.println("\tDefined tagged value: " + definition.getName()); - } - } - - IModelElementFactory factory = IModelElementFactory.instance(); - ITaggedValueContainer container = element.getTaggedValues(); - Map taggedValueMap = new HashMap<>(); - - if (container == null) { - container = factory.createTaggedValueContainer(); - element.setTaggedValues(container); - } - - if (element instanceof IClass) { - int count = element.getTaggedValues().taggedValueCount(); - System.out.println("Initial number of tagged values: " + count); - ITaggedValue[] taggedValues = container.toTaggedValueArray(); - - // 1. Saves and deletes tagged values associated to a stereotype - for (ITaggedValue tv : taggedValues) { - final boolean isAllowedTag = tv.getName().equals("allowed"); - final boolean isOntoUMLTag = getOntoUMLTaggedValues().contains(tv.getName()); - final boolean isAssociatedToStereotype = tv.getTagDefinition() != null; - - if (isAllowedTag) { - System.out.println(tv.getName() + ": allowed"); - taggedValueMap.put(tv.getName(), tv.getValue()); - container.removeTaggedValue(tv); - tv.delete(); - } else if (isOntoUMLTag) { - // It does not remove non-OntoUML tags - System.out.println(tv.getName() + ": has tag definition"); - - if (isAssociatedToStereotype){ - taggedValueMap.put(tv.getName(), tv.getValue()); - } - - container.removeTaggedValue(tv); - tv.delete(); - } - } - - } - - // 2. Removes old stereotypes - if (element.stereotypeCount() > 0) { - for (IStereotype s : element.toStereotypeModelArray()) { - element.removeStereotype(s); - } - } - - // 3. Adds new stereotype - element.addStereotype(stereotype); - - // 4. Reapply values of tagged values related to the stereotypes (e.g. restrictedTo, order, isPowertype, isExtensional) - if (element.getTaggedValues() != null) { - int count = element.getTaggedValues().taggedValueCount(); - System.out.println("Number of tagged values: " + count); - ITaggedValue[] taggedValues = element.getTaggedValues().toTaggedValueArray(); - - for (ITaggedValue taggedValue : taggedValues) { - Object oldValue = taggedValueMap.get(taggedValue.getName()); - if (oldValue != null) { - taggedValue.setValue(oldValue.toString()); - } - } - - System.out.println("Number of tagged values: " + count); - } - } - - public static String getDefaultRestrictedTo(String stereotype) { - switch (stereotype) { - case STR_TYPE: - return RESTRICTED_TO_TYPE; - case STR_EVENT: - return RESTRICTED_TO_EVENT; - case STR_SITUATION: - return RESTRICTED_TO_SITUATION; - case STR_CATEGORY: - case STR_MIXIN: - case STR_ROLE_MIXIN: - case STR_PHASE_MIXIN: - case STR_HISTORICAL_ROLE_MIXIN: - return RESTRICTED_TO_FUNCTIONAL_COMPLEX; - case STR_KIND: - return RESTRICTED_TO_FUNCTIONAL_COMPLEX; - case STR_COLLECTIVE: - return RESTRICTED_TO_COLLECTIVE; - case STR_QUANTITY: - return RESTRICTED_TO_QUANTITY; - case STR_RELATOR: - return RESTRICTED_TO_RELATOR; - case STR_QUALITY: - return RESTRICTED_TO_QUALITY; - case STR_MODE: - return RESTRICTED_TO_MODE; - case STR_ENUMERATION: - case STR_DATATYPE: - return RESTRICTED_TO_ABSTRACT; - case STR_SUBKIND: - case STR_ROLE: - case STR_PHASE: - case STR_HISTORICAL_ROLE: - default: - return ""; - } - } - - public static ITaggedValue reapplyStereotypeAndGetTaggedValue(IClass _class, String taggedValueName) { - reapplyCurrentStereotype(_class); - - ITaggedValue taggedValue = getTaggedValue(_class, taggedValueName); - if (taggedValue == null) - return null; - - //Retrieves desired tagged value - return getTaggedValue(_class, taggedValueName); - } - - public static boolean reapplyCurrentStereotype(IClass _class) { - String stereotype = _class.toStereotypeArray() != null && _class.toStereotypeArray().length > 0 ? - _class.toStereotypeArray()[0] : null; - - // Escape in case the stereotype is missing or incorrect - if (stereotype == null || !getOntoUMLClassStereotypeNames().contains(stereotype)) - return false; - - System.out.println("Reapplying " + stereotype + " to " + _class.getName()); - // Reapply stereotype making sure that the tagged values are there - applyStereotype(_class, stereotype); - - return true; - } - - public static ITaggedValue getTaggedValue(IModelElement element, String name) { - ITaggedValueContainer container = element.getTaggedValues(); - - if (container == null) - return null; - - try { - return container.getTaggedValueByName(name); - } catch (Exception e) { - return null; - } - } - - public static void deleteTaggedValue(IModelElement element, String name) { - ITaggedValueContainer container = element.getTaggedValues(); - - if (container != null) { - ITaggedValue[] taggedValues = container.toTaggedValueArray(); - for (ITaggedValue tv : taggedValues) { - if (tv.getName().equals(name)) - tv.delete(); - } - } - } - - public static String getUniqueStereotypeName(IModelElement element) { - return element.stereotypeCount() == 1 ? - element.toStereotypeModelArray()[0].getName() : - null; - } - - public static IStereotype getUniqueStereotype(IModelElement element) { - return element.stereotypeCount() == 1 ? - element.toStereotypeModelArray()[0] : - null; - } - - public static IStereotype getStereotype(String stereotypeName) { - IStereotype stereotype = STEREOTYPE_ELEMENTS.get(stereotypeName); - - if( - stereotype == null && - getOntoUMLStereotypeNames().contains(stereotypeName) - ) { - generate(); - stereotype = STEREOTYPE_ELEMENTS.get(stereotypeName); - } - - return stereotype; - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypesManager.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypesManager.java new file mode 100644 index 00000000..abe9899b --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypesManager.java @@ -0,0 +1,302 @@ +package it.unibz.inf.ontouml.vp.utils; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.IProject; +import com.vp.plugin.model.IStereotype; +import com.vp.plugin.model.ITaggedValue; +import com.vp.plugin.model.ITaggedValueContainer; +import com.vp.plugin.model.ITaggedValueDefinition; +import com.vp.plugin.model.ITaggedValueDefinitionContainer; +import com.vp.plugin.model.factory.IModelElementFactory; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class StereotypesManager { + + private static Map STEREOTYPE_ELEMENTS = null; + + // Meta-properties names + public static final String PROPERTY_RESTRICTED_TO = "restrictedTo"; + public static final String PROPERTY_IS_EXTENSIONAL = "isExtensional"; + public static final String PROPERTY_IS_POWERTYPE = "isPowertype"; + public static final String PROPERTY_ORDER = "order"; + + public static List getOntoUMLTaggedValues() { + return Arrays.asList( + PROPERTY_RESTRICTED_TO, PROPERTY_IS_EXTENSIONAL, PROPERTY_IS_POWERTYPE, PROPERTY_ORDER); + } + + /** Method to be called whenever a project is opened to properly install all stereotypes. */ + public static void generate() { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + final IModelElement[] installedStereotypes = + project.toAllLevelModelElementArray(IModelElementFactory.MODEL_TYPE_STEREOTYPE); + final Map stereotypesMap = new HashMap<>(); + final List allStereotypeNames = Stereotype.getOntoUMLAssociationStereotypeNames(); + + allStereotypeNames.addAll(Stereotype.getOntoUMLAttributeStereotypeNames()); + allStereotypeNames.addAll(Stereotype.getOntoUMLClassStereotypeNames()); + + // Retrieves IStereotype objects for OntoUML elements + for (IModelElement stereotype : installedStereotypes) { + if (allStereotypeNames.contains(stereotype.getName())) { + stereotypesMap.put(stereotype.getName(), (IStereotype) stereotype); + } + } + + // Creates missing IStereotype objects for OntoUML classes + for (String ontoUMLClassStereotype : Stereotype.getOntoUMLClassStereotypeNames()) { + if (stereotypesMap.get(ontoUMLClassStereotype) == null) { + final IStereotype newStereotypeElement = IModelElementFactory.instance().createStereotype(); + newStereotypeElement.setName(ontoUMLClassStereotype); + newStereotypeElement.setBaseType(IModelElementFactory.MODEL_TYPE_CLASS); + stereotypesMap.put(ontoUMLClassStereotype, newStereotypeElement); + } + } + + for (String ontoUMLAssociationStereotype : Stereotype.getOntoUMLAssociationStereotypeNames()) { + if (stereotypesMap.get(ontoUMLAssociationStereotype) == null) { + final IStereotype newStereotypeElement = IModelElementFactory.instance().createStereotype(); + newStereotypeElement.setName(ontoUMLAssociationStereotype); + newStereotypeElement.setBaseType(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + stereotypesMap.put(ontoUMLAssociationStereotype, newStereotypeElement); + } + } + + for (String ontoUMLAttributeStereotype : Stereotype.getOntoUMLAttributeStereotypeNames()) { + if (stereotypesMap.get(ontoUMLAttributeStereotype) == null) { + final IStereotype newStereotypeElement = IModelElementFactory.instance().createStereotype(); + newStereotypeElement.setName(ontoUMLAttributeStereotype); + newStereotypeElement.setBaseType(IModelElementFactory.MODEL_TYPE_ATTRIBUTE); + stereotypesMap.put(ontoUMLAttributeStereotype, newStereotypeElement); + } + } + + // Checks and adds missing tagged value definitions to IStereotype objects + final List taggedStereotypeNames = Stereotype.getOntoUMLClassStereotypeNames(); + + for (String stereotypeName : taggedStereotypeNames) { + final IStereotype stereotype = stereotypesMap.get(stereotypeName); + ITaggedValueDefinitionContainer definitionsContainer = stereotype.getTaggedValueDefinitions(); + + if (definitionsContainer == null) { + definitionsContainer = + IModelElementFactory.instance().createTaggedValueDefinitionContainer(); + } + + final ITaggedValueDefinition[] definitionsArray = + definitionsContainer.toTaggedValueDefinitionArray(); + final Map definitions = new HashMap<>(); + + for (int j = 0; definitionsArray != null && j < definitionsArray.length; j++) { + definitions.put(definitionsArray[j].getName(), definitionsArray[j]); + } + + // Removes deprecated references to "allowed" + if (definitions.containsKey("allowed")) { + final ITaggedValueDefinition allowed = definitions.get("allowed"); + allowed.delete(); + } + + // Adds "restrictedTo" to all IStereotype objects + if (!definitions.containsKey(PROPERTY_RESTRICTED_TO)) { + final ITaggedValueDefinition restrictedTo = + IModelElementFactory.instance().createTaggedValueDefinition(); + restrictedTo.setName(PROPERTY_RESTRICTED_TO); + restrictedTo.setType(ITaggedValueDefinition.TYPE_TEXT); + restrictedTo.setDefaultValue(RestrictedTo.getDefaultRestrictedTo(stereotypeName)); + restrictedTo.setTagDefStereotype(stereotype); + definitionsContainer.addTaggedValueDefinition(restrictedTo); + } + + // Adds "isExtensional" to all IStereotype where + // RestrictedTo.COLLECTIVE is a possible value + List possibleRestrictedToValues = + RestrictedTo.possibleRestrictedToValues(stereotypeName); + if (possibleRestrictedToValues.contains(RestrictedTo.COLLECTIVE) + && !definitions.containsKey(PROPERTY_IS_EXTENSIONAL)) { + final ITaggedValueDefinition isExtensional = + IModelElementFactory.instance().createTaggedValueDefinition(); + isExtensional.setName(PROPERTY_IS_EXTENSIONAL); + isExtensional.setType(ITaggedValueDefinition.TYPE_BOOLEAN); + isExtensional.setDefaultValue("false"); + isExtensional.setTagDefStereotype(stereotype); + definitionsContainer.addTaggedValueDefinition(isExtensional); + } + + // Adds "isPowertype" to all STR_TYPE IStereotype + if (stereotype.getName().equals(Stereotype.TYPE) + && !definitions.containsKey(PROPERTY_IS_POWERTYPE)) { + final ITaggedValueDefinition isPowertype = + IModelElementFactory.instance().createTaggedValueDefinition(); + isPowertype.setName(PROPERTY_IS_POWERTYPE); + isPowertype.setType(ITaggedValueDefinition.TYPE_BOOLEAN); + isPowertype.setDefaultValue("false"); + isPowertype.setTagDefStereotype(stereotype); + definitionsContainer.addTaggedValueDefinition(isPowertype); + } + + // Adds "order" to all STR_TYPE IStereotype + if (stereotype.getName().equals(Stereotype.TYPE) + && !definitions.containsKey(PROPERTY_ORDER)) { + final ITaggedValueDefinition order = + IModelElementFactory.instance().createTaggedValueDefinition(); + order.setName(PROPERTY_ORDER); + order.setType(ITaggedValueDefinition.TYPE_TEXT); + order.setDefaultValue("2"); + order.setTagDefStereotype(stereotype); + definitionsContainer.addTaggedValueDefinition(order); + } + + stereotype.setTaggedValueDefinitions(definitionsContainer); + } + + System.out.println("KEYS: " + stereotypesMap.keySet()); + + // generated() is called when any project is "newed" (which includes opening) + // and may trigger a NullPointerException when the project is in fact new + // so we have to be sure that the map is null until it is properly updated + STEREOTYPE_ELEMENTS = stereotypesMap; + } + + public static void applyStereotype(IModelElement element, String stereotypeName) { + final IStereotype stereotype = getStereotype(stereotypeName); + + if (stereotype == null || !element.getModelType().equals(stereotype.getBaseType())) { + return; + } + + System.out.println("\nStereotype: " + stereotype.getName()); + ITaggedValueDefinitionContainer definitionContainer = stereotype.getTaggedValueDefinitions(); + if (definitionContainer != null) { + Iterator iterator = definitionContainer.taggedValueDefinitionIterator(); + while (iterator != null && iterator.hasNext()) { + ITaggedValueDefinition definition = (ITaggedValueDefinition) iterator.next(); + System.out.println("\tDefined tagged value: " + definition.getName()); + } + } + + IModelElementFactory factory = IModelElementFactory.instance(); + ITaggedValueContainer container = element.getTaggedValues(); + Map taggedValueMap = new HashMap<>(); + + if (container == null) { + container = factory.createTaggedValueContainer(); + element.setTaggedValues(container); + } + + if (element instanceof IClass) { + int count = element.getTaggedValues().taggedValueCount(); + System.out.println("Initial number of tagged values: " + count); + ITaggedValue[] taggedValues = container.toTaggedValueArray(); + + // 1. Saves and deletes tagged values associated to a stereotype + for (ITaggedValue tv : taggedValues) { + final boolean isAllowedTag = tv.getName().equals("allowed"); + final boolean isOntoUMLTag = getOntoUMLTaggedValues().contains(tv.getName()); + final boolean isAssociatedToStereotype = tv.getTagDefinition() != null; + + if (isAllowedTag) { + System.out.println(tv.getName() + ": allowed"); + taggedValueMap.put(tv.getName(), tv.getValue()); + container.removeTaggedValue(tv); + tv.delete(); + } else if (isOntoUMLTag) { + // It does not remove non-OntoUML tags + System.out.println(tv.getName() + ": has tag definition"); + + if (isAssociatedToStereotype) { + taggedValueMap.put(tv.getName(), tv.getValue()); + } + + container.removeTaggedValue(tv); + tv.delete(); + } + } + } + + // 2. Removes old stereotypes + if (element.stereotypeCount() > 0) { + for (IStereotype s : element.toStereotypeModelArray()) { + element.removeStereotype(s); + } + } + + // 3. Adds new stereotype + element.addStereotype(stereotype); + + // 4. Reapply values of tagged values related to the stereotypes (e.g. restrictedTo, order, + // isPowertype, isExtensional) + if (element.getTaggedValues() != null) { + int count = element.getTaggedValues().taggedValueCount(); + System.out.println("Number of tagged values: " + count); + ITaggedValue[] taggedValues = element.getTaggedValues().toTaggedValueArray(); + + for (ITaggedValue taggedValue : taggedValues) { + Object oldValue = taggedValueMap.get(taggedValue.getName()); + if (oldValue != null) { + taggedValue.setValue(oldValue.toString()); + } + } + + System.out.println("Number of tagged values: " + count); + } + } + + public static ITaggedValue reapplyStereotypeAndGetTaggedValue( + IClass _class, String taggedValueName) { + reapplyCurrentStereotype(_class); + + ITaggedValue taggedValue = getTaggedValue(_class, taggedValueName); + if (taggedValue == null) return null; + + // Retrieves desired tagged value + return getTaggedValue(_class, taggedValueName); + } + + private static boolean reapplyCurrentStereotype(IClass _class) { + String stereotype = + _class.toStereotypeArray() != null && _class.toStereotypeArray().length > 0 + ? _class.toStereotypeArray()[0] + : null; + + // Escape in case the stereotype is missing or incorrect + if (stereotype == null || !Stereotype.getOntoUMLClassStereotypeNames().contains(stereotype)) + return false; + + System.out.println("Reapplying " + stereotype + " to " + _class.getName()); + // Reapply stereotype making sure that the tagged values are there + applyStereotype(_class, stereotype); + + return true; + } + + private static ITaggedValue getTaggedValue(IModelElement element, String name) { + ITaggedValueContainer container = element.getTaggedValues(); + + if (container == null) return null; + + try { + return container.getTaggedValueByName(name); + } catch (Exception e) { + return null; + } + } + + private static IStereotype getStereotype(String stereotypeName) { + IStereotype stereotype = + STEREOTYPE_ELEMENTS != null ? STEREOTYPE_ELEMENTS.get(stereotypeName) : null; + + if (stereotype == null && Stereotype.getOntoUMLStereotypeNames().contains(stereotypeName)) { + generate(); + stereotype = STEREOTYPE_ELEMENTS.get(stereotypeName); + } + + return stereotype; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/ViewManagerUtils.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/ViewManagerUtils.java new file mode 100644 index 00000000..0f2fdabb --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/ViewManagerUtils.java @@ -0,0 +1,772 @@ +package it.unibz.inf.ontouml.vp.utils; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.DiagramManager; +import com.vp.plugin.ViewManager; +import com.vp.plugin.diagram.IClassDiagramUIModel; +import com.vp.plugin.diagram.IDiagramElement; +import com.vp.plugin.diagram.IDiagramUIModel; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.IProject; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.listeners.IssueLogMenuListener; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.GitHubRelease; +import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; +import it.unibz.inf.ontouml.vp.views.HTMLEnabledMessage; +import java.io.File; +import java.net.HttpURLConnection; +import java.nio.file.Paths; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.border.EmptyBorder; + +/** + * Class responsible for facilitating display of messages on Visual Paradigm's log. + * + * @author Claudenir Fonseca + * @author Victor Viola + */ +public class ViewManagerUtils { + + public static final String SCOPE_PLUGIN = "OntoUML"; + public static final String SCOPE_VERIFICATION = "Verification Log"; + public static final String SCOPE_DEVELOPMENT_LOG = "DevLog"; + + public static final String SIMPLE_LOGO = "simple_logo"; + public static final String SIMPLE_LOGO_FILENAME = "ontouml-simple-logo.png"; + public static final String NAVIGATION_LOGO = "navigation"; + public static final String NAVIGATION_LOGO_FILENAME = "navigation.png"; + public static final String MORE_HORIZ_LOGO = "more_horiz"; + public static final String MORE_HORIZ_LOGO_FILENAME = "more_horiz.png"; + public static final String PACKAGE_LOGO = "package"; + public static final String PACKAGE_LOGO_FILENAME = "package.png"; + public static final String CLASS_LOGO = "class"; + public static final String CLASS_LOGO_FILENAME = "class.png"; + public static final String ASSOCIATION_LOGO = "association"; + public static final String ASSOCIATION_LOGO_FILENAME = "association.png"; + public static final String GENERALIZATION_LOGO = "generalization"; + public static final String GENERALIZATION_LOGO_FILENAME = "generalization.png"; + public static final String GENERALIZATION_SET_LOGO = "generalizationSet"; + public static final String GENERALIZATION_SET_LOGO_FILENAME = "generalizationset.png"; + public static final String DIAGRAM_LOGO = "diagram"; + public static final String DIAGRAM_LOGO_FILENAME = "diagram.png"; + public static final String DATATYPE_LOGO = "datatype"; + public static final String DATATYPE_LOGO_FILENAME = "datatype.png"; + public static final String ATTRIBUTE_LOGO = "attribute"; + public static final String ATTRIBUTE_LOGO_FILENAME = "attribute.png"; + + public static void simpleLog(String message) { + ApplicationManager.instance().getViewManager().showMessage(message); + } + + public static void simpleDialog(String title, String message) { + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + message, + title, + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + + public static void cleanAndShowMessage(String message) { + ApplicationManager.instance() + .getViewManager() + .removeMessagePaneComponent(OntoUMLPlugin.PLUGIN_ID); + + ArrayList messageList = new ArrayList(); + messageList.add(timestamp() + message); + JList list = new JList<>(messageList.toArray()); + JScrollPane parentContainer = new JScrollPane(list); + ApplicationManager.instance() + .getViewManager() + .showMessagePaneComponent( + OntoUMLPlugin.PLUGIN_ID, ViewManagerUtils.SCOPE_PLUGIN, parentContainer); + } + + private static String timestamp() { + return "[" + (new Timestamp(System.currentTimeMillis())) + "] "; + } + + public static String getFilePath(String imageName) { + + final File pluginDir = + ApplicationManager.instance().getPluginInfo(OntoUMLPlugin.PLUGIN_ID).getPluginDir(); + + switch (imageName) { + case SIMPLE_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", "logo", SIMPLE_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case NAVIGATION_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", NAVIGATION_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case MORE_HORIZ_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", MORE_HORIZ_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case PACKAGE_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", PACKAGE_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case CLASS_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", CLASS_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case ASSOCIATION_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", ASSOCIATION_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case GENERALIZATION_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", GENERALIZATION_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case GENERALIZATION_SET_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", GENERALIZATION_SET_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case DIAGRAM_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", DIAGRAM_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case DATATYPE_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", DATATYPE_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case ATTRIBUTE_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", ATTRIBUTE_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + default: + return null; + } + } + + public static void logDiagramVerificationResponse(String responseMessage) { + ArrayList errorList = new ArrayList(); + ArrayList idModelElementList = new ArrayList(); + + try { + JsonArray response = (JsonArray) new JsonParser().parse(responseMessage).getAsJsonArray(); + + final int errorCount = errorCountInCurrentDiagram(responseMessage); + final String diagramName = getCurrentClassDiagramName(); + + verificationDiagramConcludedDialog(errorCount, diagramName); + + if (errorCount == 0) { + errorList.add("No issues were found in diagram \"" + diagramName + "\"."); + } + + for (JsonElement elem : response) { + final JsonObject error = elem.getAsJsonObject(); + final String id = error.getAsJsonObject("source").get("id").getAsString(); + + if (isElementInCurrentDiagram(id)) { + final StringBuilder errorMessage = new StringBuilder(); + errorMessage.append( + !error.get("severity").isJsonNull() + ? error.get("severity").getAsString().toUpperCase() + : ""); + errorMessage.append(": "); + errorMessage.append( + !error.get("title").isJsonNull() ? error.get("title").getAsString() : ""); + errorMessage.append(" "); + errorMessage.append( + !error.get("description").isJsonNull() ? error.get("description").getAsString() : ""); + + errorList.add(timestamp() + errorMessage.toString()); + idModelElementList.add(id); + } + } + + JList list = new JList<>(errorList.toArray()); + IssueLogMenuListener listener = new IssueLogMenuListener(idModelElementList, list); + list.addMouseListener(listener); + list.addMouseMotionListener(listener); + + JScrollPane parentContainer = new JScrollPane(list); + ApplicationManager.instance() + .getViewManager() + .showMessagePaneComponent(OntoUMLPlugin.PLUGIN_ID, SCOPE_PLUGIN, parentContainer); + + } catch (JsonSyntaxException e) { + verificationServerErrorDialog(responseMessage); + } + } + + public static void logVerificationResponse(String responseMessage) { + ArrayList errorList = new ArrayList(); + ArrayList idModelElementList = new ArrayList(); + try { + JsonArray response = (JsonArray) new JsonParser().parse(responseMessage).getAsJsonArray(); + final int errorCount = response.size(); + + verificationConcludedDialog(errorCount); + + if (errorCount == 0) { + errorList.add("No issues were found in your project."); + } + + for (JsonElement elem : response) { + final JsonObject error = elem.getAsJsonObject(); + final String id = error.getAsJsonObject("source").get("id").getAsString(); + + final StringBuilder errorMessage = new StringBuilder(); + errorMessage.append( + !error.get("severity").isJsonNull() + ? error.get("severity").getAsString().toUpperCase() + : ""); + errorMessage.append(": "); + errorMessage.append( + !error.get("title").isJsonNull() ? error.get("title").getAsString() : ""); + errorMessage.append(" "); + errorMessage.append( + !error.get("description").isJsonNull() ? error.get("description").getAsString() : ""); + + errorList.add(timestamp() + errorMessage.toString()); + idModelElementList.add(id); + } + + JList list = new JList<>(errorList.toArray()); + IssueLogMenuListener listener = new IssueLogMenuListener(idModelElementList, list); + list.addMouseListener(listener); + list.addMouseMotionListener(listener); + + JScrollPane parentContainer = new JScrollPane(list); + ApplicationManager.instance() + .getViewManager() + .showMessagePaneComponent(OntoUMLPlugin.PLUGIN_ID, SCOPE_PLUGIN, parentContainer); + + } catch (JsonSyntaxException e) { + verificationServerErrorDialog(responseMessage); + } + } + + private static void verificationServerErrorDialog(String userMessage) { + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + userMessage, + "Verification Service", + JOptionPane.DEFAULT_OPTION, + JOptionPane.ERROR_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + + private static void verificationConcludedDialog(int nIssues) { + if (nIssues > 0) { + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + "Issues found in your project: " + + nIssues + + ".\n" + + "For details, click on the \"Show Message\" icon on the bottom right corner of" + + " the app.", + "Verification Service", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } else { + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + "No issues were found in your project.", + "Verification Service", + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + } + + private static void verificationDiagramConcludedDialog(int nIssues, String diagramName) { + if (nIssues > 0) { + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + "Issues found in diagram \"" + + diagramName + + "\": " + + nIssues + + ".\n" + + "For details, click on the \"Show Message\" icon on the bottom right corner of" + + " the app.", + "Verification Service", + JOptionPane.DEFAULT_OPTION, + JOptionPane.WARNING_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } else { + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + "No issues were found in diagram \"" + + diagramName + + "\".\n" + + "Other issues may still exist in your project.", + "Verification Service", + JOptionPane.DEFAULT_OPTION, + JOptionPane.INFORMATION_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + } + + public static void verificationFailedDialog(String msg) { + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + msg, + "Verification Service", + JOptionPane.DEFAULT_OPTION, + JOptionPane.ERROR_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + + public static boolean verificationFailedDialogWithOption(String msg, int httpCode) { + final ProjectConfigurations configurations = + Configurations.getInstance().getProjectConfigurations(); + + if (configurations.isCustomServerEnabled() + && (httpCode == HttpURLConnection.HTTP_NOT_FOUND + || httpCode == HttpURLConnection.HTTP_INTERNAL_ERROR)) { + + int option = + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + msg + "\nDo you want to retry using the default server?", + "Verification Service", + JOptionPane.YES_NO_OPTION, + JOptionPane.INFORMATION_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + + if (option == JOptionPane.OK_OPTION) { + configurations.setCustomServerEnabled(false); + return true; + } else { + return false; + } + + } else { + verificationFailedDialog(msg); + return false; + } + } + + public static void exportToGUFOIssueDialog(String msg) { + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + msg, + "Export to gUFO", + JOptionPane.DEFAULT_OPTION, + JOptionPane.ERROR_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + + public static boolean exportToGUFOIssueDialogWithOption(String msg, int httpCode) { + final ProjectConfigurations configurations = + Configurations.getInstance().getProjectConfigurations(); + + if (configurations.isCustomServerEnabled() + && (httpCode == HttpURLConnection.HTTP_NOT_FOUND + || httpCode == HttpURLConnection.HTTP_INTERNAL_ERROR)) { + + int option = + ApplicationManager.instance() + .getViewManager() + .showConfirmDialog( + null, + msg + "\nDo you want to retry using the default server?", + "Export to gUFO", + JOptionPane.YES_NO_OPTION, + JOptionPane.INFORMATION_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + + if (option == JOptionPane.OK_OPTION) { + configurations.setCustomServerEnabled(false); + return true; + } else { + return false; + } + + } else { + exportToGUFOIssueDialog(msg); + return false; + } + } + + private static String getCurrentClassDiagramName() { + final IDiagramUIModel[] diagramArray = + ApplicationManager.instance().getProjectManager().getProject().toDiagramArray(); + + if (diagramArray == null) { + return null; + } + + for (IDiagramUIModel diagram : diagramArray) { + if (diagram instanceof IClassDiagramUIModel && diagram.isOpened()) { + return diagram.getName(); + } + } + + return null; + } + + private static String getCurrentClassDiagramId() { + final IDiagramUIModel[] diagramArray = + ApplicationManager.instance().getProjectManager().getProject().toDiagramArray(); + + if (diagramArray == null) { + return null; + } + + for (IDiagramUIModel diagram : diagramArray) { + if (diagram instanceof IClassDiagramUIModel && diagram.isOpened()) { + return diagram.getId(); + } + } + + return null; + } + + private static IDiagramUIModel getCurrentClassDiagram() { + + return ApplicationManager.instance() + .getProjectManager() + .getProject() + .getDiagramById(getCurrentClassDiagramId()); + } + + private static boolean isElementInCurrentDiagram(String id) { + + if (getCurrentClassDiagram() == null) { + return false; + } + + for (IDiagramElement element : getCurrentClassDiagram().toDiagramElementArray()) { + if (element.getModelElement().getId().equals(id)) { + return true; + } + } + + return false; + } + + private static int errorCountInCurrentDiagram(String responseMessage) { + int errorCount = 0; + + try { + JsonArray response = (JsonArray) new JsonParser().parse(responseMessage).getAsJsonArray(); + + for (JsonElement elem : response) { + if (isElementInCurrentDiagram( + elem.getAsJsonObject().getAsJsonObject("source").get("id").getAsString())) { + errorCount++; + } + } + } catch (JsonSyntaxException e) { + return 0; + } + + return errorCount; + } + + public static boolean isElementInAnyDiagram(String elementId) { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + final IModelElement element = project.getModelElementById(elementId); + final IDiagramElement[] diagramElements = element != null ? element.getDiagramElements() : null; + + return diagramElements != null && diagramElements.length > 0; + } + + public static void openSpecDiagramElement(String elementId) { + final ApplicationManager app = ApplicationManager.instance(); + final IModelElement element = + app.getProjectManager().getProject().getModelElementById(elementId); + final ViewManager viewManager = app.getViewManager(); + + viewManager.openSpec(element, viewManager.getRootFrame()); + } + + public static void highlightDiagramElement(String modelElementId) { + final ApplicationManager app = ApplicationManager.instance(); + final IProject project = app.getProjectManager().getProject(); + final IModelElement modelElement = project.getModelElementById(modelElementId); + + if (modelElement == null) { + return; + } + + final DiagramManager diagramManager = app.getDiagramManager(); + final IDiagramElement[] diagramElements = modelElement.getDiagramElements(); + IDiagramElement activeView = null; + IDiagramElement masterView = null; + IDiagramElement firstView = null; + + for (int i = 0; diagramElements != null && i < diagramElements.length; i++) { + IDiagramElement diagramElement = diagramElements[i]; + + if (diagramElement == null) { + continue; + } + + firstView = firstView == null ? diagramElement : firstView; + activeView = diagramElement.getDiagramUIModel().isOpened() ? diagramElement : activeView; + masterView = diagramElement.isMasterView() ? diagramElement : masterView; + + if (activeView != null) { + break; + } + } + + if (activeView != null) { + diagramManager.highlight(activeView); + } else if (masterView != null) { + diagramManager.highlight(masterView); + } else if (firstView != null) { + diagramManager.highlight(firstView); + } + } + + public static void reportBugErrorDialog(boolean isOperationNotAllowed) { + final ViewManager vm = ApplicationManager.instance().getViewManager(); + final String body = + isOperationNotAllowed + ? "Unable to open the browser. Please visit " + + OntoUMLPlugin.PLUGIN_REPO + + " to submit bugs." + : "Something went wrong. Please visit " + + OntoUMLPlugin.PLUGIN_REPO + + " to submit bugs."; + + vm.showConfirmDialog( + null, + new HTMLEnabledMessage(body), + "Report Error", + JOptionPane.DEFAULT_OPTION, + JOptionPane.ERROR_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + + public static GitHubRelease updateDialog() { + final Configurations config = Configurations.getInstance(); + final GitHubRelease lastestRelease = config.getLatestRelease(); + + final boolean isUpToDate = + lastestRelease.getTagName().equals(OntoUMLPlugin.PLUGIN_VERSION_RELEASE); + String[] options; + String initialSelection; + StringBuilder msg = new StringBuilder(); + + if (isUpToDate) { + options = new String[2]; + options[0] = "Cancel"; + options[1] = "Select release"; + + initialSelection = options[1]; + + msg.append("Your plugin is up to date with the latest stable release."); + msg.append( + "\n" + + "If you desire to install a different version of the plugin, click on \"Select" + + " release\"."); + msg.append( + "\n" + + "Be aware that \"alpha\" releases provide experimental new features that may not" + + " be fully integrated to the plugin."); + msg.append("\n\nThe procedure may take a couple of seconds."); + } else { + options = new String[3]; + options[0] = "Cancel"; + options[1] = "Select release"; + options[2] = "Install latest release"; + + initialSelection = options[2]; + + msg.append( + "The latest stable release of the plugin is the version " + + lastestRelease.getTagName() + + "."); + msg.append( + "\n" + + "To install this update, click on \"Install latest release\", or click on" + + " \"Select a release\" to install a different version."); + msg.append( + "\n" + + "Be aware that \"alpha\" releases are provide experimental new features that may" + + " present some issues."); + msg.append("\n\nThe procedure may take a couple of seconds."); + } + + final ViewManager vm = ApplicationManager.instance().getViewManager(); + int selectedOption = + vm.showOptionDialog( + vm.getRootFrame(), + msg.toString(), + "Plugin Update", + JOptionPane.YES_NO_CANCEL_OPTION, + JOptionPane.PLAIN_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO)), + options, + initialSelection); + + switch (selectedOption) { + case 2: + return lastestRelease; + case 1: + return selectReleaseToInstall(); + default: + return null; + } + } + + public static void updateSuccessDialog() { + final ViewManager vm = ApplicationManager.instance().getViewManager(); + final String msg = + "Plugin successfully updated.\n" + + "Please restart the application for the changes to take effect."; + + vm.showConfirmDialog( + null, + msg, + "Plugin Update", + JOptionPane.DEFAULT_OPTION, + JOptionPane.PLAIN_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + + public static void updateErrorDialog() { + final ViewManager vm = ApplicationManager.instance().getViewManager(); + final StringBuilder builder = new StringBuilder(); + builder.append("Something went wrong during the update. Please verify your connection.
"); + builder.append( + "In case your plugin becomes unavailable, you may find instructions at " + + OntoUMLPlugin.PLUGIN_REPO + + ".
"); + builder.append( + "In this page you can also report this error and help us to improve our plugin."); + + vm.showConfirmDialog( + null, + new HTMLEnabledMessage(builder.toString()), + "Plugin Update Error", + JOptionPane.DEFAULT_OPTION, + JOptionPane.ERROR_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + } + + private static GitHubRelease selectReleaseToInstall() { + final Map map = new HashMap<>(); + final Configurations config = Configurations.getInstance(); + final GitHubRelease installedRelease = config.getInstalledRelease(); + final String installedReleaseTagName = + installedRelease != null ? installedRelease.getTagName() : null; + + config + .getReleases() + .forEach( + release -> { + String releaseTagName = release.getTagName(); + + releaseTagName = + installedReleaseTagName != null && releaseTagName.equals(installedReleaseTagName) + ? releaseTagName + " (installed version)" + : releaseTagName; + + map.put(releaseTagName, release); + }); + + ViewManager vm = ApplicationManager.instance().getViewManager(); + List keys = new ArrayList(map.keySet()); + keys.sort(Comparator.reverseOrder()); + Object[] keysArray = new String[keys.size()]; + keys.toArray(keysArray); + Object selectedValue = + vm.showInputDialog( + vm.getRootFrame(), + "Select the desired version of the OntoUML Plugin:", + "Plugin Versions", + JOptionPane.QUESTION_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO)), + keysArray, + keysArray[0]); + + return map.get(selectedValue); + } + + public static boolean associationInvertionWarningDialog() { + final Configurations config = Configurations.getInstance(); + final ProjectConfigurations projectConfig = config.getProjectConfigurations(); + + if (projectConfig.ignoreAssociationInversionWarning()) { + return true; + } + + final ViewManager vm = ApplicationManager.instance().getViewManager(); + final JPanel _pMessagePane = new JPanel(); + final JLabel _lLineOne = + new JLabel( + "This action will invert the direction of the
" + + "association in all diagrams it appears. You may
" + + "want to check if its name is still consistent.

" + + "Do you wish to continue?"); + final JCheckBox _chkHideWarnings = new JCheckBox("Do not show this dialog again"); + + _pMessagePane.setLayout(new BoxLayout(_pMessagePane, BoxLayout.Y_AXIS)); + _pMessagePane.add(_lLineOne); + _pMessagePane.add(_chkHideWarnings); + _chkHideWarnings.setBorder(new EmptyBorder(15, 0, 0, 0)); + + int selectedOption = + vm.showConfirmDialog( + vm.getRootFrame(), + _pMessagePane, + "Association Inversion Warning", + JOptionPane.YES_NO_OPTION, + JOptionPane.INFORMATION_MESSAGE, + new ImageIcon(getFilePath(SIMPLE_LOGO))); + + if (_chkHideWarnings.isSelected()) { + projectConfig.setIgnoreAssociationInversionWarning(true); + config.save(); + } + + return JOptionPane.YES_OPTION == selectedOption; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/utils/ViewUtils.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/ViewUtils.java deleted file mode 100644 index 282cc267..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/ViewUtils.java +++ /dev/null @@ -1,693 +0,0 @@ -package it.unibz.inf.ontouml.vp.utils; - -import java.awt.FileDialog; -import java.awt.Frame; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.stream.Collectors; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JList; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.JsonSyntaxException; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.DiagramManager; -import com.vp.plugin.ProjectManager; -import com.vp.plugin.ViewManager; -import com.vp.plugin.diagram.IClassDiagramUIModel; -import com.vp.plugin.diagram.IDiagramElement; -import com.vp.plugin.diagram.IDiagramUIModel; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.IProject; - -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; -import it.unibz.inf.ontouml.vp.views.HTMLEnabledMessage; - -/** - * - * Class responsible for facilitating display of messages on Visual Paradigm's - * log. - * - * @author Claudenir Fonseca - * @author Victor Viola - * - */ -public class ViewUtils { - - public static final String SCOPE_PLUGIN = "OntoUML"; - // public static final String SCOPE_ALL_PLUGINS = ""; - public static final String SCOPE_VERIFICATION = "Verification Log"; - public static final String SCOPE_DEVELOPMENT_LOG = "DevLog"; - - // images - public static final String SIMPLE_LOGO = "simple_logo"; - public static final String SIMPLE_LOGO_FILENAME = "ontouml-simple-logo.png"; - public static final String NAVIGATION_LOGO = "navigation"; - public static final String NAVIGATION_LOGO_FILENAME = "navigation.png"; - public static final String MORE_HORIZ_LOGO = "more_horiz"; - public static final String MORE_HORIZ_LOGO_FILENAME = "more_horiz.png"; - public static final String PACKAGE_LOGO = "package"; - public static final String PACKAGE_LOGO_FILENAME = "package.png"; - public static final String CLASS_LOGO = "class"; - public static final String CLASS_LOGO_FILENAME = "class.png"; - public static final String ASSOCIATION_LOGO = "association"; - public static final String ASSOCIATION_LOGO_FILENAME = "association.png"; - public static final String GENERALIZATION_LOGO = "generalization"; - public static final String GENERALIZATION_LOGO_FILENAME = "generalization.png"; - public static final String GENERALIZATION_SET_LOGO = "generalizationSet"; - public static final String GENERALIZATION_SET_LOGO_FILENAME = "generalizationset.png"; - public static final String DIAGRAM_LOGO = "diagram"; - public static final String DIAGRAM_LOGO_FILENAME = "diagram.png"; - public static final String DATATYPE_LOGO = "datatype"; - public static final String DATATYPE_LOGO_FILENAME = "datatype.png"; - public static final String ATTRIBUTE_LOGO = "attribute"; - public static final String ATTRIBUTE_LOGO_FILENAME = "attribute.png"; - - // buttons - public static final String ADD_LOGO = "add"; - public static final String ASTERISK_LOGO = "asterisk"; - public static final String SUBTRACT_LOGO = "subtract"; - public static final String ADD_LOGO_FILENAME = "add.png"; - public static final String ASTERISK_LOGO_FILENAME = "asterisk.png"; - public static final String SUBTRACT_LOGO_FILENAME = "subtract.png"; - - public static void log(String message) { - ApplicationManager.instance().getViewManager().showMessage(timestamp() + message); - } - - public static void log(String message, String scope) { - ApplicationManager.instance().getViewManager().showMessage(timestamp() + message, scope); - } - - public static void simpleLog(String message) { - ApplicationManager.instance().getViewManager().showMessage(message); - } - - public static void simpleLog(String message, String scope) { - ApplicationManager.instance().getViewManager().showMessage(message, scope); - } - - public static void clearLog(String scope) { - ApplicationManager.instance().getViewManager().clearMessages(scope); - } - - public static void simpleDialog(String title, String message) { - ApplicationManager.instance().getViewManager().showConfirmDialog(null, message, title, - JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static void cleanAndShowMessage(String message) { - - ApplicationManager.instance().getViewManager().removeMessagePaneComponent(OntoUMLPlugin.PLUGIN_ID); - - ArrayList messageList = new ArrayList(); - messageList.add(timestamp() + message); - JList list = new JList<>(messageList.toArray()); - JScrollPane parentContainer = new JScrollPane(list); - ApplicationManager.instance().getViewManager().showMessagePaneComponent(OntoUMLPlugin.PLUGIN_ID, - ViewUtils.SCOPE_PLUGIN, parentContainer); - - } - - private static String timestamp() { - return "[" + (new Timestamp(System.currentTimeMillis())) + "] "; - } - - public static String getFilePath(String imageName) { - - final File pluginDir = ApplicationManager.instance().getPluginInfo(OntoUMLPlugin.PLUGIN_ID).getPluginDir(); - - switch (imageName) { - case SIMPLE_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", "logo", SIMPLE_LOGO_FILENAME).toFile() - .getAbsolutePath(); - case NAVIGATION_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", NAVIGATION_LOGO_FILENAME).toFile().getAbsolutePath(); - case MORE_HORIZ_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", MORE_HORIZ_LOGO_FILENAME).toFile().getAbsolutePath(); - case PACKAGE_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", PACKAGE_LOGO_FILENAME).toFile().getAbsolutePath(); - case CLASS_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", CLASS_LOGO_FILENAME).toFile().getAbsolutePath(); - case ASSOCIATION_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", ASSOCIATION_LOGO_FILENAME).toFile() - .getAbsolutePath(); - case GENERALIZATION_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", GENERALIZATION_LOGO_FILENAME).toFile() - .getAbsolutePath(); - case GENERALIZATION_SET_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", GENERALIZATION_SET_LOGO_FILENAME).toFile() - .getAbsolutePath(); - case DIAGRAM_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", DIAGRAM_LOGO_FILENAME).toFile().getAbsolutePath(); - case DATATYPE_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", DATATYPE_LOGO_FILENAME).toFile().getAbsolutePath(); - case ATTRIBUTE_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", ATTRIBUTE_LOGO_FILENAME).toFile().getAbsolutePath(); - case ADD_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", ADD_LOGO_FILENAME).toFile().getAbsolutePath(); - case ASTERISK_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", ASTERISK_LOGO_FILENAME).toFile().getAbsolutePath(); - case SUBTRACT_LOGO: - return Paths.get(pluginDir.getAbsolutePath(), "icons", SUBTRACT_LOGO_FILENAME).toFile().getAbsolutePath(); - default: - return null; - } - } - - public static void logDiagramVerificationResponse(String responseMessage) { - ArrayList errorList = new ArrayList(); - ArrayList idModelElementList = new ArrayList(); - - try { - JsonArray response = (JsonArray) new JsonParser().parse(responseMessage).getAsJsonArray(); - - final int errorCount = errorCountInCurrentDiagram(responseMessage); - final String diagramName = getCurrentClassDiagramName(); - - verificationDiagramConcludedDialog(errorCount, diagramName); - - if (errorCount == 0) - errorList.add("No issues were found in diagram \"" + diagramName + "\"."); - - for (JsonElement elem : response) { - final JsonObject error = elem.getAsJsonObject(); - final String id = error.getAsJsonObject("source").get("id").getAsString(); - - if (isElementInCurrentDiagram(id)) { - final StringBuilder errorMessage = new StringBuilder(); - errorMessage.append( - !error.get("severity").isJsonNull() ? error.get("severity").getAsString().toUpperCase() - : ""); - errorMessage.append(": "); - errorMessage.append(!error.get("title").isJsonNull() ? error.get("title").getAsString() : ""); - errorMessage.append(" "); - errorMessage.append( - !error.get("description").isJsonNull() ? error.get("description").getAsString() : ""); - - errorList.add(timestamp() + errorMessage.toString()); - idModelElementList.add(id); - } - // final JsonObject error = elem.getAsJsonObject(); - // final String id = error.getAsJsonObject("source").get("id").getAsString(); - - // if (isElementInCurrentDiagram(id)) { - // final String errorMessage = error.get("severity").getAsString() + ":" + " " + - // error.get("title").getAsString() + " " + - // error.get("description").getAsString(); - // errorList.add(timestamp() + errorMessage); - // idModelElementList.add(id); - // } - } - - JList list = new JList<>(errorList.toArray()); - ContextMenuListener listener = new ContextMenuListener(idModelElementList, list); - list.addMouseListener(listener); - list.addMouseMotionListener(listener); - - JScrollPane parentContainer = new JScrollPane(list); - ApplicationManager.instance().getViewManager().showMessagePaneComponent(OntoUMLPlugin.PLUGIN_ID, - SCOPE_PLUGIN, parentContainer); - - } catch (JsonSyntaxException e) { - verificationServerErrorDialog(responseMessage); - } - } - - public static void logVerificationResponse(String responseMessage) { - ArrayList errorList = new ArrayList(); - ArrayList idModelElementList = new ArrayList(); - try { - JsonArray response = (JsonArray) new JsonParser().parse(responseMessage).getAsJsonArray(); - final int errorCount = response.size(); - - verificationConcludedDialog(errorCount); - - if (errorCount == 0) - errorList.add("No issues were found in your project."); - - for (JsonElement elem : response) { - final JsonObject error = elem.getAsJsonObject(); - final String id = error.getAsJsonObject("source").get("id").getAsString(); - - final StringBuilder errorMessage = new StringBuilder(); - errorMessage.append( - !error.get("severity").isJsonNull() ? error.get("severity").getAsString().toUpperCase() : ""); - errorMessage.append(": "); - errorMessage.append(!error.get("title").isJsonNull() ? error.get("title").getAsString() : ""); - errorMessage.append(" "); - errorMessage - .append(!error.get("description").isJsonNull() ? error.get("description").getAsString() : ""); - - errorList.add(timestamp() + errorMessage.toString()); - idModelElementList.add(id); - - } - - JList list = new JList<>(errorList.toArray()); - ContextMenuListener listener = new ContextMenuListener(idModelElementList, list); - list.addMouseListener(listener); - list.addMouseMotionListener(listener); - - JScrollPane parentContainer = new JScrollPane(list); - ApplicationManager.instance().getViewManager().showMessagePaneComponent(OntoUMLPlugin.PLUGIN_ID, - SCOPE_PLUGIN, parentContainer); - - } catch (JsonSyntaxException e) { - verificationServerErrorDialog(responseMessage); - } - } - - public static void verificationServerErrorDialog(String userMessage) { - ApplicationManager.instance().getViewManager().showConfirmDialog(null, userMessage, "Verification Service", - JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static void verificationConcludedDialog(int nIssues) { - if (nIssues > 0) { - ApplicationManager.instance().getViewManager().showConfirmDialog(null, - "Issues found in your project: " + nIssues + ".\n" - + "For details, click on the \"Show Message\" icon on the bottom right corner of the app.", - "Verification Service", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, - new ImageIcon(getFilePath(SIMPLE_LOGO))); - } else { - ApplicationManager.instance().getViewManager().showConfirmDialog(null, - "No issues were found in your project.", "Verification Service", JOptionPane.DEFAULT_OPTION, - JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - } - - public static void verificationDiagramConcludedDialog(int nIssues, String diagramName) { - if (nIssues > 0) { - ApplicationManager.instance().getViewManager().showConfirmDialog(null, - "Issues found in diagram \"" + diagramName + "\": " + nIssues + ".\n" - + "For details, click on the \"Show Message\" icon on the bottom right corner of the app.", - "Verification Service", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, - new ImageIcon(getFilePath(SIMPLE_LOGO))); - } else { - ApplicationManager.instance().getViewManager().showConfirmDialog(null, - "No issues were found in diagram \"" + diagramName + "\".\n" - + "Other issues may still exist in your project.", - "Verification Service", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, - new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - } - - public static void verificationFailedDialog(String msg) { - ApplicationManager.instance().getViewManager().showConfirmDialog(null, msg, "Verification Service", - JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static boolean verificationFailedDialogWithOption(String msg, int httpCode) { - final ProjectConfigurations configurations = Configurations.getInstance().getProjectConfigurations(); - - if (configurations.isCustomServerEnabled() && (httpCode == HttpURLConnection.HTTP_NOT_FOUND - || httpCode == HttpURLConnection.HTTP_INTERNAL_ERROR)) { - - int option = ApplicationManager.instance().getViewManager().showConfirmDialog(null, - msg + "\nDo you want to retry using the default server?", "Verification Service", - JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, - new ImageIcon(getFilePath(SIMPLE_LOGO))); - - if (option == JOptionPane.OK_OPTION) { - configurations.setCustomServerEnabled(false); - return true; - } else { - return false; - } - - } else { - verificationFailedDialog(msg); - return false; - } - } - - public static void exportToGUFOIssueDialog(String msg) { - ApplicationManager.instance().getViewManager().showConfirmDialog(null, msg, "Export to gUFO", - JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static boolean exportToGUFOIssueDialogWithOption(String msg, int httpCode) { - final ProjectConfigurations configurations = Configurations.getInstance().getProjectConfigurations(); - - if (configurations.isCustomServerEnabled() && (httpCode == HttpURLConnection.HTTP_NOT_FOUND - || httpCode == HttpURLConnection.HTTP_INTERNAL_ERROR)) { - - int option = ApplicationManager.instance().getViewManager().showConfirmDialog(null, - msg + "\nDo you want to retry using the default server?", "Export to gUFO", - JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, - new ImageIcon(getFilePath(SIMPLE_LOGO))); - - if (option == JOptionPane.OK_OPTION) { - configurations.setCustomServerEnabled(false); - return true; - } else { - return false; - } - - } else { - exportToGUFOIssueDialog(msg); - return false; - } - } - - public static int smartPaintEnableDialog() { - return ApplicationManager.instance().getViewManager().showConfirmDialog(null, - "Smart Paint is disabled. Do you want to enable this feature?\n" - + "Warning: this feature will affect all diagrams within the project.", - "Smart Paint", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, - new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static int smartPaintConfirmationDialog() { - return ApplicationManager.instance().getViewManager().showConfirmDialog(null, - "Warning: this feature will affect all diagrams within the project.\n" + "Do you want to proceed?", - "Smart Paint", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, - new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static void saveFile(BufferedReader buffer) throws IOException { - final Configurations configs = Configurations.getInstance(); - final ProjectConfigurations projectConfigurations = configs.getProjectConfigurations(); - final FileDialog fd = new FileDialog((Frame) ApplicationManager.instance().getViewManager().getRootFrame(), - "Choose destination", FileDialog.SAVE); - - String suggestedFolderPath = projectConfigurations.getExportGUFOFolderPath(); - String suggestedFileName = projectConfigurations.getExportGUFOFilename(); - - if (suggestedFileName.isEmpty()) { - String projectName = ApplicationManager.instance().getProjectManager().getProject().getName(); - suggestedFileName = projectName + ".ttl"; - } - - fd.setDirectory(suggestedFolderPath); - fd.setFile(suggestedFileName); - fd.setVisible(true); - - if (fd.getDirectory() != null && fd.getFile() != null) { - final String fileDirectory = fd.getDirectory(); - final String fileName = !fd.getFile().endsWith(".ttl") ? fd.getFile() + ".ttl" : fd.getFile(); - final String output = buffer.lines().collect(Collectors.joining("\n")); - - Files.write(Paths.get(fileDirectory, fileName), output.getBytes()); - projectConfigurations.setExportGUFOFolderPath(fileDirectory); - projectConfigurations.setExportGUFOFilename(fileName); - configs.save(); - } - - ViewUtils.cleanAndShowMessage("File saved successfuly."); - } - - public static String getCurrentClassDiagramName() { - final IDiagramUIModel[] diagramArray = ApplicationManager.instance().getProjectManager().getProject() - .toDiagramArray(); - - if (diagramArray == null) - return null; - - for (IDiagramUIModel diagram : diagramArray) { - if (diagram instanceof IClassDiagramUIModel && diagram.isOpened()) - return diagram.getName(); - } - - return null; - } - - public static String getCurrentClassDiagramId() { - final IDiagramUIModel[] diagramArray = ApplicationManager.instance().getProjectManager().getProject() - .toDiagramArray(); - - if (diagramArray == null) - return null; - - for (IDiagramUIModel diagram : diagramArray) { - if (diagram instanceof IClassDiagramUIModel && diagram.isOpened()) - return diagram.getId(); - } - - return null; - } - - public static IDiagramUIModel getCurrentClassDiagram() { - - return ApplicationManager.instance().getProjectManager().getProject() - .getDiagramById(getCurrentClassDiagramId()); - } - - public static boolean isElementInCurrentDiagram(String id) { - - if (getCurrentClassDiagram() == null) - return false; - - for (IDiagramElement element : getCurrentClassDiagram().toDiagramElementArray()) { - if (element.getModelElement().getId().equals(id)) - return true; - } - - return false; - } - - public static int errorCountInCurrentDiagram(String responseMessage) { - int errorCount = 0; - - try { - JsonArray response = (JsonArray) new JsonParser().parse(responseMessage).getAsJsonArray(); - - for (JsonElement elem : response) { - if (isElementInCurrentDiagram(elem.getAsJsonObject().getAsJsonObject("source").get("id").getAsString())) - errorCount++; - } - } catch (JsonSyntaxException e) { - return 0; - } - - return errorCount; - } - - public static boolean isElementInAnyDiagram(String elementId) { - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - final IModelElement element = project.getModelElementById(elementId); - final IDiagramElement[] diagramElements = element != null ? element.getDiagramElements() : null; - - return diagramElements != null && diagramElements.length > 0; - } - - public static void openSpecDiagramElement(String elementId) { - final ApplicationManager app = ApplicationManager.instance(); - final IModelElement element = app.getProjectManager().getProject().getModelElementById(elementId); - final ViewManager viewManager = app.getViewManager(); - - viewManager.openSpec(element, viewManager.getRootFrame()); - } - - public static void highlightDiagramElement(String modelElementId) { - final ApplicationManager app = ApplicationManager.instance(); - final IProject project = app.getProjectManager().getProject(); - final IModelElement modelElement = project.getModelElementById(modelElementId); - - if(modelElement == null) { - return ; - } - - final DiagramManager diagramManager = app.getDiagramManager(); - final IDiagramElement[] diagramElements = modelElement.getDiagramElements(); - IDiagramElement activeView = null; - IDiagramElement masterView = null; - IDiagramElement firstView = null; - - for (int i=0; diagramElements != null && i < diagramElements.length; i++) { - IDiagramElement diagramElement = diagramElements[i]; - - if(diagramElement == null) { - continue ; - } - - firstView = firstView == null ? diagramElement : firstView; - activeView = diagramElement.getDiagramUIModel().isOpened() ? diagramElement : activeView; - masterView = diagramElement.isMasterView() ? diagramElement : masterView; - - if(activeView != null) { - break ; - } - } - - if(activeView != null) { - diagramManager.highlight(activeView); - } - else if(masterView != null) { - diagramManager.highlight(masterView); - } - else if(firstView != null) { - diagramManager.highlight(firstView); - } - } - - public static String setOrderDialog(String currentOrder) { - final ViewManager vm = ApplicationManager.instance().getViewManager(); - final String msg = "Please enter a value for the type order,\n" + "where '*' represents an orderless type:"; - final String title = "Set type order"; - final Icon icon = new ImageIcon(getFilePath(SIMPLE_LOGO)); - - return (String) vm.showInputDialog(vm.getRootFrame(), msg, title, JOptionPane.PLAIN_MESSAGE, icon, null, - currentOrder); - } - - public static void reportBugErrorDialog(boolean isOperationNotAllowed) { - final ViewManager vm = ApplicationManager.instance().getViewManager(); - final String body = isOperationNotAllowed - ? "Unable to open the browser. Please visit " - + OntoUMLPlugin.PLUGIN_REPO + " to submit bugs." - : "Something went wrong. Please visit " - + OntoUMLPlugin.PLUGIN_REPO + " to submit bugs."; - - vm.showConfirmDialog(null, new HTMLEnabledMessage(body), "Report Error", JOptionPane.DEFAULT_OPTION, - JOptionPane.ERROR_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static void updateDialog() { - final ViewManager vm = ApplicationManager.instance().getViewManager(); - final StringBuilder builder = new StringBuilder(); - builder.append("Please select the ZIP file containing the release of the OntoUML Plguin that you wish to install.
"); - builder.append("The latest release is available at " + OntoUMLPlugin.PLUGIN_REPO +".

"); - builder.append("This procedure may take a couple of seconds."); - - vm.showConfirmDialog(null, new HTMLEnabledMessage(builder.toString()), "Plugin Update", JOptionPane.DEFAULT_OPTION, - JOptionPane.PLAIN_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static void updateSuccessDialog() { - final ViewManager vm = ApplicationManager.instance().getViewManager(); - final String msg = "Plugin successfully updated.\nPlease reopen the application for the changes to take effect."; - - vm.showConfirmDialog(null, msg, "Plugin Update", JOptionPane.DEFAULT_OPTION, - JOptionPane.PLAIN_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } - - public static void updateErrorDialog() { - final ViewManager vm = ApplicationManager.instance().getViewManager(); - final StringBuilder builder = new StringBuilder(); - builder.append("Something went wrong during the update.
"); - builder.append("In case your plugin becomes unavailable, you may find instructions at " + OntoUMLPlugin.PLUGIN_REPO +".
"); - builder.append("In this page you can also report this error and help us to improve our plugin."); - - vm.showConfirmDialog(null, new HTMLEnabledMessage(builder.toString()), "Plugin Update Error", JOptionPane.DEFAULT_OPTION, - JOptionPane.ERROR_MESSAGE, new ImageIcon(getFilePath(SIMPLE_LOGO))); - } -} - -@SuppressWarnings("serial") -final class ContextMenu extends JPopupMenu { - private JMenuItem takeMeThere; - private JMenuItem openSpec; - private ActionListener menuListener; - - public ContextMenu() { - - } - - public ContextMenu(String idModelElement) { - - menuListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - switch (e.getActionCommand()) { - case "Take me there!": - System.out.println("Firing 'Highlight'"); - ViewUtils.highlightDiagramElement(idModelElement); - break; - case "Open Specification": - System.out.println("Firing 'Open Specification'"); - ViewUtils.openSpecDiagramElement(idModelElement); - break; - default: - break; - } - } - }; - - takeMeThere = new JMenuItem("Take me there!", new ImageIcon(ViewUtils.getFilePath(ViewUtils.NAVIGATION_LOGO))); - takeMeThere.addActionListener(menuListener); - openSpec = new JMenuItem("Open Specification", new ImageIcon(ViewUtils.getFilePath(ViewUtils.MORE_HORIZ_LOGO))); - openSpec.addActionListener(menuListener); - add(takeMeThere); - add(openSpec); - } - - public void disableItem(String item) { - switch (item) { - case "Take me there!": - takeMeThere.setEnabled(false); - break; - case "Open Specification": - openSpec.setEnabled(false); - break; - default: - break; - } - } -} - -final class ContextMenuListener extends MouseAdapter { - private ArrayList idModelElementList; - private JList messageList; - - ContextMenuListener(ArrayList list, JList messages) { - super(); - idModelElementList = list; - messageList = messages; - } - - @Override - public void mouseMoved(MouseEvent e) { - final Point p = e.getPoint(); - final int index = messageList.locationToIndex(p); - - messageList.setSelectedIndex(index); - } - - @Override - public void mouseExited(MouseEvent e) { - messageList.clearSelection(); - } - - public void mouseReleased(MouseEvent e) { - doPop(e); - } - - private void doPop(MouseEvent e) { - ContextMenu menu; - String idModelElement = idModelElementList.get(messageList.locationToIndex(e.getPoint())); - - if (idModelElement == null) { - menu = new ContextMenu(); - } else { - menu = new ContextMenu(idModelElement); - if (!ViewUtils.isElementInAnyDiagram(idModelElement)) { - menu.disableItem("Take me there!"); - } - } - - menu.show(e.getComponent(), e.getX(), e.getY()); - } -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/ConfigurationsView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/ConfigurationsView.java index b827d57e..76a2e300 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/ConfigurationsView.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/ConfigurationsView.java @@ -1,256 +1,235 @@ package it.unibz.inf.ontouml.vp.views; import com.vp.plugin.view.IDialog; - import it.unibz.inf.ontouml.vp.OntoUMLPlugin; -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.ProjectConfigurations; - -import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import javax.swing.*; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; /** - * - * View for the configurations menu to be embedded on an instance - * of ConfigurationsDialog. - * - * @author Claudenir Fonseca + * View for the configurations menu to be embedded on an instance of ConfigurationsDialog + * . * + * @author Claudenir Fonseca */ public class ConfigurationsView extends JPanel { - - private static final long serialVersionUID = 1L; - - private JCheckBox _chckbxEnableCustomServer; - private JTextField _txtServerAddress; - - private JCheckBox _chckbxEnableAutoColoring; - private JCheckBox _chckbxEnableSmartModelling; - - private JButton _btnApply; - private JButton _btnResetDefaults; - - private JLabel pluginVersion; - - private IDialog _dialog; - - /** - * - * ConfigurationsView constructor. - * - */ - public ConfigurationsView(ProjectConfigurations configurations) { - setSize(new Dimension(670, 180)); - GridBagLayout gridBagLayout = new GridBagLayout(); - gridBagLayout.columnWidths = new int[] {670}; - gridBagLayout.rowHeights = new int[]{26, 82, 25, 0}; - gridBagLayout.columnWeights = new double[]{1.0}; - gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE}; - setLayout(gridBagLayout); - - JPanel _optionsPanel = new JPanel(); - GridBagConstraints gbc__optionsPanel = new GridBagConstraints(); - gbc__optionsPanel.fill = GridBagConstraints.VERTICAL; - gbc__optionsPanel.gridx = 0; - gbc__optionsPanel.gridy = 1; - add(_optionsPanel, gbc__optionsPanel); - _optionsPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); - - JPanel _ontoUMLServerPanel = new JPanel(); - _optionsPanel.add(_ontoUMLServerPanel); - GridBagLayout gbl__ontoUMLServerPanel = new GridBagLayout(); - gbl__ontoUMLServerPanel.columnWidths = new int[]{290, 370, 0}; - gbl__ontoUMLServerPanel.rowHeights = new int[]{26, 0}; - gbl__ontoUMLServerPanel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE}; - gbl__ontoUMLServerPanel.rowWeights = new double[]{0.0, Double.MIN_VALUE}; - _ontoUMLServerPanel.setLayout(gbl__ontoUMLServerPanel); - - _chckbxEnableCustomServer = new JCheckBox("Use custom OntoUML Server instance."); - _chckbxEnableCustomServer.addChangeListener(new ChangeListener() { - public void stateChanged(ChangeEvent e) { - updateComponentsStatus(); - } - }); - GridBagConstraints gbc__chckbxEnableCustomServer = new GridBagConstraints(); - gbc__chckbxEnableCustomServer.anchor = GridBagConstraints.WEST; - gbc__chckbxEnableCustomServer.insets = new Insets(0, 0, 0, 5); - gbc__chckbxEnableCustomServer.gridx = 0; - gbc__chckbxEnableCustomServer.gridy = 0; - _ontoUMLServerPanel.add(_chckbxEnableCustomServer, gbc__chckbxEnableCustomServer); - - _txtServerAddress = new JTextField(); - GridBagConstraints gbc__txtServerAddress = new GridBagConstraints(); - gbc__txtServerAddress.fill = GridBagConstraints.HORIZONTAL; - gbc__txtServerAddress.anchor = GridBagConstraints.NORTH; - gbc__txtServerAddress.gridx = 1; - gbc__txtServerAddress.gridy = 0; - _ontoUMLServerPanel.add(_txtServerAddress, gbc__txtServerAddress); - _txtServerAddress.setText(""); - _txtServerAddress.setColumns(10); - - JPanel _exportPanel = new JPanel(); - _optionsPanel.add(_exportPanel); - GridBagLayout gbl__exportPanel = new GridBagLayout(); - gbl__exportPanel.columnWidths = new int[]{290, 247, 0, 0}; - gbl__exportPanel.rowHeights = new int[]{0, 0}; - gbl__exportPanel.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE}; - gbl__exportPanel.rowWeights = new double[]{0.0, Double.MIN_VALUE}; - _exportPanel.setLayout(gbl__exportPanel); - - JPanel _smartPanel = new JPanel(); - _optionsPanel.add(_smartPanel); - GridBagLayout gbl__smartPanel = new GridBagLayout(); - gbl__smartPanel.columnWidths = new int[]{290, 247, 0, 0}; - gbl__smartPanel.rowHeights = new int[]{0, 0}; - gbl__smartPanel.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE}; - gbl__smartPanel.rowWeights = new double[]{0.0, Double.MIN_VALUE}; - _smartPanel.setLayout(gbl__smartPanel); - - _chckbxEnableAutoColoring = new JCheckBox("Enable Smart Paint"); - GridBagConstraints gbc__chckbxEnableAutoColoring = new GridBagConstraints(); - gbc__chckbxEnableAutoColoring.anchor = GridBagConstraints.WEST; - gbc__chckbxEnableAutoColoring.insets = new Insets(0, 0, 0, 5); - gbc__chckbxEnableAutoColoring.gridx = 0; - gbc__chckbxEnableAutoColoring.gridy = 0; - _smartPanel.add(_chckbxEnableAutoColoring, gbc__chckbxEnableAutoColoring); - - _chckbxEnableSmartModelling = new JCheckBox("Enable Smart Modelling"); - GridBagConstraints gbc__chckbxEnableSmartModelling = new GridBagConstraints(); - gbc__chckbxEnableSmartModelling.anchor = GridBagConstraints.WEST; - gbc__chckbxEnableSmartModelling.insets = new Insets(0, 0, 0, 5); - gbc__chckbxEnableSmartModelling.gridx = 0; - gbc__chckbxEnableSmartModelling.gridy = 1; - _smartPanel.add(_chckbxEnableSmartModelling, gbc__chckbxEnableSmartModelling); - - JPanel _controlButtonsPanel = new JPanel(); - GridBagConstraints gbc__controlButtonsPanel = new GridBagConstraints(); - gbc__controlButtonsPanel.anchor = GridBagConstraints.SOUTHEAST; - gbc__controlButtonsPanel.gridx = 0; - gbc__controlButtonsPanel.gridy = 2; - add(_controlButtonsPanel, gbc__controlButtonsPanel); - GridBagLayout gbl__controlButtonsPanel = new GridBagLayout(); - gbl__controlButtonsPanel.columnWidths = new int[]{135, 135, 0}; - gbl__controlButtonsPanel.rowHeights = new int[]{0, 0}; - gbl__controlButtonsPanel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE}; - gbl__controlButtonsPanel.rowWeights = new double[]{0.0, Double.MIN_VALUE}; - _controlButtonsPanel.setLayout(gbl__controlButtonsPanel); - - _btnApply = new JButton("Save"); - _btnApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateConfigurationsValues(configurations); - Configurations.getInstance().save(); - _dialog.close(); - OntoUMLPlugin.setConfigWindowOpen(false); - } - - }); - GridBagConstraints gbc__btnApply = new GridBagConstraints(); - gbc__btnApply.fill = GridBagConstraints.HORIZONTAL; - gbc__btnApply.insets = new Insets(0, 0, 0, 5); - gbc__btnApply.gridx = 0; - gbc__btnApply.gridy = 0; - _controlButtonsPanel.add(_btnApply, gbc__btnApply); - - _btnResetDefaults = new JButton("Reset Defaults"); - _btnResetDefaults.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - resetComponentsValues(); - updateComponentsStatus(); - } - - }); - GridBagConstraints gbc__btnResetDefaults = new GridBagConstraints(); - gbc__btnResetDefaults.fill = GridBagConstraints.HORIZONTAL; - gbc__btnResetDefaults.gridx = 1; - gbc__btnResetDefaults.gridy = 0; - _controlButtonsPanel.add(_btnResetDefaults, gbc__btnResetDefaults); - - pluginVersion = new JLabel("plugin version: " + OntoUMLPlugin.PLUGIN_VERSION_RELEASE); - pluginVersion.setEnabled(false); - - GridBagConstraints gbc__versionLabel = new GridBagConstraints(); - gbc__versionLabel.anchor = GridBagConstraints.SOUTHWEST; - gbc__versionLabel.gridx = 0; - gbc__versionLabel.gridy = 2; - - add(pluginVersion, gbc__versionLabel); - - - updateComponentsValues(configurations); - updateComponentsStatus(); - } - - /** - * - * Sets a direct reference to the container dialog after initialization. - * - * @param dialog - * - */ - public void setContainerDialog(IDialog dialog) { - this._dialog = dialog; - } - - /** - * - * Updates project configurations with components' information. - * - * @param configurations - * - */ - private void updateConfigurationsValues(ProjectConfigurations configurations) { - configurations.setCustomServerEnabled(_chckbxEnableCustomServer.isSelected()); - configurations.setServerURL(_txtServerAddress.getText()); - - configurations.setAutomaticColoringEnabled(_chckbxEnableAutoColoring.isSelected()); - configurations.setSmartModellingEnabled(_chckbxEnableSmartModelling.isSelected()); - } - - /** - * - * Updates components with project configurations' information. - * - * @param configurations - * - */ - private void updateComponentsValues(ProjectConfigurations configurations) { - _chckbxEnableCustomServer.setSelected(configurations.isCustomServerEnabled()); - _txtServerAddress.setText(configurations.getServerURL()); - - _chckbxEnableAutoColoring.setSelected(configurations.isAutomaticColoringEnabled()); - _chckbxEnableSmartModelling.setSelected(configurations.isSmartModellingEnabled()); - } - - /** - * - * Updates components with default values. - * - */ - private void resetComponentsValues() { - _chckbxEnableCustomServer.setSelected(ProjectConfigurations.DEFAULT_IS_CUSTOM_SERVER_ENABLED); - _txtServerAddress.setText(ProjectConfigurations.DEFAULT_SERVER_URL); - - _chckbxEnableAutoColoring.setSelected(ProjectConfigurations.DEFAULT_IS_AUTOMATIC_COLORING_ENABLED); - _chckbxEnableSmartModelling.setSelected(ProjectConfigurations.DEFAULT_IS_AUTOMATIC_COLORING_ENABLED); - } - - /** - * - * Updates enable/editable status of components based on their information. - * - */ - private void updateComponentsStatus() { - _chckbxEnableCustomServer.setEnabled(true); - _txtServerAddress.setEnabled(_chckbxEnableCustomServer.isSelected()); - _chckbxEnableAutoColoring.setEnabled(true); - _chckbxEnableSmartModelling.setEnabled(true); - } + private static final long serialVersionUID = 1L; + + private JCheckBox _chckbxEnableCustomServer; + private JTextField _txtServerAddress; + + private JCheckBox _chckbxEnableAutoColoring; + private JCheckBox _chckbxEnableSmartModelling; + + private JButton _btnApply; + private JButton _btnResetDefaults; + + private JLabel pluginVersion; + + private IDialog _dialog; + + /** ConfigurationsView constructor. */ + public ConfigurationsView(ProjectConfigurations configurations) { + setSize(new Dimension(670, 180)); + GridBagLayout gridBagLayout = new GridBagLayout(); + gridBagLayout.columnWidths = new int[] {670}; + gridBagLayout.rowHeights = new int[] {26, 82, 25, 0}; + gridBagLayout.columnWeights = new double[] {1.0}; + gridBagLayout.rowWeights = new double[] {0.0, 0.0, 1.0, Double.MIN_VALUE}; + setLayout(gridBagLayout); + + JPanel _optionsPanel = new JPanel(); + GridBagConstraints gbc__optionsPanel = new GridBagConstraints(); + gbc__optionsPanel.fill = GridBagConstraints.VERTICAL; + gbc__optionsPanel.gridx = 0; + gbc__optionsPanel.gridy = 1; + add(_optionsPanel, gbc__optionsPanel); + _optionsPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); + + JPanel _ontoUMLServerPanel = new JPanel(); + _optionsPanel.add(_ontoUMLServerPanel); + GridBagLayout gbl__ontoUMLServerPanel = new GridBagLayout(); + gbl__ontoUMLServerPanel.columnWidths = new int[] {290, 370, 0}; + gbl__ontoUMLServerPanel.rowHeights = new int[] {26, 0}; + gbl__ontoUMLServerPanel.columnWeights = new double[] {0.0, 0.0, Double.MIN_VALUE}; + gbl__ontoUMLServerPanel.rowWeights = new double[] {0.0, Double.MIN_VALUE}; + _ontoUMLServerPanel.setLayout(gbl__ontoUMLServerPanel); + + _chckbxEnableCustomServer = new JCheckBox("Use custom OntoUML Server instance."); + _chckbxEnableCustomServer.addChangeListener( + new ChangeListener() { + public void stateChanged(ChangeEvent e) { + updateComponentsStatus(); + } + }); + GridBagConstraints gbc__chckbxEnableCustomServer = new GridBagConstraints(); + gbc__chckbxEnableCustomServer.anchor = GridBagConstraints.WEST; + gbc__chckbxEnableCustomServer.insets = new Insets(0, 0, 0, 5); + gbc__chckbxEnableCustomServer.gridx = 0; + gbc__chckbxEnableCustomServer.gridy = 0; + _ontoUMLServerPanel.add(_chckbxEnableCustomServer, gbc__chckbxEnableCustomServer); + + _txtServerAddress = new JTextField(); + GridBagConstraints gbc__txtServerAddress = new GridBagConstraints(); + gbc__txtServerAddress.fill = GridBagConstraints.HORIZONTAL; + gbc__txtServerAddress.anchor = GridBagConstraints.NORTH; + gbc__txtServerAddress.gridx = 1; + gbc__txtServerAddress.gridy = 0; + _ontoUMLServerPanel.add(_txtServerAddress, gbc__txtServerAddress); + _txtServerAddress.setText(""); + _txtServerAddress.setColumns(10); + + JPanel _exportPanel = new JPanel(); + _optionsPanel.add(_exportPanel); + GridBagLayout gbl__exportPanel = new GridBagLayout(); + gbl__exportPanel.columnWidths = new int[] {290, 247, 0, 0}; + gbl__exportPanel.rowHeights = new int[] {0, 0}; + gbl__exportPanel.columnWeights = new double[] {0.0, 0.0, 0.0, Double.MIN_VALUE}; + gbl__exportPanel.rowWeights = new double[] {0.0, Double.MIN_VALUE}; + _exportPanel.setLayout(gbl__exportPanel); + + JPanel _smartPanel = new JPanel(); + _optionsPanel.add(_smartPanel); + GridBagLayout gbl__smartPanel = new GridBagLayout(); + gbl__smartPanel.columnWidths = new int[] {290, 247, 0, 0}; + gbl__smartPanel.rowHeights = new int[] {0, 0}; + gbl__smartPanel.columnWeights = new double[] {0.0, 0.0, 0.0, Double.MIN_VALUE}; + gbl__smartPanel.rowWeights = new double[] {0.0, Double.MIN_VALUE}; + _smartPanel.setLayout(gbl__smartPanel); + + _chckbxEnableAutoColoring = new JCheckBox("Enable Smart Paint"); + GridBagConstraints gbc__chckbxEnableAutoColoring = new GridBagConstraints(); + gbc__chckbxEnableAutoColoring.anchor = GridBagConstraints.WEST; + gbc__chckbxEnableAutoColoring.insets = new Insets(0, 0, 0, 5); + gbc__chckbxEnableAutoColoring.gridx = 0; + gbc__chckbxEnableAutoColoring.gridy = 0; + _smartPanel.add(_chckbxEnableAutoColoring, gbc__chckbxEnableAutoColoring); + + _chckbxEnableSmartModelling = new JCheckBox("Enable Smart Modelling"); + GridBagConstraints gbc__chckbxEnableSmartModelling = new GridBagConstraints(); + gbc__chckbxEnableSmartModelling.anchor = GridBagConstraints.WEST; + gbc__chckbxEnableSmartModelling.insets = new Insets(0, 0, 0, 5); + gbc__chckbxEnableSmartModelling.gridx = 0; + gbc__chckbxEnableSmartModelling.gridy = 1; + _smartPanel.add(_chckbxEnableSmartModelling, gbc__chckbxEnableSmartModelling); + + JPanel _controlButtonsPanel = new JPanel(); + GridBagConstraints gbc__controlButtonsPanel = new GridBagConstraints(); + gbc__controlButtonsPanel.anchor = GridBagConstraints.SOUTHEAST; + gbc__controlButtonsPanel.gridx = 0; + gbc__controlButtonsPanel.gridy = 2; + add(_controlButtonsPanel, gbc__controlButtonsPanel); + GridBagLayout gbl__controlButtonsPanel = new GridBagLayout(); + gbl__controlButtonsPanel.columnWidths = new int[] {135, 135, 0}; + gbl__controlButtonsPanel.rowHeights = new int[] {0, 0}; + gbl__controlButtonsPanel.columnWeights = new double[] {0.0, 0.0, Double.MIN_VALUE}; + gbl__controlButtonsPanel.rowWeights = new double[] {0.0, Double.MIN_VALUE}; + _controlButtonsPanel.setLayout(gbl__controlButtonsPanel); + + _btnApply = new JButton("Save"); + _btnApply.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateConfigurationsValues(configurations); + Configurations.getInstance().save(); + _dialog.close(); + OntoUMLPlugin.setConfigWindowOpen(false); + } + }); + GridBagConstraints gbc__btnApply = new GridBagConstraints(); + gbc__btnApply.fill = GridBagConstraints.HORIZONTAL; + gbc__btnApply.insets = new Insets(0, 0, 0, 5); + gbc__btnApply.gridx = 0; + gbc__btnApply.gridy = 0; + _controlButtonsPanel.add(_btnApply, gbc__btnApply); + + _btnResetDefaults = new JButton("Reset Defaults"); + _btnResetDefaults.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + resetComponentsValues(); + updateComponentsStatus(); + } + }); + GridBagConstraints gbc__btnResetDefaults = new GridBagConstraints(); + gbc__btnResetDefaults.fill = GridBagConstraints.HORIZONTAL; + gbc__btnResetDefaults.gridx = 1; + gbc__btnResetDefaults.gridy = 0; + _controlButtonsPanel.add(_btnResetDefaults, gbc__btnResetDefaults); + + pluginVersion = new JLabel("plugin version: " + OntoUMLPlugin.PLUGIN_VERSION_RELEASE); + pluginVersion.setEnabled(false); + + GridBagConstraints gbc__versionLabel = new GridBagConstraints(); + gbc__versionLabel.anchor = GridBagConstraints.SOUTHWEST; + gbc__versionLabel.gridx = 0; + gbc__versionLabel.gridy = 2; + + add(pluginVersion, gbc__versionLabel); + + updateComponentsValues(configurations); + updateComponentsStatus(); + } + + /** + * Sets a direct reference to the container dialog after initialization. + * + * @param dialog + */ + public void setContainerDialog(IDialog dialog) { + this._dialog = dialog; + } + + /** + * Updates project configurations with components' information. + * + * @param configurations + */ + private void updateConfigurationsValues(ProjectConfigurations configurations) { + configurations.setCustomServerEnabled(_chckbxEnableCustomServer.isSelected()); + configurations.setServerURL(_txtServerAddress.getText()); + + configurations.setAutomaticColoringEnabled(_chckbxEnableAutoColoring.isSelected()); + configurations.setSmartModellingEnabled(_chckbxEnableSmartModelling.isSelected()); + } + + /** + * Updates components with project configurations' information. + * + * @param configurations + */ + private void updateComponentsValues(ProjectConfigurations configurations) { + _chckbxEnableCustomServer.setSelected(configurations.isCustomServerEnabled()); + _txtServerAddress.setText(configurations.getServerURL()); + + _chckbxEnableAutoColoring.setSelected(configurations.isAutomaticColoringEnabled()); + _chckbxEnableSmartModelling.setSelected(configurations.isSmartModellingEnabled()); + } + + /** Updates components with default values. */ + private void resetComponentsValues() { + _chckbxEnableCustomServer.setSelected(ProjectConfigurations.DEFAULT_IS_CUSTOM_SERVER_ENABLED); + _txtServerAddress.setText(ProjectConfigurations.DEFAULT_SERVER_URL); + + _chckbxEnableAutoColoring.setSelected( + ProjectConfigurations.DEFAULT_IS_AUTOMATIC_COLORING_ENABLED); + _chckbxEnableSmartModelling.setSelected( + ProjectConfigurations.DEFAULT_IS_AUTOMATIC_COLORING_ENABLED); + } + + /** Updates enable/editable status of components based on their information. */ + private void updateComponentsStatus() { + _chckbxEnableCustomServer.setEnabled(true); + _txtServerAddress.setEnabled(_chckbxEnableCustomServer.isSelected()); + _chckbxEnableAutoColoring.setEnabled(true); + _chckbxEnableSmartModelling.setEnabled(true); + } } diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/ExportToGUFOView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/ExportToGUFOView.java deleted file mode 100644 index 5ba3e49b..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/ExportToGUFOView.java +++ /dev/null @@ -1,974 +0,0 @@ -package it.unibz.inf.ontouml.vp.views; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.awt.event.KeyEvent; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Vector; - -import javax.swing.DefaultCellEditor; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTabbedPane; -import javax.swing.JTable; -import javax.swing.JTextField; -import javax.swing.table.DefaultTableModel; -import javax.swing.table.TableColumnModel; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.TreePath; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.diagram.IDiagramUIModel; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.IProject; -import com.vp.plugin.model.factory.IModelElementFactory; -import com.vp.plugin.view.IDialog; - -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.ProjectConfigurations; -import it.unibz.inf.ontouml.vp.utils.ServerRequest; - -public class ExportToGUFOView extends JPanel { - private static final long serialVersionUID = 1L; - - private JTextField IRItxt; - private JComboBox formatBox; - private JComboBox uriFormatBox; - private JComboBox inverseBox; - private JComboBox objectBox; - private JComboBox analysisBox; - private JComboBox packagesBox; - - private JComboBox namesBox; - private JComboBox languagesBox; - private JComboBox packagesIdBox; - private JTabbedPane tabbedPane; - private JCheckBoxTree packageTree; - private JCheckBoxTree diagramTree; - - private JTable table; - private JTable table2; - - JPanel treePanelPackage; - JPanel treePanelDiagram; - - private JButton btnExport; - private JButton btnCancel; - - private IDialog _dialog; - - private boolean isToExport; - private boolean isOpen; - - private HashSet elementsPackageTree = new HashSet<>(); - private HashSet elementsDiagramTree = new HashSet<>(); - - private IModelElement[] elementsMapping; - private IModelElement[] packagesMapping; - - public ExportToGUFOView(ProjectConfigurations configurations, ServerRequest request) { - setSize(new Dimension(680, 550)); - setLayout(new GridLayout(1, 1)); - - JTabbedPane mainTabbedPane = new JTabbedPane(); - - JPanel mainPanel = new JPanel(); - JPanel elementMappingPanel = new JPanel(); - JPanel packageMappingPanel = new JPanel(); - - mainTabbedPane.add(mainPanel, "Basic Settings"); - mainTabbedPane.add(elementMappingPanel, "Element Mapping"); - mainTabbedPane.add(packageMappingPanel, "Package Mapping"); - - JPanel optionsPanelLeft = new JPanel(); - JPanel optionsPanelRight = new JPanel(); - JPanel treePanel = new JPanel(); - JPanel buttonsPanel = new JPanel(); - JPanel buttonsPanelTable1 = new JPanel(); - JPanel buttonsPanelTable2 = new JPanel(); - - mainPanel.setLayout(new GridBagLayout()); - elementMappingPanel.setLayout(new GridBagLayout()); - packageMappingPanel.setLayout(new GridBagLayout()); - optionsPanelLeft.setLayout(new GridBagLayout()); - optionsPanelRight.setLayout(new GridBagLayout()); - treePanel.setLayout(new GridBagLayout()); - buttonsPanel.setLayout(new GridBagLayout()); - buttonsPanelTable1.setLayout(new GridBagLayout()); - buttonsPanelTable2.setLayout(new GridBagLayout()); - - mainPanel.setPreferredSize(new Dimension(650, 540)); - elementMappingPanel.setPreferredSize(new Dimension(650, 480)); - packageMappingPanel.setPreferredSize(new Dimension(650, 540)); - optionsPanelLeft.setPreferredSize(new Dimension(280, 120)); - optionsPanelRight.setPreferredSize(new Dimension(320, 120)); - treePanel.setPreferredSize(new Dimension(600, 300)); - buttonsPanel.setPreferredSize(new Dimension(600, 40)); - buttonsPanelTable1.setPreferredSize(new Dimension(280, 40)); - - GridBagConstraints gbc_main = new GridBagConstraints(); - gbc_main.insets = new Insets(1, 1, 1, 1); - gbc_main.anchor = GridBagConstraints.FIRST_LINE_START; - gbc_main.weightx = 0.5; - gbc_main.weighty = 1; - gbc_main.gridx = 0; - gbc_main.gridy = 0; - mainPanel.add(optionsPanelLeft, gbc_main); - gbc_main.anchor = GridBagConstraints.FIRST_LINE_END; - gbc_main.weightx = 0.5; - gbc_main.weighty = 0.5; - gbc_main.gridx = 1; - gbc_main.gridy = 0; - mainPanel.add(optionsPanelRight, gbc_main); - gbc_main.anchor = GridBagConstraints.PAGE_START; - gbc_main.weightx = 1.0; - gbc_main.weighty = 0.8; - gbc_main.gridwidth = 4; - gbc_main.gridx = 0; - gbc_main.gridy = 1; - gbc_main.fill = GridBagConstraints.HORIZONTAL; - mainPanel.add(treePanel, gbc_main); - gbc_main.anchor = GridBagConstraints.FIRST_LINE_END; - gbc_main.weightx = 0.5; - gbc_main.weighty = 0.5; - gbc_main.gridx = 0; - gbc_main.gridy = 2; - mainPanel.add(buttonsPanel, gbc_main); - - JLabel iriLabel = new JLabel("Base IRI:"); - JLabel formatLabel = new JLabel("Output format:"); - JLabel URIformatLabel = new JLabel("Create URIs using:"); - - IRItxt = new JTextField(); - - String[] formatStrings = {"Turtle", "N-Triples", "N-Quads"}; - formatBox = new JComboBox<>(formatStrings); - ((JLabel) formatBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); - - String[] uriFormatBoxString = {"name", "id"}; - uriFormatBox = new JComboBox<>(uriFormatBoxString); - ((JLabel) uriFormatBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); - IRItxt.setText("http://example.com"); - - iriLabel.setPreferredSize(new Dimension(120, 28)); - formatLabel.setPreferredSize(new Dimension(120, 28)); - URIformatLabel.setPreferredSize(new Dimension(120, 28)); - IRItxt.setPreferredSize(new Dimension(140, 28)); - formatBox.setPreferredSize(new Dimension(140, 28)); - uriFormatBox.setPreferredSize(new Dimension(140, 28)); - - GridBagConstraints gbc_insidePanelLeft = new GridBagConstraints(); - gbc_insidePanelLeft.fill = GridBagConstraints.BOTH; - gbc_insidePanelLeft.insets = new Insets(2, 2, 2, 0); - gbc_insidePanelLeft.weightx = 0.5; - gbc_insidePanelLeft.gridx = 0; - gbc_insidePanelLeft.gridy = 0; - gbc_insidePanelLeft.anchor = GridBagConstraints.WEST; - optionsPanelLeft.add(iriLabel, gbc_insidePanelLeft); - gbc_insidePanelLeft.weightx = 0.5; - gbc_insidePanelLeft.gridx = 1; - gbc_insidePanelLeft.gridy = 0; - optionsPanelLeft.add(IRItxt, gbc_insidePanelLeft); - gbc_insidePanelLeft.weightx = 0.5; - gbc_insidePanelLeft.gridx = 0; - gbc_insidePanelLeft.gridy = 1; - optionsPanelLeft.add(formatLabel, gbc_insidePanelLeft); - gbc_insidePanelLeft.weightx = 0.5; - gbc_insidePanelLeft.gridx = 1; - gbc_insidePanelLeft.gridy = 1; - optionsPanelLeft.add(formatBox, gbc_insidePanelLeft); - gbc_insidePanelLeft.weightx = 0.5; - gbc_insidePanelLeft.gridx = 0; - gbc_insidePanelLeft.gridy = 2; - optionsPanelLeft.add(URIformatLabel, gbc_insidePanelLeft); - gbc_insidePanelLeft.weightx = 0.5; - gbc_insidePanelLeft.gridx = 1; - gbc_insidePanelLeft.gridy = 2; - optionsPanelLeft.add(uriFormatBox, gbc_insidePanelLeft); - - JLabel inverseLabel = new JLabel("Create inverse properties:"); - JLabel objectLabel = new JLabel("Minimize property creation:"); - JLabel analysisLabel = new JLabel("Run pre analysis:"); - JLabel prefixPackageLabel = new JLabel("Add prefix per package:"); - - String[] inverseBoxString = {"false", "true"}; - inverseBox = new JComboBox<>(inverseBoxString); - ((JLabel) inverseBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); - - String[] objectBoxString = {"false", "true"}; - objectBox = new JComboBox<>(objectBoxString); - ((JLabel) objectBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); - - String[] analysisBoxString = {"true", "false"}; - analysisBox = new JComboBox<>(analysisBoxString); - ((JLabel) analysisBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); - - String[] packagesBoxString = {"false", "true"}; - packagesBox = new JComboBox<>(packagesBoxString); - ((JLabel) packagesBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); - - inverseLabel.setPreferredSize(new Dimension(180, 28)); - objectLabel.setPreferredSize(new Dimension(180, 28)); - analysisLabel.setPreferredSize(new Dimension(180, 28)); - prefixPackageLabel.setPreferredSize(new Dimension(180, 28)); - inverseBox.setPreferredSize(new Dimension(90, 28)); - objectBox.setPreferredSize(new Dimension(90, 28)); - analysisBox.setPreferredSize(new Dimension(90, 28)); - packagesBox.setPreferredSize(new Dimension(90, 28)); - - GridBagConstraints gbc_insidePanelRight = new GridBagConstraints(); - gbc_insidePanelRight.fill = GridBagConstraints.BOTH; - gbc_insidePanelRight.insets = new Insets(2, 0, 2, 0); - gbc_insidePanelRight.weightx = 0.5; - gbc_insidePanelRight.gridx = 0; - gbc_insidePanelRight.gridy = 0; - gbc_insidePanelRight.anchor = GridBagConstraints.WEST; - optionsPanelRight.add(objectLabel, gbc_insidePanelRight); - gbc_insidePanelRight.weightx = 0.5; - gbc_insidePanelRight.gridx = 1; - gbc_insidePanelRight.gridy = 0; - gbc_insidePanelRight.anchor = GridBagConstraints.EAST; - optionsPanelRight.add(objectBox, gbc_insidePanelRight); - gbc_insidePanelRight.weightx = 0.5; - gbc_insidePanelRight.gridx = 0; - gbc_insidePanelRight.gridy = 1; - gbc_insidePanelRight.anchor = GridBagConstraints.WEST; - optionsPanelRight.add(inverseLabel, gbc_insidePanelRight); - gbc_insidePanelRight.weightx = 0.5; - gbc_insidePanelRight.gridx = 1; - gbc_insidePanelRight.gridy = 1; - gbc_insidePanelRight.anchor = GridBagConstraints.EAST; - optionsPanelRight.add(inverseBox, gbc_insidePanelRight); - gbc_insidePanelRight.weightx = 0.5; - gbc_insidePanelRight.gridx = 0; - gbc_insidePanelRight.gridy = 2; - gbc_insidePanelRight.anchor = GridBagConstraints.WEST; - optionsPanelRight.add(prefixPackageLabel, gbc_insidePanelRight); - gbc_insidePanelRight.weightx = 0.5; - gbc_insidePanelRight.gridx = 1; - gbc_insidePanelRight.gridy = 2; - gbc_insidePanelRight.anchor = GridBagConstraints.EAST; - optionsPanelRight.add(packagesBox, gbc_insidePanelRight); - gbc_insidePanelRight.weightx = 0.5; - gbc_insidePanelRight.gridx = 0; - gbc_insidePanelRight.gridy = 3; - gbc_insidePanelRight.anchor = GridBagConstraints.WEST; - optionsPanelRight.add(analysisLabel, gbc_insidePanelRight); - gbc_insidePanelRight.weightx = 0.5; - gbc_insidePanelRight.gridx = 1; - gbc_insidePanelRight.gridy = 3; - gbc_insidePanelRight.anchor = GridBagConstraints.EAST; - optionsPanelRight.add(analysisBox, gbc_insidePanelRight); - - JPanel packagePanel = new JPanel(); - JPanel diagramPanel = new JPanel(); - - tabbedPane = new JTabbedPane(); - packageTree = new JCheckBoxTree("package"); - diagramTree = new JCheckBoxTree("diagram"); - - JScrollPane scrollableTextAreaPackage = new JScrollPane(packageTree); - JScrollPane scrollableTextAreaDiagram = new JScrollPane(diagramTree); - - scrollableTextAreaPackage.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - scrollableTextAreaPackage.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - - scrollableTextAreaDiagram.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); - scrollableTextAreaDiagram.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); - - packagePanel.setLayout(new GridLayout(1, 1)); - packagePanel.setPreferredSize(new Dimension(550, 270)); - - diagramPanel.setLayout(new GridLayout(1, 1)); - diagramPanel.setPreferredSize(new Dimension(550, 270)); - - packagePanel.add(scrollableTextAreaPackage); - - diagramPanel.add(scrollableTextAreaDiagram); - - tabbedPane.addTab("Package Explorer", packagePanel); - tabbedPane.setMnemonicAt(0, KeyEvent.VK_1); - - tabbedPane.addTab("Diagram Explorer", diagramPanel); - tabbedPane.setMnemonicAt(1, KeyEvent.VK_2); - - tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); - - treePanel.add(tabbedPane); - treePanel.setLayout(new GridLayout(1, 1)); - - btnExport = new JButton("Export"); - btnCancel = new JButton("Cancel"); - - btnExport.setPreferredSize(new Dimension(80, 35)); - btnCancel.setPreferredSize(new Dimension(80, 35)); - - btnExport.addActionListener(actionEvent -> { - if (tabbedPane.getSelectedIndex() == 0) - saveSelectedElements("Package Tree"); - else - saveSelectedElements("Diagram Tree"); - - updateConfigurationsValues(configurations); - Configurations.getInstance().save(); - isToExport = true; - isOpen = false; - _dialog.close(); - Thread thread = new Thread(request); - thread.start(); - }); - - btnCancel.addActionListener(actionEvent -> { - isToExport = false; - isOpen = false; - request.doStop(); - _dialog.close(); - OntoUMLPlugin.setExportToGUFOWindowOpen(false); - }); - - GridBagConstraints gbc_buttonsPanel = new GridBagConstraints(); - gbc_buttonsPanel.fill = GridBagConstraints.HORIZONTAL; - gbc_buttonsPanel.insets = new Insets(2, 2, 2, 15); - gbc_buttonsPanel.weightx = 0.5; - gbc_buttonsPanel.gridx = 0; - gbc_buttonsPanel.gridy = 0; - gbc_buttonsPanel.anchor = GridBagConstraints.PAGE_END; - buttonsPanel.add(btnExport, gbc_buttonsPanel); - gbc_buttonsPanel.weightx = 0.5; - gbc_buttonsPanel.gridx = 1; - gbc_buttonsPanel.gridy = 0; - buttonsPanel.add(btnCancel, gbc_buttonsPanel); - - // TABLE 1 - - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - - final String[] anyLevelElements = {IModelElementFactory.MODEL_TYPE_CLASS, - IModelElementFactory.MODEL_TYPE_ATTRIBUTE, IModelElementFactory.MODEL_TYPE_ASSOCIATION, - IModelElementFactory.MODEL_TYPE_ASSOCIATION_END,}; - - elementsMapping = project.toAllLevelModelElementArray(anyLevelElements); - String[] nameElements = new String[elementsMapping.length]; - - for (int i = 0; i < elementsMapping.length; i++) - nameElements[i] = NameUtil.getDisplayName(elementsMapping[i]); - - namesBox = new JComboBox<>(nameElements); - ((JLabel) namesBox.getRenderer()).setHorizontalAlignment(JLabel.LEFT); - - languagesBox = new JComboBox<>(getLanguagesCode()); - ((JLabel) languagesBox.getRenderer()).setHorizontalAlignment(JLabel.LEFT); - - String[][] data; - String[] columnNamesArr; - ArrayList columnNamesList; - DefaultTableModel defaultTableModel; - TableColumnModel tableColumnModel; - JScrollPane scrollPane; - JButton addButton; - JButton deleteButton; - - columnNamesList = new ArrayList<>(); - columnNamesList.add("Element"); - columnNamesList.add("Language"); - columnNamesList.add("Text"); - - data = new String[1][columnNamesList.size()]; - - columnNamesArr = new String[columnNamesList.size()]; - for (int i = 0; i < columnNamesList.size(); i++) { - columnNamesArr[i] = columnNamesList.get(i); - data[0][i] = ""; - } - - // defaultTableModel = new DefaultTableModel(data, columnNamesArr); - defaultTableModel = new DefaultTableModel(null, columnNamesArr); - - table = new JTable(defaultTableModel); - tableColumnModel = table.getColumnModel(); - table.setGridColor(Color.LIGHT_GRAY); - - for (int i = 0; i < columnNamesList.size(); i++) { - tableColumnModel.getColumn(i).setPreferredWidth(columnNamesList.get(i).length()); - } - table.setPreferredScrollableViewportSize(table.getPreferredSize()); - scrollPane = new JScrollPane(table); - - namesBox.setEditable(false); - languagesBox.setEditable(false); - table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(namesBox)); - table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(languagesBox)); - table.getColumnModel().getColumn(0).setPreferredWidth(150); - table.getColumnModel().getColumn(1).setPreferredWidth(20); - table.getColumnModel().getColumn(2).setPreferredWidth(80); - table.setRowHeight(28); - - addButton = new JButton("Add"); - deleteButton = new JButton("Delete"); - - addButton.addActionListener(actionEvent -> { - Vector rowData = new Vector<>(); - rowData.add(namesBox.getItemAt(0)); - rowData.add(languagesBox.getItemAt(0)); - rowData.add(""); - defaultTableModel.addRow(rowData); - - table.validate(); - }); - - deleteButton.addActionListener(actionEvent -> { - // Vector rowData = null; - int rowCount = defaultTableModel.getRowCount(); - if (rowCount > 0) { - defaultTableModel.removeRow(rowCount - 1); - table.validate(); - } - }); - - GridBagConstraints gbc_buttonsPanelTable1 = new GridBagConstraints(); - gbc_buttonsPanelTable1.fill = GridBagConstraints.BOTH; - gbc_buttonsPanelTable1.insets = new Insets(1, 1, 1, 1); - gbc_buttonsPanelTable1.weightx = 0.5; - gbc_buttonsPanelTable1.gridx = 0; - gbc_buttonsPanelTable1.gridy = 0; - gbc_buttonsPanelTable1.anchor = GridBagConstraints.PAGE_END; - buttonsPanelTable1.add(addButton, gbc_buttonsPanelTable1); - gbc_buttonsPanelTable1.weightx = 0.5; - gbc_buttonsPanelTable1.gridx = 1; - gbc_buttonsPanelTable1.gridy = 0; - buttonsPanelTable1.add(deleteButton, gbc_buttonsPanelTable1); - - scrollPane.setPreferredSize(new Dimension(550, 400)); - buttonsPanelTable1.setPreferredSize(new Dimension(400, 30)); - - GridBagConstraints gbc_mappingTable1 = new GridBagConstraints(); - // gbc_insidePanelLeft.fill = GridBagConstraints.HORIZONTAL; - gbc_mappingTable1.insets = new Insets(1, 1, 1, 1); - gbc_mappingTable1.gridx = 0; - gbc_mappingTable1.gridy = 0; - elementMappingPanel.add(scrollPane, gbc_mappingTable1); - gbc_mappingTable1.gridx = 0; - gbc_mappingTable1.gridy = 1; - gbc_mappingTable1.anchor = GridBagConstraints.EAST; - elementMappingPanel.add(buttonsPanelTable1, gbc_mappingTable1); - - // TABLE 2 - - String[] packages = {IModelElementFactory.MODEL_TYPE_PACKAGE, IModelElementFactory.MODEL_TYPE_MODEL}; - - packagesMapping = project.toAllLevelModelElementArray(packages); - String[] nameElementsPack = new String[packagesMapping.length + 1]; - nameElementsPack[0] = project.getName(); - - for (int i = 0; i < packagesMapping.length; i++) - nameElementsPack[i + 1] = packagesMapping[i].getName(); - - packagesIdBox = new JComboBox<>(nameElementsPack); - ((JLabel) packagesIdBox.getRenderer()).setHorizontalAlignment(JLabel.LEFT); - - String[][] data_table2; - String[] columnNamesArr_table2; - ArrayList columnNamesList_table2; - DefaultTableModel defaultTableModel_table2; - TableColumnModel tableColumnModel_table2; - JScrollPane scrollPane_table2; - JButton addButton_table2; - JButton deleteButton_table2; - - columnNamesList_table2 = new ArrayList<>(); - columnNamesList_table2.add("Package"); - columnNamesList_table2.add("Prefix"); - columnNamesList_table2.add("URI"); - - data_table2 = new String[1][columnNamesList_table2.size()]; - - columnNamesArr_table2 = new String[columnNamesList_table2.size()]; - for (int i = 0; i < columnNamesList_table2.size(); i++) { - columnNamesArr_table2[i] = columnNamesList_table2.get(i); - data_table2[0][i] = ""; - } - -// defaultTableModel_table2 = new DefaultTableModel(data_table2, columnNamesArr_table2); - - defaultTableModel_table2 = new DefaultTableModel(null, columnNamesArr_table2); - - table2 = new JTable(defaultTableModel_table2); - table2.setGridColor(Color.LIGHT_GRAY); - tableColumnModel_table2 = table2.getColumnModel(); - - for (int i = 0; i < columnNamesList_table2.size(); i++) { - tableColumnModel_table2.getColumn(i).setPreferredWidth(columnNamesList_table2.get(i).length()); - } - table2.setPreferredScrollableViewportSize(table2.getPreferredSize()); - scrollPane_table2 = new JScrollPane(table2); - - packagesIdBox.setEditable(false); - table2.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(packagesIdBox)); - table2.getColumnModel().getColumn(0).setPreferredWidth(150); - table2.getColumnModel().getColumn(1).setPreferredWidth(20); - table2.getColumnModel().getColumn(2).setPreferredWidth(80); - table2.setRowHeight(28); - - addButton_table2 = new JButton("Add"); - deleteButton_table2 = new JButton("Delete"); - - addButton_table2.addActionListener(actionEvent -> { - Vector rowData = new Vector<>(); - rowData.add(packagesIdBox.getItemAt(0)); - rowData.add(""); - rowData.add(""); - defaultTableModel_table2.addRow(rowData); - table2.validate(); - }); - - deleteButton_table2.addActionListener(actionEvent -> { - // Vector rowData = null; - int rowCount = defaultTableModel_table2.getRowCount(); - if (rowCount > 0) { - defaultTableModel_table2.removeRow(rowCount - 1); - table2.validate(); - } - }); - - GridBagConstraints gbc_buttonsPanelTable2 = new GridBagConstraints(); - gbc_buttonsPanelTable2.fill = GridBagConstraints.BOTH; - gbc_buttonsPanelTable2.insets = new Insets(1, 1, 1, 1); - gbc_buttonsPanelTable2.weightx = 0.5; - gbc_buttonsPanelTable2.gridx = 0; - gbc_buttonsPanelTable2.gridy = 0; - gbc_buttonsPanelTable2.anchor = GridBagConstraints.PAGE_END; - buttonsPanelTable2.add(addButton_table2, gbc_buttonsPanelTable2); - gbc_buttonsPanelTable2.weightx = 0.5; - gbc_buttonsPanelTable2.gridx = 1; - gbc_buttonsPanelTable2.gridy = 0; - buttonsPanelTable2.add(deleteButton_table2, gbc_buttonsPanelTable2); - - scrollPane_table2.setPreferredSize(new Dimension(550, 400)); - buttonsPanelTable2.setPreferredSize(new Dimension(400, 30)); - - GridBagConstraints gbc_mappingTable2 = new GridBagConstraints(); - // gbc_insidePanelLeft.fill = GridBagConstraints.HORIZONTAL; - gbc_mappingTable2.insets = new Insets(1, 1, 1, 1); - gbc_mappingTable2.gridx = 0; - gbc_mappingTable2.gridy = 0; - packageMappingPanel.add(scrollPane_table2, gbc_mappingTable2); - gbc_mappingTable2.gridx = 0; - gbc_mappingTable2.gridy = 1; - gbc_mappingTable2.anchor = GridBagConstraints.EAST; - packageMappingPanel.add(buttonsPanelTable2, gbc_mappingTable2); - - add(mainTabbedPane); - - updateComponentsValues(configurations); - - } - - - public JTextField getIRItxt() { - return IRItxt; - } - - - public void setIRItxt(JTextField iRItxt) { - IRItxt = iRItxt; - } - - - public JComboBox getFormatBox() { - return formatBox; - } - - - public void setFormatBox(JComboBox formatBox) { - this.formatBox = formatBox; - } - - - public JComboBox getUriFormatBox() { - return uriFormatBox; - } - - - public void setUriFormatBox(JComboBox uriFormatBox) { - this.uriFormatBox = uriFormatBox; - } - - - public JComboBox getInverseBox() { - return inverseBox; - } - - - public void setInverseBox(JComboBox inverseBox) { - this.inverseBox = inverseBox; - } - - - public JComboBox getObjectBox() { - return objectBox; - } - - - public void setObjectBox(JComboBox objectBox) { - this.objectBox = objectBox; - } - - - public JComboBox getAnalysisBox() { - return analysisBox; - } - - - public void setAnalysisBox(JComboBox analysisBox) { - this.analysisBox = analysisBox; - } - - - public JComboBox getNamesBox() { - return namesBox; - } - - - public void setNamesBox(JComboBox namesBox) { - this.namesBox = namesBox; - } - - - public static long getSerialversionuid() { - return serialVersionUID; - } - - - public JComboBox getLanguagesBox() { - return languagesBox; - } - - - public JComboBox getPackagesIdBox() { - return packagesIdBox; - } - - - public JTabbedPane getTabbedPane() { - return tabbedPane; - } - - - public JCheckBoxTree getPackageTree() { - return packageTree; - } - - - public JCheckBoxTree getDiagramTree() { - return diagramTree; - } - - - public JTable getTable() { - return table; - } - - - public JTable getTable2() { - return table2; - } - - - public JPanel getTreePanelPackage() { - return treePanelPackage; - } - - - public JPanel getTreePanelDiagram() { - return treePanelDiagram; - } - - - public JButton getBtnExport() { - return btnExport; - } - - - public JButton getBtnCancel() { - return btnCancel; - } - - - public IDialog get_dialog() { - return _dialog; - } - - - public HashSet getElementsPackageTree() { - return elementsPackageTree; - } - - - public HashSet getElementsDiagramTree() { - return elementsDiagramTree; - } - - - public IModelElement[] getElementsMapping() { - return elementsMapping; - } - - - public IModelElement[] getPackagesMapping() { - return packagesMapping; - } - - - protected JComponent makeTextPanel(String text) { - JPanel panel = new JPanel(false); - JLabel filler = new JLabel(text); - filler.setHorizontalAlignment(JLabel.CENTER); - panel.setLayout(new GridLayout(1, 1)); - panel.add(filler); - return panel; - } - - public boolean getIsToExport() { - return isToExport; - } - - public boolean getIsOpen() { - return isOpen; - } - - private static String[] getLanguagesCode() { - - return new String[]{"default", "aa", "ab", "ae", "af", "ak", "am", "an", "ar", "as", "av", "ay", "az", "ba", - "be", "bg", "bh", "bm", "bi", "bn", "bo", "br", "bs", "ca", "ce", "ch", "co", "cr", "cs", "cu", "cv", - "cy", "da", "de", "dv", "dz", "ee", "el", "en", "eo", "es", "et", "eu", "fa", "ff", "fi", "fj", "fo", - "fr", "fy", "ga", "gd", "gl", "gn", "gu", "gv", "ha", "he", "hi", "ho", "hr", "ht", "hu", "hy", "hz", - "ia", "id", "ie", "ig", "ii", "ik", "io", "is", "it", "iu", "ja", "jv", "ka", "kg", "ki", "kj", "kk", - "kl", "km", "kn", "ko", "kr", "ks", "ku", "kv", "kw", "ky", "la", "lb", "lg", "li", "ln", "lo", "lt", - "lu", "lv", "mg", "mh", "mi", "mk", "ml", "mn", "mr", "ms", "mt", "my", "na", "nb", "nd", "ne", "ng", - "nl", "nn", "no", "nr", "nv", "ny", "oc", "oj", "om", "or", "os", "pa", "pi", "pl", "ps", "pt", "qu", - "rm", "rn", "ro", "ru", "rw", "sa", "sc", "sd", "se", "sg", "si", "sk", "sl", "sm", "sn", "so", "sq", - "sr", "ss", "st", "su", "sv", "sw", "ta", "te", "tg", "th", "ti", "tk", "tl", "tn", "to", "tr", "ts", - "tt", "tw", "ty", "ug", "uk", "ur", "uz", "ve", "vi", "vo", "wa", "wo", "xh", "yi", "yo", "za", "zh", - "zu"}; - } - - /** - * Sets a direct reference to the container dialog after initialization. - */ - public void setContainerDialog(IDialog dialog) { - this._dialog = dialog; - } - - /** - * Updates project configurations with components' information. - */ - private void updateConfigurationsValues(ProjectConfigurations configurations) { - configurations.setExportGUFOIRI(IRItxt.getText()); - configurations.setExportGUFOFormat(formatBox.getSelectedItem().toString()); - configurations.setExportGUFOURIFormat(uriFormatBox.getSelectedItem().toString()); - configurations.setExportGUFOInverseBox(inverseBox.getSelectedItem().toString()); - configurations.setExportGUFOObjectBox(objectBox.getSelectedItem().toString()); - configurations.setExportGUFOAnalysisBox(analysisBox.getSelectedItem().toString()); - configurations.setExportGUFOPackagesBox(packagesBox.getSelectedItem().toString()); - configurations.setExportGUFOElementMapping(getTableElementMapping()); - configurations.setExportGUFOPackageMapping(getTablePackageMapping()); - - if (tabbedPane.getSelectedIndex() == 0) - configurations.setExportGUFOElementsPackageTree(elementsPackageTree); - else - configurations.setExportGUFOElementsDiagramTree(elementsDiagramTree); - } - - /** - * Updates components with project configurations' information. - * - * @param configurations - */ - private void updateComponentsValues(ProjectConfigurations configurations) { - - if (configurations.getExportGUFOIRI() != null && !configurations.getExportGUFOIRI().equals("")) - IRItxt.setText(configurations.getExportGUFOIRI()); - - if (configurations.getExportGUFOFormat() != null && !configurations.getExportGUFOFormat().equals("")) - formatBox.setSelectedItem(configurations.getExportGUFOFormat()); - - if (configurations.getExportGUFOURIFormat() != null && !configurations.getExportGUFOURIFormat().equals("")) - uriFormatBox.setSelectedItem(configurations.getExportGUFOURIFormat()); - - if (configurations.getExportGUFOElementsPackageTree() != null) - packageTree.setNodesCheck(configurations.getExportGUFOElementsPackageTree()); - - if (configurations.getExportGUFOElementsDiagramTree() != null) - diagramTree.setNodesCheck(configurations.getExportGUFOElementsDiagramTree()); - - if (configurations.getExportGUFOInverseBox() != null) - inverseBox.setSelectedItem(configurations.getExportGUFOInverseBox()); - - if (configurations.getExportGUFOObjectBox() != null) - objectBox.setSelectedItem(configurations.getExportGUFOObjectBox()); - - if (configurations.getExportGUFOAnalysisBox() != null) - analysisBox.setSelectedItem(configurations.getExportGUFOAnalysisBox()); - - if (configurations.getExportGUFOPackagesBox() != null) - packagesBox.setSelectedItem(configurations.getExportGUFOPackagesBox()); - } - - private void saveSelectedElements(String tree) { - - TreePath[] paths; - HashSet aux; - - if (tree.equals("Package Tree")) { - paths = packageTree.getCheckedPaths(); - aux = this.elementsPackageTree; - } else { - paths = diagramTree.getCheckedPaths(); - aux = this.elementsDiagramTree; - } - - for (TreePath path : paths) { - Object[] object = path.getPath(); - for (Object o : object) { - - if (o instanceof DefaultMutableTreeNode) { - - DefaultMutableTreeNode node = (DefaultMutableTreeNode) o; - - if (node.getUserObject() instanceof IModelElement) - aux.add(((IModelElement) node.getUserObject()).getId()); - - if (node.getUserObject() instanceof IDiagramUIModel) - aux.add(((IDiagramUIModel) node.getUserObject()).getId()); - } - } - /* - * final IProject project = - * ApplicationManager.instance().getProjectManager().getProject(); final - * String[] datatypes = { IModelElementFactory.MODEL_TYPE_DATA_TYPE }; - * - * for (IModelElement datatype : project.toModelElementArray(datatypes)) - * aux.add(datatype.getId()); - */ - } - - } - - public HashSet getSavedElements() { - - if (tabbedPane.getSelectedIndex() == 0) - return elementsPackageTree; - else - return elementsDiagramTree; - } - - public String getTableElementMapping() { - HashMap>> results = new HashMap>>(); - String elementId = ""; - - for (int row = 0; row < table.getRowCount(); row++) { - - HashMap content; - HashMap> label; - - String element = table.getValueAt(row, 0).toString(); - String language = table.getValueAt(row, 1).toString(); - String text = table.getValueAt(row, 2).toString(); - - for (IModelElement iModelElement : elementsMapping) { - - if (iModelElement.getName() == null) - continue; - - if (iModelElement.getName().equals(element)) { - elementId = iModelElement.getId(); - } - } - - if (!results.containsKey(elementId)) { - label = new HashMap>(); - content = new HashMap(); - label.put("label", content); - results.put(elementId, label); - - } else { - label = results.get(elementId); - content = label.get("label"); - } - - content.put(language, text); - - } - - Gson gson = new Gson(); - String json = gson.toJson(results); - - JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); - - return convertedObject.toString(); - - } - - public String getTablePackageMapping() { - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - HashMap> results = new HashMap<>(); - String elementId = ""; - - for (int row = 0; row < table2.getRowCount(); row++) { - HashMap content; - - String packages = table2.getValueAt(row, 0).toString(); - String prefix = table2.getValueAt(row, 1).toString(); - String uri = table2.getValueAt(row, 2).toString(); - - for (IModelElement element : packagesMapping) { - - if (element.getName() == null) - continue; - - if (element.getName().equals(packages)) - elementId = element.getId(); - - } - - if (project.getName().equals(packages)) - elementId = project.getId(); - - if (!results.containsKey(elementId)) { - content = new HashMap<>(); - content.put("prefix", prefix); - content.put("uri", uri); - } else { - content = results.get(elementId); - } - - results.put(elementId, content); - content.put("prefix", prefix); - content.put("uri", uri); - } - - Gson gson = new Gson(); - String json = gson.toJson(results); - - JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); - - return convertedObject.toString(); - - } - - - -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/GUFOExportView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/GUFOExportView.java new file mode 100644 index 00000000..da0d4b2f --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/GUFOExportView.java @@ -0,0 +1,1004 @@ +package it.unibz.inf.ontouml.vp.views; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.diagram.IDiagramUIModel; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IAssociationClass; +import com.vp.plugin.model.IAssociationEnd; +import com.vp.plugin.model.IAttribute; +import com.vp.plugin.model.IGeneralization; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.IProject; +import com.vp.plugin.model.factory.IModelElementFactory; +import com.vp.plugin.view.IDialog; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; +import it.unibz.inf.ontouml.vp.model.ServerRequest; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.GridLayout; +import java.awt.Insets; +import java.awt.event.KeyEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Vector; +import javax.swing.DefaultCellEditor; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTable; +import javax.swing.JTextField; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableColumnModel; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreePath; + +public class GUFOExportView extends JPanel { + private static final long serialVersionUID = 1L; + + private JTextField IRItxt; + private JComboBox formatBox; + private JComboBox uriFormatBox; + private JComboBox inverseBox; + private JComboBox objectBox; + private JComboBox analysisBox; + private JComboBox packagesBox; + + private JComboBox namesBox; + private JComboBox languagesBox; + private JComboBox packagesIdBox; + private JTabbedPane tabbedPane; + private JCheckBoxTree packageTree; + private JCheckBoxTree diagramTree; + + private JTable table; + private JTable table2; + + JPanel treePanelPackage; + JPanel treePanelDiagram; + + private JButton btnExport; + private JButton btnCancel; + + private IDialog _dialog; + + private boolean isToExport; + private boolean isOpen; + + private HashSet elementsPackageTree = new HashSet<>(); + private HashSet elementsDiagramTree = new HashSet<>(); + + private IModelElement[] elementsMapping; + private IModelElement[] packagesMapping; + + public GUFOExportView(ProjectConfigurations configurations, ServerRequest request) { + setSize(new Dimension(680, 550)); + setLayout(new GridLayout(1, 1)); + + JTabbedPane mainTabbedPane = new JTabbedPane(); + + JPanel mainPanel = new JPanel(); + JPanel elementMappingPanel = new JPanel(); + JPanel packageMappingPanel = new JPanel(); + + mainTabbedPane.add(mainPanel, "Basic Settings"); + mainTabbedPane.add(elementMappingPanel, "Element Mapping"); + mainTabbedPane.add(packageMappingPanel, "Package Mapping"); + + JPanel optionsPanelLeft = new JPanel(); + JPanel optionsPanelRight = new JPanel(); + JPanel treePanel = new JPanel(); + JPanel buttonsPanel = new JPanel(); + JPanel buttonsPanelTable1 = new JPanel(); + JPanel buttonsPanelTable2 = new JPanel(); + + mainPanel.setLayout(new GridBagLayout()); + elementMappingPanel.setLayout(new GridBagLayout()); + packageMappingPanel.setLayout(new GridBagLayout()); + optionsPanelLeft.setLayout(new GridBagLayout()); + optionsPanelRight.setLayout(new GridBagLayout()); + treePanel.setLayout(new GridBagLayout()); + buttonsPanel.setLayout(new GridBagLayout()); + buttonsPanelTable1.setLayout(new GridBagLayout()); + buttonsPanelTable2.setLayout(new GridBagLayout()); + + mainPanel.setPreferredSize(new Dimension(650, 540)); + elementMappingPanel.setPreferredSize(new Dimension(650, 480)); + packageMappingPanel.setPreferredSize(new Dimension(650, 540)); + optionsPanelLeft.setPreferredSize(new Dimension(280, 120)); + optionsPanelRight.setPreferredSize(new Dimension(320, 120)); + treePanel.setPreferredSize(new Dimension(600, 300)); + buttonsPanel.setPreferredSize(new Dimension(600, 40)); + buttonsPanelTable1.setPreferredSize(new Dimension(280, 40)); + + GridBagConstraints gbc_main = new GridBagConstraints(); + gbc_main.insets = new Insets(1, 1, 1, 1); + gbc_main.anchor = GridBagConstraints.FIRST_LINE_START; + gbc_main.weightx = 0.5; + gbc_main.weighty = 1; + gbc_main.gridx = 0; + gbc_main.gridy = 0; + mainPanel.add(optionsPanelLeft, gbc_main); + gbc_main.anchor = GridBagConstraints.FIRST_LINE_END; + gbc_main.weightx = 0.5; + gbc_main.weighty = 0.5; + gbc_main.gridx = 1; + gbc_main.gridy = 0; + mainPanel.add(optionsPanelRight, gbc_main); + gbc_main.anchor = GridBagConstraints.PAGE_START; + gbc_main.weightx = 1.0; + gbc_main.weighty = 0.8; + gbc_main.gridwidth = 4; + gbc_main.gridx = 0; + gbc_main.gridy = 1; + gbc_main.fill = GridBagConstraints.HORIZONTAL; + mainPanel.add(treePanel, gbc_main); + gbc_main.anchor = GridBagConstraints.FIRST_LINE_END; + gbc_main.weightx = 0.5; + gbc_main.weighty = 0.5; + gbc_main.gridx = 0; + gbc_main.gridy = 2; + mainPanel.add(buttonsPanel, gbc_main); + + JLabel iriLabel = new JLabel("Base IRI:"); + JLabel formatLabel = new JLabel("Output format:"); + JLabel URIformatLabel = new JLabel("Create URIs using:"); + + IRItxt = new JTextField(); + + String[] formatStrings = {"Turtle", "N-Triples", "N-Quads"}; + formatBox = new JComboBox<>(formatStrings); + ((JLabel) formatBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); + + String[] uriFormatBoxString = {"name", "id"}; + uriFormatBox = new JComboBox<>(uriFormatBoxString); + ((JLabel) uriFormatBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); + IRItxt.setText("http://example.com"); + + iriLabel.setPreferredSize(new Dimension(120, 28)); + formatLabel.setPreferredSize(new Dimension(120, 28)); + URIformatLabel.setPreferredSize(new Dimension(120, 28)); + IRItxt.setPreferredSize(new Dimension(140, 28)); + formatBox.setPreferredSize(new Dimension(140, 28)); + uriFormatBox.setPreferredSize(new Dimension(140, 28)); + + GridBagConstraints gbc_insidePanelLeft = new GridBagConstraints(); + gbc_insidePanelLeft.fill = GridBagConstraints.BOTH; + gbc_insidePanelLeft.insets = new Insets(2, 2, 2, 0); + gbc_insidePanelLeft.weightx = 0.5; + gbc_insidePanelLeft.gridx = 0; + gbc_insidePanelLeft.gridy = 0; + gbc_insidePanelLeft.anchor = GridBagConstraints.WEST; + optionsPanelLeft.add(iriLabel, gbc_insidePanelLeft); + gbc_insidePanelLeft.weightx = 0.5; + gbc_insidePanelLeft.gridx = 1; + gbc_insidePanelLeft.gridy = 0; + optionsPanelLeft.add(IRItxt, gbc_insidePanelLeft); + gbc_insidePanelLeft.weightx = 0.5; + gbc_insidePanelLeft.gridx = 0; + gbc_insidePanelLeft.gridy = 1; + optionsPanelLeft.add(formatLabel, gbc_insidePanelLeft); + gbc_insidePanelLeft.weightx = 0.5; + gbc_insidePanelLeft.gridx = 1; + gbc_insidePanelLeft.gridy = 1; + optionsPanelLeft.add(formatBox, gbc_insidePanelLeft); + gbc_insidePanelLeft.weightx = 0.5; + gbc_insidePanelLeft.gridx = 0; + gbc_insidePanelLeft.gridy = 2; + optionsPanelLeft.add(URIformatLabel, gbc_insidePanelLeft); + gbc_insidePanelLeft.weightx = 0.5; + gbc_insidePanelLeft.gridx = 1; + gbc_insidePanelLeft.gridy = 2; + optionsPanelLeft.add(uriFormatBox, gbc_insidePanelLeft); + + JLabel inverseLabel = new JLabel("Create inverse properties:"); + JLabel objectLabel = new JLabel("Minimize property creation:"); + JLabel analysisLabel = new JLabel("Run pre analysis:"); + JLabel prefixPackageLabel = new JLabel("Add prefix per package:"); + + String[] inverseBoxString = {"false", "true"}; + inverseBox = new JComboBox<>(inverseBoxString); + ((JLabel) inverseBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); + + String[] objectBoxString = {"false", "true"}; + objectBox = new JComboBox<>(objectBoxString); + ((JLabel) objectBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); + + String[] analysisBoxString = {"true", "false"}; + analysisBox = new JComboBox<>(analysisBoxString); + ((JLabel) analysisBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); + + String[] packagesBoxString = {"false", "true"}; + packagesBox = new JComboBox<>(packagesBoxString); + ((JLabel) packagesBox.getRenderer()).setHorizontalAlignment(JLabel.CENTER); + + inverseLabel.setPreferredSize(new Dimension(180, 28)); + objectLabel.setPreferredSize(new Dimension(180, 28)); + analysisLabel.setPreferredSize(new Dimension(180, 28)); + prefixPackageLabel.setPreferredSize(new Dimension(180, 28)); + inverseBox.setPreferredSize(new Dimension(90, 28)); + objectBox.setPreferredSize(new Dimension(90, 28)); + analysisBox.setPreferredSize(new Dimension(90, 28)); + packagesBox.setPreferredSize(new Dimension(90, 28)); + + GridBagConstraints gbc_insidePanelRight = new GridBagConstraints(); + gbc_insidePanelRight.fill = GridBagConstraints.BOTH; + gbc_insidePanelRight.insets = new Insets(2, 0, 2, 0); + gbc_insidePanelRight.weightx = 0.5; + gbc_insidePanelRight.gridx = 0; + gbc_insidePanelRight.gridy = 0; + gbc_insidePanelRight.anchor = GridBagConstraints.WEST; + optionsPanelRight.add(objectLabel, gbc_insidePanelRight); + gbc_insidePanelRight.weightx = 0.5; + gbc_insidePanelRight.gridx = 1; + gbc_insidePanelRight.gridy = 0; + gbc_insidePanelRight.anchor = GridBagConstraints.EAST; + optionsPanelRight.add(objectBox, gbc_insidePanelRight); + gbc_insidePanelRight.weightx = 0.5; + gbc_insidePanelRight.gridx = 0; + gbc_insidePanelRight.gridy = 1; + gbc_insidePanelRight.anchor = GridBagConstraints.WEST; + optionsPanelRight.add(inverseLabel, gbc_insidePanelRight); + gbc_insidePanelRight.weightx = 0.5; + gbc_insidePanelRight.gridx = 1; + gbc_insidePanelRight.gridy = 1; + gbc_insidePanelRight.anchor = GridBagConstraints.EAST; + optionsPanelRight.add(inverseBox, gbc_insidePanelRight); + gbc_insidePanelRight.weightx = 0.5; + gbc_insidePanelRight.gridx = 0; + gbc_insidePanelRight.gridy = 2; + gbc_insidePanelRight.anchor = GridBagConstraints.WEST; + optionsPanelRight.add(prefixPackageLabel, gbc_insidePanelRight); + gbc_insidePanelRight.weightx = 0.5; + gbc_insidePanelRight.gridx = 1; + gbc_insidePanelRight.gridy = 2; + gbc_insidePanelRight.anchor = GridBagConstraints.EAST; + optionsPanelRight.add(packagesBox, gbc_insidePanelRight); + gbc_insidePanelRight.weightx = 0.5; + gbc_insidePanelRight.gridx = 0; + gbc_insidePanelRight.gridy = 3; + gbc_insidePanelRight.anchor = GridBagConstraints.WEST; + optionsPanelRight.add(analysisLabel, gbc_insidePanelRight); + gbc_insidePanelRight.weightx = 0.5; + gbc_insidePanelRight.gridx = 1; + gbc_insidePanelRight.gridy = 3; + gbc_insidePanelRight.anchor = GridBagConstraints.EAST; + optionsPanelRight.add(analysisBox, gbc_insidePanelRight); + + JPanel packagePanel = new JPanel(); + JPanel diagramPanel = new JPanel(); + + tabbedPane = new JTabbedPane(); + packageTree = new JCheckBoxTree("package"); + diagramTree = new JCheckBoxTree("diagram"); + + JScrollPane scrollableTextAreaPackage = new JScrollPane(packageTree); + JScrollPane scrollableTextAreaDiagram = new JScrollPane(diagramTree); + + scrollableTextAreaPackage.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + scrollableTextAreaPackage.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + + scrollableTextAreaDiagram.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + scrollableTextAreaDiagram.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + + packagePanel.setLayout(new GridLayout(1, 1)); + packagePanel.setPreferredSize(new Dimension(550, 270)); + + diagramPanel.setLayout(new GridLayout(1, 1)); + diagramPanel.setPreferredSize(new Dimension(550, 270)); + + packagePanel.add(scrollableTextAreaPackage); + + diagramPanel.add(scrollableTextAreaDiagram); + + tabbedPane.addTab("Package Explorer", packagePanel); + tabbedPane.setMnemonicAt(0, KeyEvent.VK_1); + + tabbedPane.addTab("Diagram Explorer", diagramPanel); + tabbedPane.setMnemonicAt(1, KeyEvent.VK_2); + + tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); + + treePanel.add(tabbedPane); + treePanel.setLayout(new GridLayout(1, 1)); + + btnExport = new JButton("Export"); + btnCancel = new JButton("Cancel"); + + btnExport.setPreferredSize(new Dimension(80, 35)); + btnCancel.setPreferredSize(new Dimension(80, 35)); + + btnExport.addActionListener( + actionEvent -> { + if (tabbedPane.getSelectedIndex() == 0) saveSelectedElements("Package Tree"); + else saveSelectedElements("Diagram Tree"); + + updateConfigurationsValues(configurations); + Configurations.getInstance().save(); + isToExport = true; + isOpen = false; + _dialog.close(); + Thread thread = new Thread(request); + thread.start(); + }); + + btnCancel.addActionListener( + actionEvent -> { + isToExport = false; + isOpen = false; + request.doStop(); + _dialog.close(); + OntoUMLPlugin.setExportToGUFOWindowOpen(false); + }); + + GridBagConstraints gbc_buttonsPanel = new GridBagConstraints(); + gbc_buttonsPanel.fill = GridBagConstraints.HORIZONTAL; + gbc_buttonsPanel.insets = new Insets(2, 2, 2, 15); + gbc_buttonsPanel.weightx = 0.5; + gbc_buttonsPanel.gridx = 0; + gbc_buttonsPanel.gridy = 0; + gbc_buttonsPanel.anchor = GridBagConstraints.PAGE_END; + buttonsPanel.add(btnExport, gbc_buttonsPanel); + gbc_buttonsPanel.weightx = 0.5; + gbc_buttonsPanel.gridx = 1; + gbc_buttonsPanel.gridy = 0; + buttonsPanel.add(btnCancel, gbc_buttonsPanel); + + // TABLE 1 + + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + + final String[] anyLevelElements = { + IModelElementFactory.MODEL_TYPE_CLASS, + IModelElementFactory.MODEL_TYPE_ATTRIBUTE, + IModelElementFactory.MODEL_TYPE_ASSOCIATION, + IModelElementFactory.MODEL_TYPE_ASSOCIATION_END, + }; + + elementsMapping = project.toAllLevelModelElementArray(anyLevelElements); + String[] nameElements = new String[elementsMapping.length]; + + for (int i = 0; i < elementsMapping.length; i++) + nameElements[i] = getDisplayName(elementsMapping[i]); + + namesBox = new JComboBox<>(nameElements); + ((JLabel) namesBox.getRenderer()).setHorizontalAlignment(JLabel.LEFT); + + languagesBox = new JComboBox<>(getLanguagesCode()); + ((JLabel) languagesBox.getRenderer()).setHorizontalAlignment(JLabel.LEFT); + + String[][] data; + String[] columnNamesArr; + ArrayList columnNamesList; + DefaultTableModel defaultTableModel; + TableColumnModel tableColumnModel; + JScrollPane scrollPane; + JButton addButton; + JButton deleteButton; + + columnNamesList = new ArrayList<>(); + columnNamesList.add("Element"); + columnNamesList.add("Language"); + columnNamesList.add("Text"); + + data = new String[1][columnNamesList.size()]; + + columnNamesArr = new String[columnNamesList.size()]; + for (int i = 0; i < columnNamesList.size(); i++) { + columnNamesArr[i] = columnNamesList.get(i); + data[0][i] = ""; + } + + // defaultTableModel = new DefaultTableModel(data, columnNamesArr); + defaultTableModel = new DefaultTableModel(null, columnNamesArr); + + table = new JTable(defaultTableModel); + tableColumnModel = table.getColumnModel(); + table.setGridColor(Color.LIGHT_GRAY); + + for (int i = 0; i < columnNamesList.size(); i++) { + tableColumnModel.getColumn(i).setPreferredWidth(columnNamesList.get(i).length()); + } + table.setPreferredScrollableViewportSize(table.getPreferredSize()); + scrollPane = new JScrollPane(table); + + namesBox.setEditable(false); + languagesBox.setEditable(false); + table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(namesBox)); + table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(languagesBox)); + table.getColumnModel().getColumn(0).setPreferredWidth(150); + table.getColumnModel().getColumn(1).setPreferredWidth(20); + table.getColumnModel().getColumn(2).setPreferredWidth(80); + table.setRowHeight(28); + + addButton = new JButton("Add"); + deleteButton = new JButton("Delete"); + + addButton.addActionListener( + actionEvent -> { + Vector rowData = new Vector<>(); + rowData.add(namesBox.getItemAt(0)); + rowData.add(languagesBox.getItemAt(0)); + rowData.add(""); + defaultTableModel.addRow(rowData); + + table.validate(); + }); + + deleteButton.addActionListener( + actionEvent -> { + // Vector rowData = null; + int rowCount = defaultTableModel.getRowCount(); + if (rowCount > 0) { + defaultTableModel.removeRow(rowCount - 1); + table.validate(); + } + }); + + GridBagConstraints gbc_buttonsPanelTable1 = new GridBagConstraints(); + gbc_buttonsPanelTable1.fill = GridBagConstraints.BOTH; + gbc_buttonsPanelTable1.insets = new Insets(1, 1, 1, 1); + gbc_buttonsPanelTable1.weightx = 0.5; + gbc_buttonsPanelTable1.gridx = 0; + gbc_buttonsPanelTable1.gridy = 0; + gbc_buttonsPanelTable1.anchor = GridBagConstraints.PAGE_END; + buttonsPanelTable1.add(addButton, gbc_buttonsPanelTable1); + gbc_buttonsPanelTable1.weightx = 0.5; + gbc_buttonsPanelTable1.gridx = 1; + gbc_buttonsPanelTable1.gridy = 0; + buttonsPanelTable1.add(deleteButton, gbc_buttonsPanelTable1); + + scrollPane.setPreferredSize(new Dimension(550, 400)); + buttonsPanelTable1.setPreferredSize(new Dimension(400, 30)); + + GridBagConstraints gbc_mappingTable1 = new GridBagConstraints(); + // gbc_insidePanelLeft.fill = GridBagConstraints.HORIZONTAL; + gbc_mappingTable1.insets = new Insets(1, 1, 1, 1); + gbc_mappingTable1.gridx = 0; + gbc_mappingTable1.gridy = 0; + elementMappingPanel.add(scrollPane, gbc_mappingTable1); + gbc_mappingTable1.gridx = 0; + gbc_mappingTable1.gridy = 1; + gbc_mappingTable1.anchor = GridBagConstraints.EAST; + elementMappingPanel.add(buttonsPanelTable1, gbc_mappingTable1); + + // TABLE 2 + + String[] packages = { + IModelElementFactory.MODEL_TYPE_PACKAGE, IModelElementFactory.MODEL_TYPE_MODEL + }; + + packagesMapping = project.toAllLevelModelElementArray(packages); + String[] nameElementsPack = new String[packagesMapping.length + 1]; + nameElementsPack[0] = project.getName(); + + for (int i = 0; i < packagesMapping.length; i++) + nameElementsPack[i + 1] = packagesMapping[i].getName(); + + packagesIdBox = new JComboBox<>(nameElementsPack); + ((JLabel) packagesIdBox.getRenderer()).setHorizontalAlignment(JLabel.LEFT); + + String[][] data_table2; + String[] columnNamesArr_table2; + ArrayList columnNamesList_table2; + DefaultTableModel defaultTableModel_table2; + TableColumnModel tableColumnModel_table2; + JScrollPane scrollPane_table2; + JButton addButton_table2; + JButton deleteButton_table2; + + columnNamesList_table2 = new ArrayList<>(); + columnNamesList_table2.add("Package"); + columnNamesList_table2.add("Prefix"); + columnNamesList_table2.add("URI"); + + data_table2 = new String[1][columnNamesList_table2.size()]; + + columnNamesArr_table2 = new String[columnNamesList_table2.size()]; + for (int i = 0; i < columnNamesList_table2.size(); i++) { + columnNamesArr_table2[i] = columnNamesList_table2.get(i); + data_table2[0][i] = ""; + } + + // defaultTableModel_table2 = new DefaultTableModel(data_table2, columnNamesArr_table2); + + defaultTableModel_table2 = new DefaultTableModel(null, columnNamesArr_table2); + + table2 = new JTable(defaultTableModel_table2); + table2.setGridColor(Color.LIGHT_GRAY); + tableColumnModel_table2 = table2.getColumnModel(); + + for (int i = 0; i < columnNamesList_table2.size(); i++) { + tableColumnModel_table2 + .getColumn(i) + .setPreferredWidth(columnNamesList_table2.get(i).length()); + } + table2.setPreferredScrollableViewportSize(table2.getPreferredSize()); + scrollPane_table2 = new JScrollPane(table2); + + packagesIdBox.setEditable(false); + table2.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(packagesIdBox)); + table2.getColumnModel().getColumn(0).setPreferredWidth(150); + table2.getColumnModel().getColumn(1).setPreferredWidth(20); + table2.getColumnModel().getColumn(2).setPreferredWidth(80); + table2.setRowHeight(28); + + addButton_table2 = new JButton("Add"); + deleteButton_table2 = new JButton("Delete"); + + addButton_table2.addActionListener( + actionEvent -> { + Vector rowData = new Vector<>(); + rowData.add(packagesIdBox.getItemAt(0)); + rowData.add(""); + rowData.add(""); + defaultTableModel_table2.addRow(rowData); + table2.validate(); + }); + + deleteButton_table2.addActionListener( + actionEvent -> { + // Vector rowData = null; + int rowCount = defaultTableModel_table2.getRowCount(); + if (rowCount > 0) { + defaultTableModel_table2.removeRow(rowCount - 1); + table2.validate(); + } + }); + + GridBagConstraints gbc_buttonsPanelTable2 = new GridBagConstraints(); + gbc_buttonsPanelTable2.fill = GridBagConstraints.BOTH; + gbc_buttonsPanelTable2.insets = new Insets(1, 1, 1, 1); + gbc_buttonsPanelTable2.weightx = 0.5; + gbc_buttonsPanelTable2.gridx = 0; + gbc_buttonsPanelTable2.gridy = 0; + gbc_buttonsPanelTable2.anchor = GridBagConstraints.PAGE_END; + buttonsPanelTable2.add(addButton_table2, gbc_buttonsPanelTable2); + gbc_buttonsPanelTable2.weightx = 0.5; + gbc_buttonsPanelTable2.gridx = 1; + gbc_buttonsPanelTable2.gridy = 0; + buttonsPanelTable2.add(deleteButton_table2, gbc_buttonsPanelTable2); + + scrollPane_table2.setPreferredSize(new Dimension(550, 400)); + buttonsPanelTable2.setPreferredSize(new Dimension(400, 30)); + + GridBagConstraints gbc_mappingTable2 = new GridBagConstraints(); + // gbc_insidePanelLeft.fill = GridBagConstraints.HORIZONTAL; + gbc_mappingTable2.insets = new Insets(1, 1, 1, 1); + gbc_mappingTable2.gridx = 0; + gbc_mappingTable2.gridy = 0; + packageMappingPanel.add(scrollPane_table2, gbc_mappingTable2); + gbc_mappingTable2.gridx = 0; + gbc_mappingTable2.gridy = 1; + gbc_mappingTable2.anchor = GridBagConstraints.EAST; + packageMappingPanel.add(buttonsPanelTable2, gbc_mappingTable2); + + add(mainTabbedPane); + + updateComponentsValues(configurations); + } + + public JTextField getIRItxt() { + return IRItxt; + } + + public void setIRItxt(JTextField iRItxt) { + IRItxt = iRItxt; + } + + public JComboBox getFormatBox() { + return formatBox; + } + + public void setFormatBox(JComboBox formatBox) { + this.formatBox = formatBox; + } + + public JComboBox getUriFormatBox() { + return uriFormatBox; + } + + public void setUriFormatBox(JComboBox uriFormatBox) { + this.uriFormatBox = uriFormatBox; + } + + public JComboBox getInverseBox() { + return inverseBox; + } + + public void setInverseBox(JComboBox inverseBox) { + this.inverseBox = inverseBox; + } + + public JComboBox getObjectBox() { + return objectBox; + } + + public void setObjectBox(JComboBox objectBox) { + this.objectBox = objectBox; + } + + public JComboBox getAnalysisBox() { + return analysisBox; + } + + public void setAnalysisBox(JComboBox analysisBox) { + this.analysisBox = analysisBox; + } + + public JComboBox getNamesBox() { + return namesBox; + } + + public void setNamesBox(JComboBox namesBox) { + this.namesBox = namesBox; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + + public JComboBox getLanguagesBox() { + return languagesBox; + } + + public JComboBox getPackagesIdBox() { + return packagesIdBox; + } + + public JTabbedPane getTabbedPane() { + return tabbedPane; + } + + public JCheckBoxTree getPackageTree() { + return packageTree; + } + + public JCheckBoxTree getDiagramTree() { + return diagramTree; + } + + public JTable getTable() { + return table; + } + + public JTable getTable2() { + return table2; + } + + public JPanel getTreePanelPackage() { + return treePanelPackage; + } + + public JPanel getTreePanelDiagram() { + return treePanelDiagram; + } + + public JButton getBtnExport() { + return btnExport; + } + + public JButton getBtnCancel() { + return btnCancel; + } + + public IDialog get_dialog() { + return _dialog; + } + + public HashSet getElementsPackageTree() { + return elementsPackageTree; + } + + public HashSet getElementsDiagramTree() { + return elementsDiagramTree; + } + + public IModelElement[] getElementsMapping() { + return elementsMapping; + } + + public IModelElement[] getPackagesMapping() { + return packagesMapping; + } + + protected JComponent makeTextPanel(String text) { + JPanel panel = new JPanel(false); + JLabel filler = new JLabel(text); + filler.setHorizontalAlignment(JLabel.CENTER); + panel.setLayout(new GridLayout(1, 1)); + panel.add(filler); + return panel; + } + + public boolean getIsToExport() { + return isToExport; + } + + public boolean getIsOpen() { + return isOpen; + } + + private static String[] getLanguagesCode() { + + return new String[] { + "default", "aa", "ab", "ae", "af", "ak", "am", "an", "ar", "as", "av", "ay", "az", "ba", "be", + "bg", "bh", "bm", "bi", "bn", "bo", "br", "bs", "ca", "ce", "ch", "co", "cr", "cs", "cu", + "cv", "cy", "da", "de", "dv", "dz", "ee", "el", "en", "eo", "es", "et", "eu", "fa", "ff", + "fi", "fj", "fo", "fr", "fy", "ga", "gd", "gl", "gn", "gu", "gv", "ha", "he", "hi", "ho", + "hr", "ht", "hu", "hy", "hz", "ia", "id", "ie", "ig", "ii", "ik", "io", "is", "it", "iu", + "ja", "jv", "ka", "kg", "ki", "kj", "kk", "kl", "km", "kn", "ko", "kr", "ks", "ku", "kv", + "kw", "ky", "la", "lb", "lg", "li", "ln", "lo", "lt", "lu", "lv", "mg", "mh", "mi", "mk", + "ml", "mn", "mr", "ms", "mt", "my", "na", "nb", "nd", "ne", "ng", "nl", "nn", "no", "nr", + "nv", "ny", "oc", "oj", "om", "or", "os", "pa", "pi", "pl", "ps", "pt", "qu", "rm", "rn", + "ro", "ru", "rw", "sa", "sc", "sd", "se", "sg", "si", "sk", "sl", "sm", "sn", "so", "sq", + "sr", "ss", "st", "su", "sv", "sw", "ta", "te", "tg", "th", "ti", "tk", "tl", "tn", "to", + "tr", "ts", "tt", "tw", "ty", "ug", "uk", "ur", "uz", "ve", "vi", "vo", "wa", "wo", "xh", + "yi", "yo", "za", "zh", "zu" + }; + } + + /** Sets a direct reference to the container dialog after initialization. */ + public void setContainerDialog(IDialog dialog) { + this._dialog = dialog; + } + + /** Updates project configurations with components' information. */ + private void updateConfigurationsValues(ProjectConfigurations configurations) { + configurations.setExportGUFOIRI(IRItxt.getText()); + configurations.setExportGUFOFormat(formatBox.getSelectedItem().toString()); + configurations.setExportGUFOURIFormat(uriFormatBox.getSelectedItem().toString()); + configurations.setExportGUFOInverseBox(inverseBox.getSelectedItem().toString()); + configurations.setExportGUFOObjectBox(objectBox.getSelectedItem().toString()); + configurations.setExportGUFOAnalysisBox(analysisBox.getSelectedItem().toString()); + configurations.setExportGUFOPackagesBox(packagesBox.getSelectedItem().toString()); + configurations.setExportGUFOElementMapping(getTableElementMapping()); + configurations.setExportGUFOPackageMapping(getTablePackageMapping()); + + if (tabbedPane.getSelectedIndex() == 0) + configurations.setExportGUFOElementsPackageTree(elementsPackageTree); + else configurations.setExportGUFOElementsDiagramTree(elementsDiagramTree); + } + + /** + * Updates components with project configurations' information. + * + * @param configurations + */ + private void updateComponentsValues(ProjectConfigurations configurations) { + + if (configurations.getExportGUFOIRI() != null && !configurations.getExportGUFOIRI().equals("")) + IRItxt.setText(configurations.getExportGUFOIRI()); + + if (configurations.getExportGUFOFormat() != null + && !configurations.getExportGUFOFormat().equals("")) + formatBox.setSelectedItem(configurations.getExportGUFOFormat()); + + if (configurations.getExportGUFOURIFormat() != null + && !configurations.getExportGUFOURIFormat().equals("")) + uriFormatBox.setSelectedItem(configurations.getExportGUFOURIFormat()); + + if (configurations.getExportGUFOElementsPackageTree() != null) + packageTree.setNodesCheck(configurations.getExportGUFOElementsPackageTree()); + + if (configurations.getExportGUFOElementsDiagramTree() != null) + diagramTree.setNodesCheck(configurations.getExportGUFOElementsDiagramTree()); + + if (configurations.getExportGUFOInverseBox() != null) + inverseBox.setSelectedItem(configurations.getExportGUFOInverseBox()); + + if (configurations.getExportGUFOObjectBox() != null) + objectBox.setSelectedItem(configurations.getExportGUFOObjectBox()); + + if (configurations.getExportGUFOAnalysisBox() != null) + analysisBox.setSelectedItem(configurations.getExportGUFOAnalysisBox()); + + if (configurations.getExportGUFOPackagesBox() != null) + packagesBox.setSelectedItem(configurations.getExportGUFOPackagesBox()); + } + + private void saveSelectedElements(String tree) { + + TreePath[] paths; + HashSet aux; + + if (tree.equals("Package Tree")) { + paths = packageTree.getCheckedPaths(); + aux = this.elementsPackageTree; + } else { + paths = diagramTree.getCheckedPaths(); + aux = this.elementsDiagramTree; + } + + for (TreePath path : paths) { + Object[] object = path.getPath(); + for (Object o : object) { + + if (o instanceof DefaultMutableTreeNode) { + + DefaultMutableTreeNode node = (DefaultMutableTreeNode) o; + + if (node.getUserObject() instanceof IModelElement) + aux.add(((IModelElement) node.getUserObject()).getId()); + + if (node.getUserObject() instanceof IDiagramUIModel) + aux.add(((IDiagramUIModel) node.getUserObject()).getId()); + } + } + } + } + + public HashSet getSavedElements() { + + if (tabbedPane.getSelectedIndex() == 0) return elementsPackageTree; + else return elementsDiagramTree; + } + + public String getTableElementMapping() { + HashMap>> results = + new HashMap>>(); + String elementId = ""; + + for (int row = 0; row < table.getRowCount(); row++) { + + HashMap content; + HashMap> label; + + String element = table.getValueAt(row, 0).toString(); + String language = table.getValueAt(row, 1).toString(); + String text = table.getValueAt(row, 2).toString(); + + for (IModelElement iModelElement : elementsMapping) { + + if (iModelElement.getName() == null) continue; + + if (iModelElement.getName().equals(element)) { + elementId = iModelElement.getId(); + } + } + + if (!results.containsKey(elementId)) { + label = new HashMap>(); + content = new HashMap(); + label.put("label", content); + results.put(elementId, label); + + } else { + label = results.get(elementId); + content = label.get("label"); + } + + content.put(language, text); + } + + Gson gson = new Gson(); + String json = gson.toJson(results); + + JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); + + return convertedObject.toString(); + } + + public String getTablePackageMapping() { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + HashMap> results = new HashMap<>(); + String elementId = ""; + + for (int row = 0; row < table2.getRowCount(); row++) { + HashMap content; + + String packages = table2.getValueAt(row, 0).toString(); + String prefix = table2.getValueAt(row, 1).toString(); + String uri = table2.getValueAt(row, 2).toString(); + + for (IModelElement element : packagesMapping) { + + if (element.getName() == null) continue; + + if (element.getName().equals(packages)) elementId = element.getId(); + } + + if (project.getName().equals(packages)) elementId = project.getId(); + + if (!results.containsKey(elementId)) { + content = new HashMap<>(); + content.put("prefix", prefix); + content.put("uri", uri); + } else { + content = results.get(elementId); + } + + results.put(elementId, content); + content.put("prefix", prefix); + content.put("uri", uri); + } + + Gson gson = new Gson(); + String json = gson.toJson(results); + + JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); + + return convertedObject.toString(); + } + + public static String getDisplayName(Object obj) { + if (obj == null) return ""; + + if (obj instanceof String) return obj.toString(); + + if (obj instanceof IDiagramUIModel) { + IDiagramUIModel diagram = (IDiagramUIModel) obj; + + return diagram.getName() != null ? diagram.getName() : "Diagram"; + } + + if (obj instanceof IAttribute) { + IAttribute attribute = (IAttribute) obj; + + String attributeName = attribute.getName() != null ? attribute.getName() : ""; + + String attributeType = ""; + if (attribute.getType() != null) attributeType = attribute.getTypeAsString(); + + return attributeName + " : " + attributeType; + } + + if (obj instanceof IAssociation) { + IAssociation association = (IAssociation) obj; + String assocName = ""; + + if (association.getName() != null && !association.getName().equals("")) + assocName = association.getName() + " "; + + String nameFrom = association.getFrom() == null ? "" : association.getFrom().getName(); + String nameTo = association.getTo() == null ? "" : association.getTo().getName(); + + return assocName + "(" + nameFrom + " -> " + nameTo + ")"; + } + + if (obj instanceof IAssociationEnd) { + IAssociationEnd assocEnd = (IAssociationEnd) obj; + + String endName = assocEnd.getName() != null ? assocEnd.getName() : ""; + String typeName = assocEnd.getType() != null ? assocEnd.getTypeAsString() : ""; + + return endName + " : " + typeName; + } + + if (obj instanceof IGeneralization) { + IGeneralization generalization = (IGeneralization) obj; + + String childTypeName = generalization.getTo() != null ? generalization.getTo().getName() : ""; + String parentTypeName = + generalization.getFrom() != null ? generalization.getFrom().getName() : ""; + + return "(" + childTypeName + " -> " + parentTypeName + ")"; + } + + if (obj instanceof IAssociationClass) { + IAssociationClass assocClass = (IAssociationClass) obj; + + String nameFrom = assocClass.getFrom() != null ? assocClass.getFrom().getName() : ""; + String nameTo = assocClass.getTo() != null ? assocClass.getTo().getName() : ""; + + return "(" + nameFrom + " -> " + nameTo + ")"; + } + + if (obj instanceof IModelElement) { + IModelElement element = (IModelElement) obj; + return element.getName() != null ? element.getName() : "ModelElement " + element.getId(); + } + + return "Element"; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/HTMLEnabledMessage.java b/src/main/java/it/unibz/inf/ontouml/vp/views/HTMLEnabledMessage.java index b435f443..fc778588 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/HTMLEnabledMessage.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/HTMLEnabledMessage.java @@ -1,57 +1,62 @@ package it.unibz.inf.ontouml.vp.views; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; import java.awt.Color; import java.awt.Desktop; import java.awt.Font; -import java.net.URI; - import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; - public class HTMLEnabledMessage extends JEditorPane { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public HTMLEnabledMessage(String htmlBody) { - super("text/html", "" + htmlBody + ""); - addHyperlinkListener(new HyperlinkListener() { - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { - try { - final Desktop desktop = Desktop.getDesktop(); - desktop.browse(e.getURL().toURI()); - } catch (UnsupportedOperationException unsupportedException) { - ViewUtils.reportBugErrorDialog(true); - unsupportedException.printStackTrace(); - } catch (SecurityException securityException) { - ViewUtils.reportBugErrorDialog(true); - securityException.printStackTrace(); - } catch(Exception exception) { - ViewUtils.reportBugErrorDialog(false); - exception.printStackTrace(); - } - } + public HTMLEnabledMessage(String htmlBody) { + super("text/html", "" + htmlBody + ""); + addHyperlinkListener( + new HyperlinkListener() { + @Override + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { + try { + final Desktop desktop = Desktop.getDesktop(); + desktop.browse(e.getURL().toURI()); + } catch (UnsupportedOperationException unsupportedException) { + ViewManagerUtils.reportBugErrorDialog(true); + unsupportedException.printStackTrace(); + } catch (SecurityException securityException) { + ViewManagerUtils.reportBugErrorDialog(true); + securityException.printStackTrace(); + } catch (Exception exception) { + ViewManagerUtils.reportBugErrorDialog(false); + exception.printStackTrace(); + } } + } }); - setEditable(false); - setBorder(null); - } + setEditable(false); + setBorder(null); + } - static StringBuffer getStyle() { - // for copying style - JLabel label = new JLabel(); - Font font = label.getFont(); - Color color = label.getBackground(); + static StringBuffer getStyle() { + // for copying style + JLabel label = new JLabel(); + Font font = label.getFont(); + Color color = label.getBackground(); - // create some css from the label's font - StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); - style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); - style.append("font-size:" + font.getSize() + "pt;"); - style.append("background-color: rgb(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + ");"); - return style; - } + // create some css from the label's font + StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); + style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); + style.append("font-size:" + font.getSize() + "pt;"); + style.append( + "background-color: rgb(" + + color.getRed() + + "," + + color.getGreen() + + "," + + color.getBlue() + + ");"); + return style; + } } diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/IssueLogMenu.java b/src/main/java/it/unibz/inf/ontouml/vp/views/IssueLogMenu.java new file mode 100644 index 00000000..ced9b926 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/IssueLogMenu.java @@ -0,0 +1,63 @@ +package it.unibz.inf.ontouml.vp.views; + +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.*; + +@SuppressWarnings("serial") +public final class IssueLogMenu extends JPopupMenu { + private JMenuItem takeMeThere; + private JMenuItem openSpec; + private ActionListener menuListener; + + public IssueLogMenu() {} + + public IssueLogMenu(String idModelElement) { + + menuListener = + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + switch (e.getActionCommand()) { + case "Take me there!": + System.out.println("Firing 'Highlight'"); + ViewManagerUtils.highlightDiagramElement(idModelElement); + break; + case "Open Specification": + System.out.println("Firing 'Open Specification'"); + ViewManagerUtils.openSpecDiagramElement(idModelElement); + break; + default: + break; + } + } + }; + + takeMeThere = + new JMenuItem( + "Take me there!", + new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.NAVIGATION_LOGO))); + takeMeThere.addActionListener(menuListener); + openSpec = + new JMenuItem( + "Open Specification", + new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.MORE_HORIZ_LOGO))); + openSpec.addActionListener(menuListener); + add(takeMeThere); + add(openSpec); + } + + public void disableItem(String item) { + switch (item) { + case "Take me there!": + takeMeThere.setEnabled(false); + break; + case "Open Specification": + openSpec.setEnabled(false); + break; + default: + break; + } + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/JCheckBoxTree.java b/src/main/java/it/unibz/inf/ontouml/vp/views/JCheckBoxTree.java index a1185bb6..5c4e527a 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/JCheckBoxTree.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/JCheckBoxTree.java @@ -1,5 +1,23 @@ package it.unibz.inf.ontouml.vp.views; +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.diagram.IClassDiagramUIModel; +import com.vp.plugin.diagram.IDiagramElement; +import com.vp.plugin.diagram.IDiagramUIModel; +import com.vp.plugin.model.IAssociation; +import com.vp.plugin.model.IAssociationClass; +import com.vp.plugin.model.IAssociationEnd; +import com.vp.plugin.model.IAttribute; +import com.vp.plugin.model.IClass; +import com.vp.plugin.model.IDataType; +import com.vp.plugin.model.IGeneralization; +import com.vp.plugin.model.IGeneralizationSet; +import com.vp.plugin.model.IModel; +import com.vp.plugin.model.IModelElement; +import com.vp.plugin.model.IPackage; +import com.vp.plugin.model.IProject; +import com.vp.plugin.model.factory.IModelElementFactory; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; import java.awt.BorderLayout; import java.awt.Component; import java.util.Collections; @@ -10,7 +28,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; - import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JLabel; @@ -26,202 +43,192 @@ import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.diagram.IClassDiagramUIModel; -import com.vp.plugin.diagram.IDiagramElement; -import com.vp.plugin.diagram.IDiagramUIModel; -import com.vp.plugin.model.IAssociation; -import com.vp.plugin.model.IAssociationClass; -import com.vp.plugin.model.IAssociationEnd; -import com.vp.plugin.model.IAttribute; -import com.vp.plugin.model.IClass; -import com.vp.plugin.model.IDataType; -import com.vp.plugin.model.IGeneralization; -import com.vp.plugin.model.IGeneralizationSet; -import com.vp.plugin.model.IModel; -import com.vp.plugin.model.IModelElement; -import com.vp.plugin.model.IPackage; -import com.vp.plugin.model.IProject; -import com.vp.plugin.model.factory.IModelElementFactory; - -import it.unibz.inf.ontouml.vp.utils.ViewUtils; - public class JCheckBoxTree extends JTree { - private static final long serialVersionUID = -4194122328392241790L; - - JCheckBoxTree selfPointer = this; - - // Defining data structure that will enable to fast check-indicate the state of - // each node - // It totally replaces the "selection" mechanism of the JTree - private class CheckedNode { - boolean isSelected; - boolean hasChildren; - boolean allChildrenSelected; - - public CheckedNode(boolean isSelected_, boolean hasChildren_, boolean allChildrenSelected_) { - isSelected = isSelected_; - hasChildren = hasChildren_; - allChildrenSelected = allChildrenSelected_; - } - } - - HashMap nodesCheckingState; - HashSet checkedPaths = new HashSet(); + private static final long serialVersionUID = -4194122328392241790L; + + JCheckBoxTree selfPointer = this; + + // Defining data structure that will enable to fast check-indicate the state of + // each node + // It totally replaces the "selection" mechanism of the JTree + private class CheckedNode { + boolean isSelected; + boolean hasChildren; + boolean allChildrenSelected; + + public CheckedNode(boolean isSelected_, boolean hasChildren_, boolean allChildrenSelected_) { + isSelected = isSelected_; + hasChildren = hasChildren_; + allChildrenSelected = allChildrenSelected_; + } + } + + HashMap nodesCheckingState; + HashSet checkedPaths = new HashSet(); + + // Defining a new event type for the checking mechanism and preparing + // event-handling mechanism + protected EventListenerList listenerList = new EventListenerList(); + + public class CheckChangeEvent extends EventObject { + private static final long serialVersionUID = -8100230309044193368L; + + public CheckChangeEvent(Object source) { + super(source); + } + } + + public interface CheckChangeEventListener extends EventListener { + public void checkStateChanged(CheckChangeEvent event); + } + + public void addCheckChangeEventListener(CheckChangeEventListener listener) { + listenerList.add(CheckChangeEventListener.class, listener); + } + + public void removeCheckChangeEventListener(CheckChangeEventListener listener) { + listenerList.remove(CheckChangeEventListener.class, listener); + } + + void fireCheckChangeEvent(CheckChangeEvent evt) { + Object[] listeners = listenerList.getListenerList(); + for (int i = 0; i < listeners.length; i++) { + if (listeners[i] == CheckChangeEventListener.class) { + ((CheckChangeEventListener) listeners[i + 1]).checkStateChanged(evt); + } + } + } + + // Override + public void setModel(TreeModel newModel) { + super.setModel(newModel); + resetCheckingState(); + } + + // New method that returns only the checked paths (totally ignores original + // "selection" mechanism) + public TreePath[] getCheckedPaths() { + return checkedPaths.toArray(new TreePath[checkedPaths.size()]); + } + + // Returns true in case that the node is selected, has children but not all of + // them are selected + public boolean isSelectedPartially(TreePath path) { + CheckedNode cn = nodesCheckingState.get(path); + return cn.isSelected && cn.hasChildren && !cn.allChildrenSelected; + } + + private void resetCheckingState() { + nodesCheckingState = new HashMap(); + checkedPaths = new HashSet(); + ElementNode node = (ElementNode) getModel().getRoot(); + if (node == null) { + return; + } + addSubtreeToCheckingStateTracking(node); + } + + // Creating data structure of the current model for the checking mechanism + private void addSubtreeToCheckingStateTracking(ElementNode node) { + TreeNode[] path = node.getPath(); + TreePath tp = new TreePath(path); + CheckedNode cn = new CheckedNode(false, node.getChildCount() > 0, false); + nodesCheckingState.put(tp, cn); + for (int i = 0; i < node.getChildCount(); i++) { + addSubtreeToCheckingStateTracking( + (ElementNode) tp.pathByAddingChild(node.getChildAt(i)).getLastPathComponent()); + } + } + + // Overriding cell renderer by a class that ignores the original "selection" + // mechanism + // It decides how to show the nodes due to the checking-mechanism + private class CheckBoxCellRenderer extends JPanel implements TreeCellRenderer { + private static final long serialVersionUID = -7341833835878991719L; + JCheckBox checkBox; + JLabel label; + + public CheckBoxCellRenderer() { + super(); + this.setLayout(new BorderLayout()); + checkBox = new JCheckBox(); + label = new JLabel(); + add(label, BorderLayout.WEST); + add(checkBox, BorderLayout.CENTER); + setOpaque(false); + } + + @Override + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean selected, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + ElementNode node = (ElementNode) value; + Object obj = node.getUserObject(); + TreePath tp = new TreePath(node.getPath()); + CheckedNode cn = nodesCheckingState.get(tp); - // Defining a new event type for the checking mechanism and preparing - // event-handling mechanism - protected EventListenerList listenerList = new EventListenerList(); + if (cn == null) { + return this; + } + + if (obj instanceof IDiagramUIModel) + label.setIcon(new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.DIAGRAM_LOGO))); + else if (obj instanceof IClass) + label.setIcon(new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.CLASS_LOGO))); + else if (obj instanceof IDataType) + label.setIcon(new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.DATATYPE_LOGO))); + else if (obj instanceof IAttribute) + label.setIcon(new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.ATTRIBUTE_LOGO))); + else if (obj instanceof IAssociation) + label.setIcon( + new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.ASSOCIATION_LOGO))); + else if (obj instanceof IAssociationEnd) + label.setIcon(new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.ATTRIBUTE_LOGO))); + else if (obj instanceof IGeneralization) + label.setIcon( + new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.GENERALIZATION_LOGO))); + else if (obj instanceof IGeneralizationSet) + label.setIcon( + new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.GENERALIZATION_SET_LOGO))); + else if (obj instanceof IAssociationClass) + label.setIcon( + new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.ASSOCIATION_LOGO))); + else + label.setIcon(new ImageIcon(ViewManagerUtils.getFilePath(ViewManagerUtils.PACKAGE_LOGO))); - public class CheckChangeEvent extends EventObject { - private static final long serialVersionUID = -8100230309044193368L; + checkBox.setSelected(cn.isSelected); + checkBox.setText(getNameNode(node)); - public CheckChangeEvent(Object source) { - super(source); - } - } - - public interface CheckChangeEventListener extends EventListener { - public void checkStateChanged(CheckChangeEvent event); - } - - public void addCheckChangeEventListener(CheckChangeEventListener listener) { - listenerList.add(CheckChangeEventListener.class, listener); - } - - public void removeCheckChangeEventListener(CheckChangeEventListener listener) { - listenerList.remove(CheckChangeEventListener.class, listener); - } - - void fireCheckChangeEvent(CheckChangeEvent evt) { - Object[] listeners = listenerList.getListenerList(); - for (int i = 0; i < listeners.length; i++) { - if (listeners[i] == CheckChangeEventListener.class) { - ((CheckChangeEventListener) listeners[i + 1]).checkStateChanged(evt); - } - } - } - - // Override - public void setModel(TreeModel newModel) { - super.setModel(newModel); - resetCheckingState(); - } - - // New method that returns only the checked paths (totally ignores original - // "selection" mechanism) - public TreePath[] getCheckedPaths() { - return checkedPaths.toArray(new TreePath[checkedPaths.size()]); - } - - // Returns true in case that the node is selected, has children but not all of - // them are selected - public boolean isSelectedPartially(TreePath path) { - CheckedNode cn = nodesCheckingState.get(path); - return cn.isSelected && cn.hasChildren && !cn.allChildrenSelected; - } - - private void resetCheckingState() { - nodesCheckingState = new HashMap(); - checkedPaths = new HashSet(); - ElementNode node = (ElementNode) getModel().getRoot(); - if (node == null) { - return; - } - addSubtreeToCheckingStateTracking(node); - } - - // Creating data structure of the current model for the checking mechanism - private void addSubtreeToCheckingStateTracking(ElementNode node) { - TreeNode[] path = node.getPath(); - TreePath tp = new TreePath(path); - CheckedNode cn = new CheckedNode(false, node.getChildCount() > 0, false); - nodesCheckingState.put(tp, cn); - for (int i = 0; i < node.getChildCount(); i++) { - addSubtreeToCheckingStateTracking( - (ElementNode) tp.pathByAddingChild(node.getChildAt(i)).getLastPathComponent()); - } - } - - // Overriding cell renderer by a class that ignores the original "selection" - // mechanism - // It decides how to show the nodes due to the checking-mechanism - private class CheckBoxCellRenderer extends JPanel implements TreeCellRenderer { - private static final long serialVersionUID = -7341833835878991719L; - JCheckBox checkBox; - JLabel label; - - public CheckBoxCellRenderer() { - super(); - this.setLayout(new BorderLayout()); - checkBox = new JCheckBox(); - label = new JLabel(); - add(label, BorderLayout.WEST); - add(checkBox, BorderLayout.CENTER); - setOpaque(false); - } - - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, - boolean leaf, int row, boolean hasFocus) { - ElementNode node = (ElementNode) value; - Object obj = node.getUserObject(); - TreePath tp = new TreePath(node.getPath()); - CheckedNode cn = nodesCheckingState.get(tp); - - if (cn == null) { - return this; - } - - if (obj instanceof IDiagramUIModel) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.DIAGRAM_LOGO))); - else if (obj instanceof IClass) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.CLASS_LOGO))); - else if (obj instanceof IDataType) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.DATATYPE_LOGO))); - else if (obj instanceof IAttribute) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.ATTRIBUTE_LOGO))); - else if (obj instanceof IAssociation) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.ASSOCIATION_LOGO))); - else if (obj instanceof IAssociationEnd) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.ATTRIBUTE_LOGO))); - else if (obj instanceof IGeneralization) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.GENERALIZATION_LOGO))); - else if (obj instanceof IGeneralizationSet) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.GENERALIZATION_SET_LOGO))); - else if (obj instanceof IAssociationClass) - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.ASSOCIATION_LOGO))); - else - label.setIcon(new ImageIcon(ViewUtils.getFilePath(ViewUtils.PACKAGE_LOGO))); - - checkBox.setSelected(cn.isSelected); - checkBox.setText(getNameNode(node)); - - checkBox.setOpaque(cn.isSelected && cn.hasChildren && !cn.allChildrenSelected); - - return this; - } + checkBox.setOpaque(cn.isSelected && cn.hasChildren && !cn.allChildrenSelected); - } + return this; + } + } - private String getNameNode(ElementNode node) { - return NameUtil.getDisplayName(node.getUserObject()); - } + private String getNameNode(ElementNode node) { + return GUFOExportView.getDisplayName(node.getUserObject()); + } - public JCheckBoxTree(String type) { + public JCheckBoxTree(String type) { - super(getTreeModel(type)); - // Disabling toggling by double-click - this.setToggleClickCount(0); - // Overriding cell renderer by new one defined above - CheckBoxCellRenderer cellRenderer = new CheckBoxCellRenderer(); - this.setCellRenderer(cellRenderer); + super(getTreeModel(type)); + // Disabling toggling by double-click + this.setToggleClickCount(0); + // Overriding cell renderer by new one defined above + CheckBoxCellRenderer cellRenderer = new CheckBoxCellRenderer(); + this.setCellRenderer(cellRenderer); - DefaultTreeSelectionModel dtsm = new DefaultTreeSelectionModel() { - private static final long serialVersionUID = -8190634240451667286L; + DefaultTreeSelectionModel dtsm = + new DefaultTreeSelectionModel() { + private static final long serialVersionUID = -8190634240451667286L; - public void setSelectionPath(TreePath path) { + public void setSelectionPath(TreePath path) { boolean checkMode = !nodesCheckingState.get(path).isSelected; checkSubTree(path, checkMode); updatePredecessorsWithCheckMode(path, checkMode); @@ -232,731 +239,758 @@ public void setSelectionPath(TreePath path) { selectTypeNodes((ElementNode) path.getLastPathComponent()); - if (((ElementNode) path.getLastPathComponent()).getUserObject() instanceof IGeneralizationSet) - selectAllGeneralizationsFromSet((ElementNode) path.getLastPathComponent(), checkMode); + if (((ElementNode) path.getLastPathComponent()).getUserObject() + instanceof IGeneralizationSet) + selectAllGeneralizationsFromSet((ElementNode) path.getLastPathComponent(), checkMode); selfPointer.repaint(); - } + } - public void addSelectionPath(TreePath path) { - } + public void addSelectionPath(TreePath path) {} - public void removeSelectionPath(TreePath path) { - } + public void removeSelectionPath(TreePath path) {} - public void setSelectionPaths(TreePath[] pPaths) { - } - }; - - this.setSelectionModel(dtsm); - } + public void setSelectionPaths(TreePath[] pPaths) {} + }; - private void visitAllNodesAndCheckSimilar(ElementNode root, ElementNode nodeToCompare) { + this.setSelectionModel(dtsm); + } - // if same Object - if (((ElementNode) root).getUserObject().equals(nodeToCompare.getUserObject())) { + private void visitAllNodesAndCheckSimilar(ElementNode root, ElementNode nodeToCompare) { - TreeNode[] old_treeNode = nodeToCompare.getPath(); - TreePath oldTp = new TreePath(old_treeNode); + // if same Object + if (((ElementNode) root).getUserObject().equals(nodeToCompare.getUserObject())) { - TreeNode[] new_treeNode = root.getPath(); - TreePath newTp = new TreePath(new_treeNode); + TreeNode[] old_treeNode = nodeToCompare.getPath(); + TreePath oldTp = new TreePath(old_treeNode); - // if different paths - if (!oldTp.toString().equals(newTp.toString())) { + TreeNode[] new_treeNode = root.getPath(); + TreePath newTp = new TreePath(new_treeNode); - boolean checkMode = nodesCheckingState.get(oldTp).isSelected; + // if different paths + if (!oldTp.toString().equals(newTp.toString())) { - CheckedNode cn = nodesCheckingState.get(newTp); - cn.isSelected = checkMode; + boolean checkMode = nodesCheckingState.get(oldTp).isSelected; - if (checkMode) - checkedPaths.add(newTp); - else - checkedPaths.remove(newTp); - } + CheckedNode cn = nodesCheckingState.get(newTp); + cn.isSelected = checkMode; + if (checkMode) checkedPaths.add(newTp); + else checkedPaths.remove(newTp); } + } - if (root.getChildCount() >= 0) { - for (Enumeration e = root.children(); e.hasMoreElements(); ) { - ElementNode n = (ElementNode) e.nextElement(); + if (root.getChildCount() >= 0) { + for (Enumeration e = root.children(); e.hasMoreElements(); ) { + ElementNode n = (ElementNode) e.nextElement(); - visitAllNodesAndCheckSimilar(n, nodeToCompare); - } + visitAllNodesAndCheckSimilar(n, nodeToCompare); } - } - - private void visitAllAndCheckSameId(ElementNode root, String id, boolean checkMode) { + } + } - if (root.getUserObject() instanceof IModelElement) { - IModelElement rootModelElement = ((IModelElement) ((DefaultMutableTreeNode) root).getUserObject()); + private void visitAllAndCheckSameId(ElementNode root, String id, boolean checkMode) { - // if same Object - if (rootModelElement.getId().equals(id)) { + if (root.getUserObject() instanceof IModelElement) { + IModelElement rootModelElement = + ((IModelElement) ((DefaultMutableTreeNode) root).getUserObject()); - TreeNode[] new_treeNode = root.getPath(); - TreePath newTp = new TreePath(new_treeNode); + // if same Object + if (rootModelElement.getId().equals(id)) { - CheckedNode cn = nodesCheckingState.get(newTp); - cn.isSelected = checkMode; + TreeNode[] new_treeNode = root.getPath(); + TreePath newTp = new TreePath(new_treeNode); - if (checkMode) - checkedPaths.add(newTp); - else - checkedPaths.remove(newTp); + CheckedNode cn = nodesCheckingState.get(newTp); + cn.isSelected = checkMode; - } + if (checkMode) checkedPaths.add(newTp); + else checkedPaths.remove(newTp); } + } - if (root.getChildCount() >= 0) { - for (Enumeration e = root.children(); e.hasMoreElements(); ) { - ElementNode n = (ElementNode) e.nextElement(); + if (root.getChildCount() >= 0) { + for (Enumeration e = root.children(); e.hasMoreElements(); ) { + ElementNode n = (ElementNode) e.nextElement(); - visitAllAndCheckSameId(n, id, checkMode); - } + visitAllAndCheckSameId(n, id, checkMode); } - } - - protected void findSimilarNodes(ElementNode node) { + } + } - for (int i = 0; i < node.getChildCount(); i++) - findSimilarNodes((ElementNode) node.getChildAt(i)); + protected void findSimilarNodes(ElementNode node) { - ElementNode root = (ElementNode) this.getModel().getRoot(); - visitAllNodesAndCheckSimilar(root, node); - } + for (int i = 0; i < node.getChildCount(); i++) + findSimilarNodes((ElementNode) node.getChildAt(i)); - private void visitAllNodesAndCheckType(ElementNode root, ElementNode nodeToCompare) { - String typeOriginal = ""; - String typeCurrentNode = ""; + ElementNode root = (ElementNode) this.getModel().getRoot(); + visitAllNodesAndCheckSimilar(root, node); + } - if (nodeToCompare.getUserObject() instanceof IClass) - typeOriginal = ((IClass) nodeToCompare.getUserObject()).getName(); + private void visitAllNodesAndCheckType(ElementNode root, ElementNode nodeToCompare) { + String typeOriginal = ""; + String typeCurrentNode = ""; - if (nodeToCompare.getUserObject() instanceof IAttribute) - typeOriginal = ((IAttribute) nodeToCompare.getUserObject()).getTypeAsString(); + if (nodeToCompare.getUserObject() instanceof IClass) + typeOriginal = ((IClass) nodeToCompare.getUserObject()).getName(); - if (root.getUserObject() instanceof IClass) - typeCurrentNode = ((IClass) root.getUserObject()).getName(); + if (nodeToCompare.getUserObject() instanceof IAttribute) + typeOriginal = ((IAttribute) nodeToCompare.getUserObject()).getTypeAsString(); - if (root.getUserObject() instanceof IDataType) - typeCurrentNode = ((IDataType) root.getUserObject()).getName(); + if (root.getUserObject() instanceof IClass) + typeCurrentNode = ((IClass) root.getUserObject()).getName(); - if (typeOriginal != null && typeCurrentNode.contentEquals(typeOriginal)) { + if (root.getUserObject() instanceof IDataType) + typeCurrentNode = ((IDataType) root.getUserObject()).getName(); - TreeNode[] old_treeNode = nodeToCompare.getPath(); - TreePath oldTp = new TreePath(old_treeNode); + if (typeOriginal != null && typeCurrentNode.contentEquals(typeOriginal)) { - TreeNode[] new_treeNode = root.getPath(); - TreePath newTp = new TreePath(new_treeNode); + TreeNode[] old_treeNode = nodeToCompare.getPath(); + TreePath oldTp = new TreePath(old_treeNode); - // if different paths - if (!oldTp.toString().equals(newTp.toString())) { - boolean checkMode = nodesCheckingState.get(oldTp).isSelected; + TreeNode[] new_treeNode = root.getPath(); + TreePath newTp = new TreePath(new_treeNode); - if ((root.getUserObject() instanceof IClass || root.getUserObject() instanceof IDataType) - && checkMode == true) { + // if different paths + if (!oldTp.toString().equals(newTp.toString())) { + boolean checkMode = nodesCheckingState.get(oldTp).isSelected; - CheckedNode cn = nodesCheckingState.get(newTp); - cn.isSelected = checkMode; + if ((root.getUserObject() instanceof IClass || root.getUserObject() instanceof IDataType) + && checkMode == true) { - if (checkMode) - checkedPaths.add(newTp); - else - checkedPaths.remove(newTp); - } + CheckedNode cn = nodesCheckingState.get(newTp); + cn.isSelected = checkMode; - } + if (checkMode) checkedPaths.add(newTp); + else checkedPaths.remove(newTp); + } } + } - if (root.getChildCount() >= 0) { - for (Enumeration e = root.children(); e.hasMoreElements(); ) { - ElementNode n = (ElementNode) e.nextElement(); + if (root.getChildCount() >= 0) { + for (Enumeration e = root.children(); e.hasMoreElements(); ) { + ElementNode n = (ElementNode) e.nextElement(); + + visitAllNodesAndCheckType(n, nodeToCompare); + } + } + } + + protected void selectTypeNodes(ElementNode node) { + ElementNode root = (ElementNode) this.getModel().getRoot(); + visitAllNodesAndCheckType(root, node); + } - visitAllNodesAndCheckType(n, nodeToCompare); - } - } - } - - protected void selectTypeNodes(ElementNode node) { - ElementNode root = (ElementNode) this.getModel().getRoot(); - visitAllNodesAndCheckType(root, node); - } - - protected void selectAllGeneralizationsFromSet(ElementNode node, boolean checkMode) { + protected void selectAllGeneralizationsFromSet(ElementNode node, boolean checkMode) { - if (!(node.getUserObject() instanceof IGeneralizationSet)) - return; + if (!(node.getUserObject() instanceof IGeneralizationSet)) return; - IGeneralizationSet gSet = ((IGeneralizationSet) ((DefaultMutableTreeNode) node).getUserObject()); + IGeneralizationSet gSet = + ((IGeneralizationSet) ((DefaultMutableTreeNode) node).getUserObject()); - IGeneralization[] generalizations = gSet.toGeneralizationArray(); + IGeneralization[] generalizations = gSet.toGeneralizationArray(); - if (generalizations == null) - return; + if (generalizations == null) return; - ElementNode root = (ElementNode) this.getModel().getRoot(); + ElementNode root = (ElementNode) this.getModel().getRoot(); - for (int i = 0; i < generalizations.length; i++) { - visitAllAndCheckSameId(root, generalizations[i].getId(), checkMode); - } - - } - - // When a node is checked/unchecked, updating the states of the predecessors - protected void updatePredecessorsWithCheckMode(TreePath tp, boolean check) { - TreePath parentPath = tp.getParentPath(); - // If it is the root, stop the recursive calls and return - if (parentPath == null) - return; - - CheckedNode currentNode = nodesCheckingState.get(tp); - // It is allowed to choose a class without its attributes - if (((ElementNode) tp.getLastPathComponent()).getUserObject() instanceof IAttribute - && currentNode.isSelected == false) - return; - - CheckedNode parentCheckedNode = nodesCheckingState.get(parentPath); - ElementNode parentNode = (ElementNode) parentPath.getLastPathComponent(); - parentCheckedNode.allChildrenSelected = true; - parentCheckedNode.isSelected = false; - for (int i = 0; i < parentNode.getChildCount(); i++) { - TreePath childPath = parentPath.pathByAddingChild(parentNode.getChildAt(i)); - CheckedNode childCheckedNode = nodesCheckingState.get(childPath); - // It is enough that even one subtree is not fully selected - // to determine that the parent is not fully selected - if (!childCheckedNode.allChildrenSelected) { - parentCheckedNode.allChildrenSelected = false; - } - // If at least one child is selected, selecting also the parent - if (childCheckedNode.isSelected) { - parentCheckedNode.isSelected = true; - } - } - if (parentCheckedNode.isSelected) { - checkedPaths.add(parentPath); - } else { - checkedPaths.remove(parentPath); - } - // Go to upper predecessor - updatePredecessorsWithCheckMode(parentPath, check); - } + for (int i = 0; i < generalizations.length; i++) { + visitAllAndCheckSameId(root, generalizations[i].getId(), checkMode); + } + } - // Recursively checks/unchecks a subtree - protected void checkSubTree(TreePath tp, boolean check) { - CheckedNode cn = nodesCheckingState.get(tp); - cn.isSelected = check; - ElementNode node = (ElementNode) tp.getLastPathComponent(); - selectTypeNodes(node); - for (int i = 0; i < node.getChildCount(); i++) { - checkSubTree(tp.pathByAddingChild(node.getChildAt(i)), check); - } - cn.allChildrenSelected = check; - if (check) { - checkedPaths.add(tp); - } else { - checkedPaths.remove(tp); - } - } + // When a node is checked/unchecked, updating the states of the predecessors + protected void updatePredecessorsWithCheckMode(TreePath tp, boolean check) { + TreePath parentPath = tp.getParentPath(); + // If it is the root, stop the recursive calls and return + if (parentPath == null) return; - private static TreeModel getTreeModel(String type) { - if (type.equals("package")) - return getTreeModelPackage(); - else - return getTreeModelDiagram(); - } + CheckedNode currentNode = nodesCheckingState.get(tp); + // It is allowed to choose a class without its attributes + if (((ElementNode) tp.getLastPathComponent()).getUserObject() instanceof IAttribute + && currentNode.isSelected == false) return; - private static TreeModel getTreeModelPackage() { - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - final String[] rootLevelElements = {IModelElementFactory.MODEL_TYPE_PACKAGE, - IModelElementFactory.MODEL_TYPE_MODEL, IModelElementFactory.MODEL_TYPE_CLASS, - IModelElementFactory.MODEL_TYPE_DATA_TYPE}; - final String[] anyLevelElements = {IModelElementFactory.MODEL_TYPE_GENERALIZATION, - IModelElementFactory.MODEL_TYPE_ASSOCIATION, IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS}; + CheckedNode parentCheckedNode = nodesCheckingState.get(parentPath); + ElementNode parentNode = (ElementNode) parentPath.getLastPathComponent(); + parentCheckedNode.allChildrenSelected = true; + parentCheckedNode.isSelected = false; + for (int i = 0; i < parentNode.getChildCount(); i++) { + TreePath childPath = parentPath.pathByAddingChild(parentNode.getChildAt(i)); + CheckedNode childCheckedNode = nodesCheckingState.get(childPath); + // It is enough that even one subtree is not fully selected + // to determine that the parent is not fully selected + if (!childCheckedNode.allChildrenSelected) { + parentCheckedNode.allChildrenSelected = false; + } + // If at least one child is selected, selecting also the parent + if (childCheckedNode.isSelected) { + parentCheckedNode.isSelected = true; + } + } + if (parentCheckedNode.isSelected) { + checkedPaths.add(parentPath); + } else { + checkedPaths.remove(parentPath); + } + // Go to upper predecessor + updatePredecessorsWithCheckMode(parentPath, check); + } + + // Recursively checks/unchecks a subtree + protected void checkSubTree(TreePath tp, boolean check) { + CheckedNode cn = nodesCheckingState.get(tp); + cn.isSelected = check; + ElementNode node = (ElementNode) tp.getLastPathComponent(); + selectTypeNodes(node); + for (int i = 0; i < node.getChildCount(); i++) { + checkSubTree(tp.pathByAddingChild(node.getChildAt(i)), check); + } + cn.allChildrenSelected = check; + if (check) { + checkedPaths.add(tp); + } else { + checkedPaths.remove(tp); + } + } + + private static TreeModel getTreeModel(String type) { + if (type.equals("package")) return getTreeModelPackage(); + else return getTreeModelDiagram(); + } + + private static TreeModel getTreeModelPackage() { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + final String[] rootLevelElements = { + IModelElementFactory.MODEL_TYPE_PACKAGE, + IModelElementFactory.MODEL_TYPE_MODEL, + IModelElementFactory.MODEL_TYPE_CLASS, + IModelElementFactory.MODEL_TYPE_DATA_TYPE + }; + final String[] anyLevelElements = { + IModelElementFactory.MODEL_TYPE_GENERALIZATION, + IModelElementFactory.MODEL_TYPE_ASSOCIATION, + IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS + }; + + ElementNode root = new ElementNode("All Models"); + + for (IModelElement rootElement : project.toModelElementArray(rootLevelElements)) + setChildrenRecursively(rootElement, root); + + for (IModelElement rootElement : project.toAllLevelModelElementArray(anyLevelElements)) + setChildrenRecursively(rootElement, root); + + return new DefaultTreeModel(root); + } + + private static TreeModel getTreeModelDiagram() { + final IDiagramUIModel[] diagramArray = + ApplicationManager.instance().getProjectManager().getProject().toDiagramArray(); + + ElementNode root = new ElementNode("All Diagrams"); + + if (diagramArray != null) { + + for (IDiagramUIModel diagram : diagramArray) { + + if (diagram instanceof IClassDiagramUIModel) { + ElementNode parent; + parent = new ElementNode(diagram); + root.add(parent); + setChildrenFromDiagrams(diagram, parent); + } + } + } + + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + final String[] datatypes = {IModelElementFactory.MODEL_TYPE_DATA_TYPE}; + + for (IModelElement datatype : project.toModelElementArray(datatypes)) { + ElementNode datatypeNodes = new ElementNode(datatype); + root.add(datatypeNodes); + } + + return new DefaultTreeModel(root); + } + + private static ElementNode setChildrenRecursively( + IModelElement modelElement, ElementNode parent) { + ElementNode newRoot = parent; - ElementNode root = new ElementNode("All Models"); + final String[] rootLevelElements = { + IModelElementFactory.MODEL_TYPE_PACKAGE, + IModelElementFactory.MODEL_TYPE_MODEL, + IModelElementFactory.MODEL_TYPE_CLASS, + IModelElementFactory.MODEL_TYPE_ASSOCIATION, + IModelElementFactory.MODEL_TYPE_DATA_TYPE, + IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET, + IModelElementFactory.MODEL_TYPE_GENERALIZATION + }; - for (IModelElement rootElement : project.toModelElementArray(rootLevelElements)) - setChildrenRecursively(rootElement, root); + if (modelElement instanceof IModel) { + IModel model = (IModel) modelElement; - for (IModelElement rootElement : project.toAllLevelModelElementArray(anyLevelElements)) - setChildrenRecursively(rootElement, root); + ElementNode newParent; + newParent = new ElementNode(model); - return new DefaultTreeModel(root); - } + newRoot.add(newParent); - private static TreeModel getTreeModelDiagram() { - final IDiagramUIModel[] diagramArray = ApplicationManager.instance().getProjectManager().getProject() - .toDiagramArray(); + for (IModelElement element : model.toChildArray(rootLevelElements)) + setChildrenRecursively(element, newParent); + } - ElementNode root = new ElementNode("All Diagrams"); + if (modelElement instanceof IPackage) { + IPackage pckg = (IPackage) modelElement; - if (diagramArray != null) { + ElementNode newParent; + newParent = new ElementNode(pckg); - for (IDiagramUIModel diagram : diagramArray) { + newRoot.add(newParent); - if (diagram instanceof IClassDiagramUIModel) { - ElementNode parent; - parent = new ElementNode(diagram); - root.add(parent); - setChildrenFromDiagrams(diagram, parent); - } - } - } + for (IModelElement element : pckg.toChildArray(rootLevelElements)) + setChildrenRecursively(element, newParent); + } - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - final String[] datatypes = {IModelElementFactory.MODEL_TYPE_DATA_TYPE}; + if (modelElement instanceof IClass) { + IClass _class = (IClass) modelElement; + ElementNode newParent; - for (IModelElement datatype : project.toModelElementArray(datatypes)) { - ElementNode datatypeNodes = new ElementNode(datatype); - root.add(datatypeNodes); - } + newParent = new ElementNode(_class); - return new DefaultTreeModel(root); - } + IAttribute[] attributes = _class.toAttributeArray(); - private static ElementNode setChildrenRecursively(IModelElement modelElement, ElementNode parent) { - ElementNode newRoot = parent; + for (int j = 0; attributes != null && j < attributes.length; j++) + newParent.add(new ElementNode(attributes[j])); - final String[] rootLevelElements = {IModelElementFactory.MODEL_TYPE_PACKAGE, - IModelElementFactory.MODEL_TYPE_MODEL, IModelElementFactory.MODEL_TYPE_CLASS, - IModelElementFactory.MODEL_TYPE_ASSOCIATION, IModelElementFactory.MODEL_TYPE_DATA_TYPE, - IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET, IModelElementFactory.MODEL_TYPE_GENERALIZATION}; + newRoot.add(newParent); + } - if (modelElement instanceof IModel) { - IModel model = (IModel) modelElement; + if (modelElement instanceof IAssociation) { + IAssociation association = (IAssociation) modelElement; + ElementNode newParent; - ElementNode newParent; - newParent = new ElementNode(model); + newParent = new ElementNode(association); - newRoot.add(newParent); + IAssociationEnd fromEnd = (IAssociationEnd) association.getFromEnd(); + IAssociationEnd toEnd = (IAssociationEnd) association.getToEnd(); - for (IModelElement element : model.toChildArray(rootLevelElements)) - setChildrenRecursively(element, newParent); - } + if (fromEnd != null) newParent.add(new ElementNode(fromEnd)); - if (modelElement instanceof IPackage) { - IPackage pckg = (IPackage) modelElement; + if (toEnd != null) newParent.add(new ElementNode(toEnd)); - ElementNode newParent; - newParent = new ElementNode(pckg); + newRoot.add(newParent); + } - newRoot.add(newParent); + if (modelElement instanceof IDataType) { + IDataType _class = (IDataType) modelElement; - for (IModelElement element : pckg.toChildArray(rootLevelElements)) - setChildrenRecursively(element, newParent); - } + ElementNode newParent; + newParent = new ElementNode(_class); - if (modelElement instanceof IClass) { - IClass _class = (IClass) modelElement; - ElementNode newParent; + newRoot.add(newParent); + } - newParent = new ElementNode(_class); + if (modelElement instanceof IGeneralizationSet) { + IGeneralizationSet generalizationSet = (IGeneralizationSet) modelElement; + ElementNode newParent; - IAttribute[] attributes = _class.toAttributeArray(); + newParent = new ElementNode(generalizationSet); + newRoot.add(newParent); + } - for (int j = 0; attributes != null && j < attributes.length; j++) - newParent.add(new ElementNode(attributes[j])); + if (modelElement instanceof IGeneralization) { + IGeneralization generalization = (IGeneralization) modelElement; + ElementNode newParent; - newRoot.add(newParent); + if (generalization.getFrom() != null && generalization.getTo() != null) { + newParent = new ElementNode(generalization); + newRoot.add(newParent); } + } - if (modelElement instanceof IAssociation) { - IAssociation association = (IAssociation) modelElement; - ElementNode newParent; + if (modelElement instanceof IAssociationClass) { + IAssociationClass associationClass = (IAssociationClass) modelElement; + ElementNode newParent; - newParent = new ElementNode(association); + newParent = new ElementNode(associationClass); + newRoot.add(newParent); + } - IAssociationEnd fromEnd = (IAssociationEnd) association.getFromEnd(); - IAssociationEnd toEnd = (IAssociationEnd) association.getToEnd(); + return newRoot; + } - if (fromEnd != null) - newParent.add(new ElementNode(fromEnd)); + private static ElementNode setChildrenFromDiagrams(IDiagramUIModel diagram, ElementNode parent) { + ElementNode newRoot = parent; - if (toEnd != null) - newParent.add(new ElementNode(toEnd)); + IDiagramElement[] models = diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_MODEL); + IDiagramElement[] pckgs = + diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_PACKAGE); + IDiagramElement[] classes = + diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_CLASS); + IDiagramElement[] associations = + diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + IDiagramElement[] generalizationSets = + diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET); + IDiagramElement[] generalizations = + diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_GENERALIZATION); + IDiagramElement[] associationClasses = + diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS); - newRoot.add(newParent); - } - - if (modelElement instanceof IDataType) { - IDataType _class = (IDataType) modelElement; + for (int i = 0; models != null && i < models.length; i++) { + if (models[i].getModelElement() != null) { + IModel model = (IModel) models[i].getModelElement(); - ElementNode newParent; - newParent = new ElementNode(_class); + ElementNode newParent; + newParent = new ElementNode(model); - newRoot.add(newParent); - } + newRoot.add(newParent); - if (modelElement instanceof IGeneralizationSet) { - IGeneralizationSet generalizationSet = (IGeneralizationSet) modelElement; - ElementNode newParent; + IModelElement[] elements = model.toChildArray(); - newParent = new ElementNode(generalizationSet); - newRoot.add(newParent); + for (int j = 0; elements != null && j < elements.length; j++) + setChildrenRecursively(elements[i], newParent); } + } - if (modelElement instanceof IGeneralization) { - IGeneralization generalization = (IGeneralization) modelElement; - ElementNode newParent; + for (int i = 0; pckgs != null && i < pckgs.length; i++) { + if (pckgs[i].getModelElement() != null) { + IPackage pckg = (IPackage) pckgs[i].getModelElement(); - if (generalization.getFrom() != null && generalization.getTo() != null) { - newParent = new ElementNode(generalization); - newRoot.add(newParent); - } - } - - if (modelElement instanceof IAssociationClass) { - IAssociationClass associationClass = (IAssociationClass) modelElement; - ElementNode newParent; - - newParent = new ElementNode(associationClass); - newRoot.add(newParent); - } - - return newRoot; - } - - private static ElementNode setChildrenFromDiagrams(IDiagramUIModel diagram, ElementNode parent) { - ElementNode newRoot = parent; - - IDiagramElement[] models = diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_MODEL); - IDiagramElement[] pckgs = diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_PACKAGE); - IDiagramElement[] classes = diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_CLASS); - IDiagramElement[] associations = diagram.toDiagramElementArray(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - IDiagramElement[] generalizationSets = diagram - .toDiagramElementArray(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET); - IDiagramElement[] generalizations = diagram - .toDiagramElementArray(IModelElementFactory.MODEL_TYPE_GENERALIZATION); - IDiagramElement[] associationClasses = diagram - .toDiagramElementArray(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS); + ElementNode newParent; + newParent = new ElementNode(pckg); - for (int i = 0; models != null && i < models.length; i++) { - if (models[i].getModelElement() != null) { - IModel model = (IModel) models[i].getModelElement(); + newRoot.add(newParent); - ElementNode newParent; - newParent = new ElementNode(model); + IModelElement[] elements = pckg.toChildArray(); - newRoot.add(newParent); - - IModelElement[] elements = model.toChildArray(); - - for (int j = 0; elements != null && j < elements.length; j++) - setChildrenRecursively(elements[i], newParent); - } + for (int j = 0; elements != null && j < elements.length; j++) + setChildrenRecursively(elements[i], newParent); } + } - for (int i = 0; pckgs != null && i < pckgs.length; i++) { - if (pckgs[i].getModelElement() != null) { - IPackage pckg = (IPackage) pckgs[i].getModelElement(); + for (int i = 0; classes != null && i < classes.length; i++) { + if (classes[i].getModelElement() != null) { + IClass _class = (IClass) classes[i].getModelElement(); - ElementNode newParent; - newParent = new ElementNode(pckg); + ElementNode newParent; + newParent = new ElementNode(_class); - newRoot.add(newParent); + IAttribute[] attributes = _class.toAttributeArray(); - IModelElement[] elements = pckg.toChildArray(); + for (int j = 0; attributes != null && j < attributes.length; j++) + newParent.add(new ElementNode(attributes[j])); - for (int j = 0; elements != null && j < elements.length; j++) - setChildrenRecursively(elements[i], newParent); - } + newRoot.add(newParent); } + } - for (int i = 0; classes != null && i < classes.length; i++) { - if (classes[i].getModelElement() != null) { - IClass _class = (IClass) classes[i].getModelElement(); - - ElementNode newParent; - newParent = new ElementNode(_class); + for (int i = 0; associations != null && i < associations.length; i++) { + if (associations[i].getModelElement() != null) { + IAssociation association = (IAssociation) associations[i].getModelElement(); + ElementNode newParent; - IAttribute[] attributes = _class.toAttributeArray(); - - for (int j = 0; attributes != null && j < attributes.length; j++) - newParent.add(new ElementNode(attributes[j])); - - newRoot.add(newParent); - } - } + newParent = new ElementNode(association); - for (int i = 0; associations != null && i < associations.length; i++) { - if (associations[i].getModelElement() != null) { - IAssociation association = (IAssociation) associations[i].getModelElement(); - ElementNode newParent; + IAssociationEnd fromEnd = (IAssociationEnd) association.getFromEnd(); + IAssociationEnd toEnd = (IAssociationEnd) association.getToEnd(); - newParent = new ElementNode(association); + if (fromEnd != null) newParent.add(new ElementNode(fromEnd)); - IAssociationEnd fromEnd = (IAssociationEnd) association.getFromEnd(); - IAssociationEnd toEnd = (IAssociationEnd) association.getToEnd(); + if (toEnd != null) newParent.add(new ElementNode(toEnd)); - if (fromEnd != null) - newParent.add(new ElementNode(fromEnd)); - - if (toEnd != null) - newParent.add(new ElementNode(toEnd)); - - newRoot.add(newParent); - - } + newRoot.add(newParent); } + } - for (int i = 0; generalizationSets != null && i < generalizationSets.length; i++) { - if (generalizationSets[i].getModelElement() != null) { - IGeneralizationSet generalizationSet = (IGeneralizationSet) generalizationSets[i].getModelElement(); - ElementNode newParent; + for (int i = 0; generalizationSets != null && i < generalizationSets.length; i++) { + if (generalizationSets[i].getModelElement() != null) { + IGeneralizationSet generalizationSet = + (IGeneralizationSet) generalizationSets[i].getModelElement(); + ElementNode newParent; - newParent = new ElementNode(generalizationSet); - newRoot.add(newParent); - } + newParent = new ElementNode(generalizationSet); + newRoot.add(newParent); } + } - for (int i = 0; generalizations != null && i < generalizations.length; i++) { - if (generalizations[i].getModelElement() != null) { - IGeneralization generalization = (IGeneralization) generalizations[i].getModelElement(); - ElementNode newParent; + for (int i = 0; generalizations != null && i < generalizations.length; i++) { + if (generalizations[i].getModelElement() != null) { + IGeneralization generalization = (IGeneralization) generalizations[i].getModelElement(); + ElementNode newParent; - newParent = new ElementNode(generalization); - newRoot.add(newParent); - } + newParent = new ElementNode(generalization); + newRoot.add(newParent); } + } - for (int i = 0; associationClasses != null && i < associationClasses.length; i++) { - if (associationClasses[i].getModelElement() != null) { - IAssociationClass associationClass = (IAssociationClass) associationClasses[i].getModelElement(); - ElementNode newParent; + for (int i = 0; associationClasses != null && i < associationClasses.length; i++) { + if (associationClasses[i].getModelElement() != null) { + IAssociationClass associationClass = + (IAssociationClass) associationClasses[i].getModelElement(); + ElementNode newParent; - newParent = new ElementNode(associationClass); - newRoot.add(newParent); - } + newParent = new ElementNode(associationClass); + newRoot.add(newParent); } + } - return newRoot; - } + return newRoot; + } - private void visitAllNodesAndCheckSameId(ElementNode root, String id) { + private void visitAllNodesAndCheckSameId(ElementNode root, String id) { + TreeNode[] treeNode = root.getPath(); + TreePath tp = new TreePath(treeNode); + CheckedNode cn = new CheckedNode(false, root.getChildCount() > 0, false); - TreeNode[] treeNode = root.getPath(); - TreePath tp = new TreePath(treeNode); - CheckedNode cn = new CheckedNode(false, root.getChildCount() > 0, false); - - TreePath parentPath = tp.getParentPath(); - // the root item is assumed to be always selected if not this function is not - // called - if (parentPath == null) { - cn.isSelected = true; - checkedPaths.add(tp); - nodesCheckingState.put(tp, cn); - } + TreePath parentPath = tp.getParentPath(); + // the root item is assumed to be always selected if not this function is not + // called + if (parentPath == null) { + cn.isSelected = true; + checkedPaths.add(tp); + nodesCheckingState.put(tp, cn); + } - // if modelElement - if (((ElementNode) root).getUserObject() instanceof IModelElement) { - IModelElement nodeElement = (IModelElement) root.getUserObject(); + // if modelElement + if (((ElementNode) root).getUserObject() instanceof IModelElement) { + IModelElement nodeElement = (IModelElement) root.getUserObject(); - if (nodeElement.getId().contentEquals(id)) { - cn.isSelected = true; - checkedPaths.add(tp); - nodesCheckingState.put(tp, cn); - } + if (nodeElement.getId().contentEquals(id)) { + cn.isSelected = true; + checkedPaths.add(tp); + nodesCheckingState.put(tp, cn); } + } - // if Diagram - if (((ElementNode) root).getUserObject() instanceof IDiagramUIModel) { - IDiagramUIModel diagramElement = (IDiagramUIModel) root.getUserObject(); + // if Diagram + if (((ElementNode) root).getUserObject() instanceof IDiagramUIModel) { + IDiagramUIModel diagramElement = (IDiagramUIModel) root.getUserObject(); - if (diagramElement.getId().contentEquals(id)) { - cn.isSelected = true; - checkedPaths.add(tp); - nodesCheckingState.put(tp, cn); - } + if (diagramElement.getId().contentEquals(id)) { + cn.isSelected = true; + checkedPaths.add(tp); + nodesCheckingState.put(tp, cn); } + } - if (root.getChildCount() >= 0) { - for (Enumeration e = root.children(); e.hasMoreElements(); ) { - ElementNode n = (ElementNode) e.nextElement(); + if (root.getChildCount() >= 0) { + for (Enumeration e = root.children(); e.hasMoreElements(); ) { + ElementNode n = (ElementNode) e.nextElement(); - visitAllNodesAndCheckSameId(n, id); - } + visitAllNodesAndCheckSameId(n, id); } - } + } + } - public void setNodesCheck(HashSet idElements) { - resetCheckingState(); - ElementNode root = (ElementNode) treeModel.getRoot(); + public void setNodesCheck(HashSet idElements) { + resetCheckingState(); + ElementNode root = (ElementNode) treeModel.getRoot(); - Iterator ite = idElements.iterator(); + Iterator ite = idElements.iterator(); - while (ite.hasNext()) { - String id = ite.next(); - visitAllNodesAndCheckSameId(root, id); - } - - } + while (ite.hasNext()) { + String id = ite.next(); + visitAllNodesAndCheckSameId(root, id); + } + } -public static class ElementNode extends DefaultMutableTreeNode { + public static class ElementNode extends DefaultMutableTreeNode { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public ElementNode(Object userObject) { + public ElementNode(Object userObject) { super(userObject); - } + } - @Override - public void add(MutableTreeNode newChild) { + @Override + public void add(MutableTreeNode newChild) { super.add(newChild); sort(); - } + } - @SuppressWarnings("unchecked") - public void sort() { + @SuppressWarnings("unchecked") + public void sort() { Collections.sort(children, compare()); - } + } - @SuppressWarnings("rawtypes") - private Comparator compare() { + @SuppressWarnings("rawtypes") + private Comparator compare() { return new Comparator() { - @Override - public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) { - String arg1 = ""; - String arg2 = ""; - - if (o1 == null) - return 0; - if (o2 == null) - return 0; - - if (o1.getUserObject() instanceof IDiagramUIModel) { - if (o2.getUserObject() instanceof IDiagramUIModel) { - return ((IDiagramUIModel) o1.getUserObject()).getName() - .compareTo(((IDiagramUIModel) o2.getUserObject()).getName()); - } else { - return 0; - } + @Override + public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) { + String arg1 = ""; + String arg2 = ""; + + if (o1 == null) return 0; + if (o2 == null) return 0; + + if (o1.getUserObject() instanceof IDiagramUIModel) { + if (o2.getUserObject() instanceof IDiagramUIModel) { + return ((IDiagramUIModel) o1.getUserObject()) + .getName() + .compareTo(((IDiagramUIModel) o2.getUserObject()).getName()); + } else { + return 0; } - - if (o1.getUserObject() instanceof IModelElement) { - if (o2.getUserObject() instanceof IModelElement) { - IModelElement element1 = (IModelElement) o1.getUserObject(); - IModelElement element2 = (IModelElement) o2.getUserObject(); - - if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE) - && element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE) - && element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL) - && element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE)) { - return -1; - } else if (element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE)) { - return 1; - } - - if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL) - && element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL)) { - return -1; - } else if (element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL)) { - return 1; - } - - if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_CLASS) - && element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_CLASS)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_CLASS)) { - return -1; - } else if (element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_CLASS)) { - return 1; - } - - if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION) - && element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION)) { - return -1; - } else if (element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION)) { - return 1; - } - - if (element1.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET) - && element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET)) { - return -1; - } else if (element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET)) { - return 1; - } - - if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION) - && element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION)) { - return -1; - } else if (element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION)) { - return 1; - } - - if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS) - && element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS)) { - return -1; - } else if (element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS)) { - return 1; - } - - if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_DATA_TYPE) - && element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_DATA_TYPE)) { - arg1 = element1.getName(); - arg2 = element2.getName(); - } else if (element1.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_DATA_TYPE)) { - return -1; - } else if (element2.getModelType() - .contentEquals(IModelElementFactory.MODEL_TYPE_DATA_TYPE)) { - return 1; - } - - } + } + + if (o1.getUserObject() instanceof IModelElement) { + if (o2.getUserObject() instanceof IModelElement) { + IModelElement element1 = (IModelElement) o1.getUserObject(); + IModelElement element2 = (IModelElement) o2.getUserObject(); + + if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE) + && element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE) + && element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_MODEL) + && element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE)) { + return -1; + } else if (element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_PACKAGE)) { + return 1; + } + + if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL) + && element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_MODEL)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_MODEL)) { + return -1; + } else if (element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_MODEL)) { + return 1; + } + + if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_CLASS) + && element2.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_CLASS)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_CLASS)) { + return -1; + } else if (element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_CLASS)) { + return 1; + } + + if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION) + && element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION)) { + return -1; + } else if (element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION)) { + return 1; + } + + if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET) + && element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET)) { + return -1; + } else if (element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET)) { + return 1; + } + + if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION) + && element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION)) { + return -1; + } else if (element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_GENERALIZATION)) { + return 1; + } + + if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS) + && element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS)) { + return -1; + } else if (element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS)) { + return 1; + } + + if (element1.getModelType().contentEquals(IModelElementFactory.MODEL_TYPE_DATA_TYPE) + && element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_DATA_TYPE)) { + arg1 = element1.getName(); + arg2 = element2.getName(); + } else if (element1 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_DATA_TYPE)) { + return -1; + } else if (element2 + .getModelType() + .contentEquals(IModelElementFactory.MODEL_TYPE_DATA_TYPE)) { + return 1; + } } + } - if (arg1 == null) - arg1 = ""; - if (arg2 == null) - arg2 = ""; - - return arg1.compareTo(arg2); - } + if (arg1 == null) arg1 = ""; + if (arg2 == null) arg2 = ""; + return arg1.compareTo(arg2); + } }; - - } + } + } } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/NameUtil.java b/src/main/java/it/unibz/inf/ontouml/vp/views/NameUtil.java deleted file mode 100644 index 8ed9134e..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/NameUtil.java +++ /dev/null @@ -1,81 +0,0 @@ -package it.unibz.inf.ontouml.vp.views; - -import com.vp.plugin.diagram.IDiagramUIModel; -import com.vp.plugin.model.*; - -public class NameUtil { - - public static String getDisplayName(Object obj) { - if (obj == null) - return ""; - - if(obj instanceof String) - return obj.toString(); - - if(obj instanceof IDiagramUIModel) { - IDiagramUIModel diagram = (IDiagramUIModel) obj; - - return diagram.getName() != null ? diagram.getName(): "Diagram"; - } - - if (obj instanceof IAttribute) { - IAttribute attribute = (IAttribute) obj; - - String attributeName = attribute.getName() != null ? attribute.getName() : ""; - - String attributeType = ""; - if (attribute.getType() != null) - attributeType = attribute.getTypeAsString(); - - return attributeName + " : " + attributeType; - } - - if (obj instanceof IAssociation) { - IAssociation association = (IAssociation) obj; - String assocName = ""; - - if (association.getName() != null && !association.getName().equals("")) - assocName = association.getName() + " "; - - String nameFrom = association.getFrom() == null ? "" : association.getFrom().getName(); - String nameTo = association.getTo() == null ? "" : association.getTo().getName(); - - return assocName + "(" + nameFrom + " -> " + nameTo + ")"; - } - - if (obj instanceof IAssociationEnd) { - IAssociationEnd assocEnd = (IAssociationEnd) obj; - - String endName = assocEnd.getName() != null ? assocEnd.getName() : ""; - String typeName = assocEnd.getType() != null ? assocEnd.getTypeAsString() : ""; - - return endName + " : " + typeName; - } - - if (obj instanceof IGeneralization) { - IGeneralization generalization = (IGeneralization) obj; - - String childTypeName = generalization.getTo() != null ? generalization.getTo().getName() : ""; - String parentTypeName = generalization.getFrom() != null ? generalization.getFrom().getName() : ""; - - return "(" + childTypeName + " -> " + parentTypeName + ")"; - } - - if (obj instanceof IAssociationClass) { - IAssociationClass assocClass = (IAssociationClass) obj; - - String nameFrom = assocClass.getFrom() != null ? assocClass.getFrom().getName() : ""; - String nameTo = assocClass.getTo() != null ? assocClass.getTo().getName() : ""; - - return "(" + nameFrom + " -> " + nameTo + ")"; - - } - - if( obj instanceof IModelElement) { - IModelElement element = (IModelElement) obj; - return element.getName() != null ? element.getName() : "ModelElement " + element.getId(); - } - - return "Element"; - } -} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/ProgressPanel.java b/src/main/java/it/unibz/inf/ontouml/vp/views/ProgressPanel.java index f2349a4c..b3ba5636 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/ProgressPanel.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/ProgressPanel.java @@ -1,62 +1,60 @@ package it.unibz.inf.ontouml.vp.views; -import it.unibz.inf.ontouml.vp.utils.ServerRequest; -import it.unibz.inf.ontouml.vp.utils.ViewUtils; - +import com.vp.plugin.view.IDialog; +import it.unibz.inf.ontouml.vp.model.ServerRequest; +import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; - import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; -import com.vp.plugin.view.IDialog; - public class ProgressPanel extends JPanel { - private static final long serialVersionUID = 1L; - - private JLabel label; - private JProgressBar progressBar; - private JButton btnCancel; - private IDialog _dialog; - - public ProgressPanel(String text) { - setSize(new Dimension(200, 100)); - - label = new JLabel(); - label.setText(text); - - progressBar = new JProgressBar(); - progressBar.setIndeterminate(true); - - GridBagConstraints constraints = new GridBagConstraints(); - constraints.anchor = GridBagConstraints.CENTER; - - add(label, constraints); - add(progressBar, constraints); - } - - public ProgressPanel(ServerRequest request) { - this("Contacting Server..."); - - btnCancel = new JButton("Cancel"); - btnCancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - request.doStop(); - _dialog.close(); - ViewUtils.cleanAndShowMessage("Request cancelled by the user."); - } - }); - - add(btnCancel); - } - - public void setContainerDialog(IDialog dialog) { - this._dialog = dialog; - } -} \ No newline at end of file + private static final long serialVersionUID = 1L; + + private JLabel label; + private JProgressBar progressBar; + private JButton btnCancel; + private IDialog _dialog; + + public ProgressPanel(String text) { + setSize(new Dimension(200, 100)); + + label = new JLabel(); + label.setText(text); + + progressBar = new JProgressBar(); + progressBar.setIndeterminate(true); + + GridBagConstraints constraints = new GridBagConstraints(); + constraints.anchor = GridBagConstraints.CENTER; + + add(label, constraints); + add(progressBar, constraints); + } + + public ProgressPanel(ServerRequest request) { + this("Contacting Server..."); + + btnCancel = new JButton("Cancel"); + btnCancel.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + request.doStop(); + _dialog.close(); + ViewManagerUtils.cleanAndShowMessage("Request cancelled by the user."); + } + }); + + add(btnCancel); + } + + public void setContainerDialog(IDialog dialog) { + this._dialog = dialog; + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/SelectMultipleOptionsDialog.java b/src/main/java/it/unibz/inf/ontouml/vp/views/SelectMultipleOptionsDialog.java deleted file mode 100644 index 46536a74..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/SelectMultipleOptionsDialog.java +++ /dev/null @@ -1,202 +0,0 @@ -package it.unibz.inf.ontouml.vp.views; - -import java.awt.Component; -import java.awt.FlowLayout; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.border.EmptyBorder; - -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; - -import it.unibz.inf.ontouml.vp.utils.Configurations; -import it.unibz.inf.ontouml.vp.utils.StereotypeUtils; - -public class SelectMultipleOptionsDialog implements IDialogHandler { - - private IDialog _dialog; - // private Component _component; - private JPanel _selectionsPane; - private boolean cancelledExit = true; - private String initialSelecteion; - - public SelectMultipleOptionsDialog(String selectedValues) { - super(); - - this.initialSelecteion = selectedValues; - this._selectionsPane = new JPanel(); - this.setSelectedValues(selectedValues); - this._selectionsPane.setBorder(new EmptyBorder(7, 0, 0, 0)); - } - - @Override - public Component getComponent() { - final JLabel line = new JLabel("Select the possible ontological natures of the type's instances."); - final JButton cancelButton = new JButton("Cancel"); - final JButton applyButton = new JButton("Apply"); - - applyButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - cancelledExit = false; - _dialog.close(); - } - }); - - cancelButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - cancelledExit = true; - _dialog.close(); - } - }); - - // JPanel panel = new JPanel(); - JPanel panel = new JPanel(); - - panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS)); - - panel.add(line); - panel.add(this._selectionsPane); - - JPanel buttonsPanel = new JPanel(); - buttonsPanel.setLayout(new FlowLayout()); - buttonsPanel.add(applyButton); - buttonsPanel.add(cancelButton); - panel.add(buttonsPanel); - - line.setAlignmentX(Component.LEFT_ALIGNMENT); - this._selectionsPane.setAlignmentX(Component.LEFT_ALIGNMENT); - buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT); - - // this._component = panel; - - return panel; - } - - @Override - public void prepare(IDialog dialog) { - this._dialog = dialog; - dialog.setTitle("Restrict allowed natures"); - dialog.pack(); - } - - @Override - public boolean canClosed() { - return true; - } - - @Override - public void shown() {} - - public String getSelectedValues() { - if(this.cancelledExit) { - return this.initialSelecteion; - } - - final StringBuilder selectedValues = new StringBuilder(""); - final Component[] checkBoxes = this._selectionsPane.getComponents(); - - for (int i = 0; checkBoxes != null && i < checkBoxes.length; i++) { - if(checkBoxes[i] instanceof JCheckBox) { - final JCheckBox checkBox = (JCheckBox) checkBoxes[i]; - if(checkBox.isSelected()) { - selectedValues.append(selectedValues.length() == 0 ? - checkBox.getText() : " " + checkBox.getText()); - } - } - } - - return selectedValues.toString(); - } - - public void setSelectedValues(String selectedValuesString) { - final List selectedList = - Arrays.asList(selectedValuesString.split("\\s+")); - final List restrictedNatures = StereotypeUtils.getRestrictionsList(); - Collections.sort(restrictedNatures); - final boolean isSmartModelingEnabled = Configurations.getInstance() - .getProjectConfigurations().isSmartModellingEnabled(); - - this._selectionsPane.setLayout(new GridLayout(4,3)); - - JCheckBox checkBox; - - // Line 1, Column 1 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_COLLECTIVE); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_COLLECTIVE)); - // Line 1, Column 2 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_MODE); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_MODE)); - // Line 1, Column 3 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_ABSTRACT); - this._selectionsPane.add(checkBox); - if(isSmartModelingEnabled) { - checkBox.setSelected(false); - checkBox.setEnabled(false); - } else { - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_ABSTRACT)); - } - - // Line 2, Column 1 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_FUNCTIONAL_COMPLEX); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_FUNCTIONAL_COMPLEX)); - // Line 2, Column 2 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_QUALITY); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_QUALITY)); - // Line 2, Column 3 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_EVENT); - this._selectionsPane.add(checkBox); - if(isSmartModelingEnabled) { - checkBox.setSelected(false); - checkBox.setEnabled(false); - } else { - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_EVENT)); - } - - // Line 3, Column 1 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_QUANTITY); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_QUANTITY)); - // Line 3, Column 2 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_RELATOR); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_RELATOR)); - // Line 3, Column 3 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_SITUATION); - this._selectionsPane.add(checkBox); - if(isSmartModelingEnabled) { - checkBox.setSelected(false); - checkBox.setEnabled(false); - } else { - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_SITUATION)); - } - - // Line 4, Column 1 - this._selectionsPane.add(new JLabel()); - // Line 4, Column 2 - this._selectionsPane.add(new JLabel()); - // Line 4, Column 3 - checkBox = new JCheckBox(StereotypeUtils.RESTRICTED_TO_TYPE); - this._selectionsPane.add(checkBox); - if(isSmartModelingEnabled) { - checkBox.setSelected(false); - checkBox.setEnabled(false); - } else { - checkBox.setSelected(selectedList.contains(StereotypeUtils.RESTRICTED_TO_TYPE)); - } - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/SelectRestrictionsView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/SelectRestrictionsView.java new file mode 100644 index 00000000..a676740a --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/SelectRestrictionsView.java @@ -0,0 +1,160 @@ +package it.unibz.inf.ontouml.vp.views; + +import com.vp.plugin.view.IDialog; +import com.vp.plugin.view.IDialogHandler; +import it.unibz.inf.ontouml.vp.model.Configurations; +import it.unibz.inf.ontouml.vp.model.uml.Class; +import it.unibz.inf.ontouml.vp.utils.RestrictedTo; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.util.List; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.border.EmptyBorder; + +public class SelectRestrictionsView implements IDialogHandler { + + private IDialog dialog; + private JPanel selectionPanel; + + private boolean cancelledExit = true; + private String restrictedTo; + private List restrictedToList; + private List selectableRestrictedTo; + + public SelectRestrictionsView(String restrictedTo, List selectableRestrictedTo) { + super(); + + this.restrictedTo = restrictedTo; + this.restrictedToList = Class.getRestrictedToList(restrictedTo); + this.selectableRestrictedTo = selectableRestrictedTo; + + this.selectionPanel = new JPanel(); + this.selectionPanel.setBorder(new EmptyBorder(7, 0, 0, 0)); + + this.createDialogContents(); + } + + @Override + public Component getComponent() { + final JLabel line = + new JLabel("Select the possible ontological natures of the type's instances."); + final JButton cancelButton = new JButton("Cancel"); + final JButton applyButton = new JButton("Apply"); + + applyButton.addActionListener( + e -> { + cancelledExit = false; + dialog.close(); + }); + + cancelButton.addActionListener( + e -> { + cancelledExit = true; + dialog.close(); + }); + + JPanel panel = new JPanel(); + + panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); + + panel.add(line); + panel.add(this.selectionPanel); + + JPanel buttonsPanel = new JPanel(); + buttonsPanel.setLayout(new FlowLayout()); + buttonsPanel.add(applyButton); + buttonsPanel.add(cancelButton); + panel.add(buttonsPanel); + + line.setAlignmentX(Component.LEFT_ALIGNMENT); + this.selectionPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + buttonsPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + + return panel; + } + + @Override + public void prepare(IDialog dialog) { + this.dialog = dialog; + dialog.setTitle("Restrict allowed natures"); + dialog.pack(); + } + + @Override + public boolean canClosed() { + return true; + } + + @Override + public void shown() {} + + public String getSelectedValues() { + if (this.cancelledExit) { + return this.restrictedTo; + } + + final StringBuilder selectedValues = new StringBuilder(); + final Component[] checkBoxes = this.selectionPanel.getComponents(); + + for (int i = 0; checkBoxes != null && i < checkBoxes.length; i++) { + if (checkBoxes[i] instanceof JCheckBox) { + final JCheckBox checkBox = (JCheckBox) checkBoxes[i]; + if (checkBox.isSelected()) { + selectedValues.append( + selectedValues.length() == 0 ? checkBox.getText() : " " + checkBox.getText()); + } + } + } + + return selectedValues.toString(); + } + + private void addCheckbox(String restrictedTo) { + JCheckBox checkBox = new JCheckBox(restrictedTo); + selectionPanel.add(checkBox); + + checkBox.setSelected(restrictedToList.contains(restrictedTo)); + + final boolean isSmartModelingEnabled = + Configurations.getInstance().getProjectConfigurations().isSmartModellingEnabled(); + + if (isSmartModelingEnabled) checkBox.setEnabled(selectableRestrictedTo.contains(restrictedTo)); + } + + public void createDialogContents() { + this.selectionPanel.setLayout(new GridLayout(4, 3)); + + // Line 1, Column 1 + addCheckbox(RestrictedTo.COLLECTIVE); + // Line 1, Column 2 + addCheckbox(RestrictedTo.INTRINSIC_MODE); + // Line 1, Column 3 + addCheckbox(RestrictedTo.ABSTRACT); + + // Line 2, Column 1 + addCheckbox(RestrictedTo.FUNCTIONAL_COMPLEX); + // Line 2, Column 2 + addCheckbox(RestrictedTo.EXTRINSIC_MODE); + // Line 2, Column 3 + addCheckbox(RestrictedTo.EVENT); + + // Line 3, Column 1 + addCheckbox(RestrictedTo.QUANTITY); + // Line 3, Column 2 + addCheckbox(RestrictedTo.QUALITY); + // Line 3, Column 3 + addCheckbox(RestrictedTo.SITUATION); + + // Line 4, Column 1 (empty) + this.selectionPanel.add(new JLabel()); + // Line 4, Column 2 + addCheckbox(RestrictedTo.RELATOR); + // Line 4, Column 3 + addCheckbox(RestrictedTo.TYPE); + } +} diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderDialog.java b/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderDialog.java deleted file mode 100644 index ea5db111..00000000 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderDialog.java +++ /dev/null @@ -1,152 +0,0 @@ -package it.unibz.inf.ontouml.vp.views; - -import java.awt.Component; -import java.awt.FlowLayout; -import java.awt.Image; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.BoxLayout; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.border.EmptyBorder; - -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; - -import it.unibz.inf.ontouml.vp.utils.ViewUtils; - -public class SetOrderDialog implements IDialogHandler { - - private IDialog _dialog; - // private Component _component; - private boolean cancelledExit = true; - private String currentString = ""; - private JTextField _inputField; - - public SetOrderDialog(String current) { - super(); - this.currentString = current; - } - - @Override - public Component getComponent() { - final JLabel line = new JLabel("Set the type order (\"*\" for orderless)"); - line.setBorder(new EmptyBorder(0, 7, 0, 0)); - - _inputField = new JTextField(this.currentString); - _inputField.setColumns(10); - - ImageIcon addIcon = new ImageIcon(ViewUtils.getFilePath(ViewUtils.ADD_LOGO)); - addIcon.setImage(addIcon.getImage().getScaledInstance(17, 17, Image.SCALE_SMOOTH)); - ImageIcon subtractIcon = new ImageIcon(ViewUtils.getFilePath(ViewUtils.SUBTRACT_LOGO)); - subtractIcon.setImage(subtractIcon.getImage().getScaledInstance(17, 17, Image.SCALE_SMOOTH)); - ImageIcon asteriskIcon = new ImageIcon(ViewUtils.getFilePath(ViewUtils.ASTERISK_LOGO)); - asteriskIcon.setImage(asteriskIcon.getImage().getScaledInstance(17, 17, Image.SCALE_SMOOTH)); - - final JButton addButton = new JButton(addIcon); - final JButton subtractButton = new JButton(subtractIcon); - final JButton asteriskButton = new JButton(asteriskIcon); - - addButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - try { - int input = Integer.parseInt(_inputField.getText()) + 1; - _inputField.setText(input < 2 ? "2" : input+""); - } catch (NumberFormatException e1) { - _inputField.setText("2"); - } - } - }); - subtractButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - try { - int input = Integer.parseInt(_inputField.getText()) - 1; - _inputField.setText(input < 2 ? "2" : input+""); - } catch (NumberFormatException e2) { - _inputField.setText("2"); - } - } - }); - asteriskButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - _inputField.setText("*"); - } - }); - - addButton.setSize(5, 5); - subtractButton.setSize(5, 5); - asteriskButton.setSize(5, 5); - - final JButton cancelButton = new JButton("Cancel"); - final JButton applyButton = new JButton("Apply"); - - applyButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - cancelledExit = false; - _dialog.close(); - } - }); - - cancelButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - cancelledExit = true; - _dialog.close(); - } - }); - - JPanel panel = new JPanel(); - - panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS)); - panel.add(line); - - JPanel middlePanel = new JPanel(); - middlePanel.setLayout(new FlowLayout()); - middlePanel.setAlignmentX(FlowLayout.LEFT); - middlePanel.add(_inputField); - middlePanel.add(addButton); - middlePanel.add(subtractButton); - middlePanel.add(asteriskButton); - panel.add(middlePanel); - - JPanel bottomPanel = new JPanel(); - bottomPanel.setLayout(new FlowLayout()); - bottomPanel.setAlignmentX(FlowLayout.RIGHT); - bottomPanel.add(applyButton); - bottomPanel.add(cancelButton); - panel.add(bottomPanel); - - line.setAlignmentX(Component.LEFT_ALIGNMENT); - bottomPanel.setAlignmentX(Component.LEFT_ALIGNMENT); - - // this._component = panel; - - return panel; - } - - @Override - public void prepare(IDialog dialog) { - this._dialog = dialog; - dialog.setTitle("Set type order"); - dialog.pack(); - } - - @Override - public boolean canClosed() { - return true; - } - - @Override - public void shown() {} - - public String getOrder() { - return this.cancelledExit ? this.currentString : this._inputField.getText(); - } - -} \ No newline at end of file diff --git a/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderView.java new file mode 100644 index 00000000..cf5e0e65 --- /dev/null +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderView.java @@ -0,0 +1,182 @@ +package it.unibz.inf.ontouml.vp.views; + +import com.vp.plugin.ApplicationManager; +import com.vp.plugin.view.IDialog; +import com.vp.plugin.view.IDialogHandler; +import it.unibz.inf.ontouml.vp.OntoUMLPlugin; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.Image; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.nio.file.Paths; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.border.EmptyBorder; + +public class SetOrderView implements IDialogHandler { + + private static final String ADD_LOGO = "add"; + private static final String ASTERISK_LOGO = "asterisk"; + private static final String SUBTRACT_LOGO = "subtract"; + private static final String ADD_LOGO_FILENAME = "add.png"; + private static final String ASTERISK_LOGO_FILENAME = "asterisk.png"; + private static final String SUBTRACT_LOGO_FILENAME = "subtract.png"; + + private IDialog _dialog; + private boolean cancelledExit = true; + private String currentString = ""; + private JTextField _inputField; + + public SetOrderView(String current) { + super(); + this.currentString = current; + } + + @Override + public Component getComponent() { + final JLabel line = new JLabel("Set the type order (\"*\" for orderless)"); + line.setBorder(new EmptyBorder(0, 7, 0, 0)); + + _inputField = new JTextField(this.currentString); + _inputField.setColumns(10); + + ImageIcon addIcon = new ImageIcon(getFilePath(ADD_LOGO)); + addIcon.setImage(addIcon.getImage().getScaledInstance(17, 17, Image.SCALE_SMOOTH)); + ImageIcon subtractIcon = new ImageIcon(getFilePath(SUBTRACT_LOGO)); + subtractIcon.setImage(subtractIcon.getImage().getScaledInstance(17, 17, Image.SCALE_SMOOTH)); + ImageIcon asteriskIcon = new ImageIcon(getFilePath(ASTERISK_LOGO)); + asteriskIcon.setImage(asteriskIcon.getImage().getScaledInstance(17, 17, Image.SCALE_SMOOTH)); + + final JButton addButton = new JButton(addIcon); + final JButton subtractButton = new JButton(subtractIcon); + final JButton asteriskButton = new JButton(asteriskIcon); + + addButton.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + int input = Integer.parseInt(_inputField.getText()) + 1; + _inputField.setText(input < 2 ? "2" : input + ""); + } catch (NumberFormatException e1) { + _inputField.setText("2"); + } + } + }); + subtractButton.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + int input = Integer.parseInt(_inputField.getText()) - 1; + _inputField.setText(input < 2 ? "2" : input + ""); + } catch (NumberFormatException e2) { + _inputField.setText("2"); + } + } + }); + asteriskButton.addActionListener( + new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + _inputField.setText("*"); + } + }); + + addButton.setSize(5, 5); + subtractButton.setSize(5, 5); + asteriskButton.setSize(5, 5); + + final JButton cancelButton = new JButton("Cancel"); + final JButton applyButton = new JButton("Apply"); + + applyButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + cancelledExit = false; + _dialog.close(); + } + }); + + cancelButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + cancelledExit = true; + _dialog.close(); + } + }); + + JPanel panel = new JPanel(); + + panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); + panel.add(line); + + JPanel middlePanel = new JPanel(); + middlePanel.setLayout(new FlowLayout()); + middlePanel.setAlignmentX(FlowLayout.LEFT); + middlePanel.add(_inputField); + middlePanel.add(addButton); + middlePanel.add(subtractButton); + middlePanel.add(asteriskButton); + panel.add(middlePanel); + + JPanel bottomPanel = new JPanel(); + bottomPanel.setLayout(new FlowLayout()); + bottomPanel.setAlignmentX(FlowLayout.RIGHT); + bottomPanel.add(applyButton); + bottomPanel.add(cancelButton); + panel.add(bottomPanel); + + line.setAlignmentX(Component.LEFT_ALIGNMENT); + bottomPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + + return panel; + } + + @Override + public void prepare(IDialog dialog) { + this._dialog = dialog; + dialog.setTitle("Set type order"); + dialog.pack(); + } + + @Override + public boolean canClosed() { + return true; + } + + @Override + public void shown() {} + + public String getOrder() { + return this.cancelledExit ? this.currentString : this._inputField.getText(); + } + + private static String getFilePath(String imageName) { + final File pluginDir = + ApplicationManager.instance().getPluginInfo(OntoUMLPlugin.PLUGIN_ID).getPluginDir(); + + switch (imageName) { + case ADD_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", ADD_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case ASTERISK_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", ASTERISK_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + case SUBTRACT_LOGO: + return Paths.get(pluginDir.getAbsolutePath(), "icons", SUBTRACT_LOGO_FILENAME) + .toFile() + .getAbsolutePath(); + default: + return null; + } + } +} diff --git a/src/main/resources/association_constraints.json b/src/main/resources/association_constraints.json index c555206d..ced717b5 100644 --- a/src/main/resources/association_constraints.json +++ b/src/main/resources/association_constraints.json @@ -14,11 +14,12 @@ "kind:phaseMixin": ["comparative","material","componentOf","memberOf","historicalDependence"], "kind:historicalRole": ["comparative","material","componentOf","memberOf","historicalDependence"], "kind:historicalRoleMixin": ["comparative","material","componentOf","memberOf","historicalDependence"], - "kind:event": [], + "kind:event": ["participation", "creation", "termination"], "kind:situation": [], "kind:type": ["instantiation"], "kind:enumeration": [], "kind:datatype": [], + "kind:abstract": [], "quantity:kind": ["comparative", "material", "historicalDependence" ], "quantity:quantity": ["comparative", "material", "subQuantityOf", "historicalDependence"], "quantity:collective": ["comparative", "material", "historicalDependence"], @@ -34,11 +35,12 @@ "quantity:phaseMixin": ["comparative", "material", "subQuantityOf", "historicalDependence"], "quantity:historicalRole": ["comparative", "material", "subQuantityOf", "historicalDependence"], "quantity:historicalRoleMixin": ["comparative", "material", "subQuantityOf", "historicalDependence"], - "quantity:event": [], + "quantity:event": ["participation", "creation", "termination"], "quantity:situation": [], "quantity:type": ["instantiation"], "quantity:enumeration": [], "quantity:datatype": [], + "quantity:abstract": [], "collective:kind": ["comparative", "material", "historicalDependence"], "collective:quantity": ["comparative", "material", "historicalDependence"], "collective:collective": ["comparative", "material", "memberOf", "subCollectionOf", "historicalDependence"], @@ -54,11 +56,12 @@ "collective:phaseMixin": ["comparative", "material", "memberOf", "subCollectionOf", "historicalDependence"], "collective:historicalRole": ["comparative", "material", "memberOf", "subCollectionOf", "historicalDependence"], "collective:historicalRoleMixin": ["comparative", "material", "memberOf", "subCollectionOf", "historicalDependence"], - "collective:event": [], + "collective:event": ["participation", "creation", "termination"], "collective:situation": [], "collective:type": ["instantiation"], "collective:enumeration": [], "collective:datatype": [], + "collective:abstract": [], "relator:kind": ["comparative", "material", "mediation", "historicalDependence"], "relator:quantity": ["comparative", "material", "mediation", "historicalDependence"], "relator:collective": ["comparative", "material", "mediation", "historicalDependence"], @@ -74,11 +77,12 @@ "relator:phaseMixin": ["comparative", "material", "mediation", "historicalDependence"], "relator:historicalRole": ["comparative", "material", "mediation", "historicalDependence"], "relator:historicalRoleMixin": ["comparative", "material", "mediation", "historicalDependence"], - "relator:event": ["material", "mediation"], + "relator:event": ["manifestation", "creation", "termination"], "relator:situation": [], - "relator:type": ["comparative", "material", "mediation", "historicalDependence", "instantiation"], - "relator:enumeration": ["historicalDependence"], - "relator:datatype": ["historicalDependence"], + "relator:type": ["instantiation"], + "relator:enumeration": [], + "relator:datatype": [], + "relator:abstract": [], "mode:kind": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], "mode:quantity": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], "mode:collective": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], @@ -94,11 +98,12 @@ "mode:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], "mode:historicalRole": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], "mode:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], - "mode:event": ["characterization", "externalDependence", "material"], + "mode:event": ["characterization", "manifestation", "creation", "termination"], "mode:situation": [], - "mode:type": ["characterization", "comparative", "externalDependence", "material", "instantiation"], + "mode:type": ["instantiation"], "mode:enumeration": [], "mode:datatype": [], + "mode:abstract": [], "quality:kind": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], "quality:quantity": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], "quality:collective": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], @@ -114,11 +119,12 @@ "quality:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], "quality:historicalRole": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], "quality:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "historicalDependence"], - "quality:event": ["characterization", "externalDependence", "material"], + "quality:event": ["characterization", "manifestation", "creation", "termination"], "quality:situation": [], - "quality:type": ["characterization", "comparative", "externalDependence", "material", "historicalDependence", "instantiation"], - "quality:enumeration": ["historicalDependence"], - "quality:datatype": ["historicalDependence"], + "quality:type": ["instantiation"], + "quality:enumeration": [], + "quality:datatype": [], + "quality:abstract": [], "subkind:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "subkind:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "subkind:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -134,10 +140,12 @@ "subkind:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "subkind:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "subkind:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], + "subkind:event": ["characterization", "participation", "creation", "termination", "manifestation"], "subkind:situation": [], - "subkind:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "subkind:type": ["instantiation"], "subkind:enumeration": [], "subkind:datatype": [], + "subkind:abstract": [], "role:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "role:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "role:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -153,11 +161,12 @@ "role:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "role:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "role:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], - "role:event": ["characterization", "externalDependence", "material", "mediation"], + "role:event": ["characterization", "participation", "creation", "termination", "manifestation"], "role:situation": [], - "role:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "role:type": ["instantiation"], "role:enumeration": [], "role:datatype": [], + "role:abstract": [], "phase:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "phase:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "phase:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -173,11 +182,12 @@ "phase:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "phase:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "phase:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], - "phase:event": ["characterization", "externalDependence", "material", "mediation"], + "phase:event": ["characterization", "participation", "creation", "termination", "manifestation"], "phase:situation": [], - "phase:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "phase:type": ["instantiation"], "phase:enumeration": [], "phase:datatype": [], + "phase:abstract": [], "category:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "category:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "category:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -193,11 +203,12 @@ "category:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "category:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "category:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], - "category:event": ["characterization", "externalDependence", "material", "mediation"], + "category:event": ["characterization", "participation", "creation", "termination", "manifestation"], "category:situation": [], - "category:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "category:type": ["instantiation"], "category:enumeration": [], "category:datatype": [], + "category:abstract": [], "mixin:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "mixin:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "mixin:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -213,11 +224,12 @@ "mixin:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "mixin:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "mixin:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], - "mixin:event": ["characterization", "externalDependence", "material", "mediation"], + "mixin:event": ["characterization", "participation", "creation", "termination", "manifestation"], "mixin:situation": [], - "mixin:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "mixin:type": ["instantiation"], "mixin:enumeration": [], "mixin:datatype": [], + "mixin:abstract": [], "roleMixin:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "roleMixin:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "roleMixin:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -233,11 +245,12 @@ "roleMixin:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "roleMixin:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "roleMixin:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], - "roleMixin:event": ["characterization", "externalDependence", "material", "mediation"], + "roleMixin:event": ["characterization", "participation", "creation", "termination", "manifestation"], "roleMixin:situation": [], - "roleMixin:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "roleMixin:type": ["instantiation"], "roleMixin:enumeration": [], "roleMixin:datatype": [], + "roleMixin:abstract": [], "phaseMixin:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "phaseMixin:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "phaseMixin:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -253,11 +266,12 @@ "phaseMixin:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "phaseMixin:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "phaseMixin:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], - "phaseMixin:event": ["characterization", "externalDependence", "material", "mediation"], + "phaseMixin:event": ["characterization", "participation", "creation", "termination", "manifestation"], "phaseMixin:situation": [], - "phaseMixin:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "phaseMixin:type": ["instantiation"], "phaseMixin:enumeration": [], "phaseMixin:datatype": [], + "phaseMixin:abstract": [], "historicalRole:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "historicalRole:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "historicalRole:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -273,11 +287,12 @@ "historicalRole:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "historicalRole:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "historicalRole:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], - "historicalRole:event": ["characterization", "externalDependence", "material", "mediation"], + "historicalRole:event": ["characterization", "participation", "creation", "termination", "manifestation"], "historicalRole:situation": [], - "historicalRole:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "historicalRole:type": ["instantiation"], "historicalRole:enumeration": [], "historicalRole:datatype": [], + "historicalRole:abstract": [], "historicalRoleMixin:kind": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "historicalDependence"], "historicalRoleMixin:quantity": ["characterization", "comparative", "externalDependence", "material", "mediation", "subQuantityOf", "historicalDependence"], "historicalRoleMixin:collective": ["characterization", "comparative", "externalDependence", "material", "mediation", "memberOf", "subCollectionOf", "historicalDependence"], @@ -293,31 +308,33 @@ "historicalRoleMixin:phaseMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "historicalRoleMixin:historicalRole": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], "historicalRoleMixin:historicalRoleMixin": ["characterization", "comparative", "externalDependence", "material", "mediation", "componentOf", "memberOf", "subCollectionOf", "subQuantityOf", "historicalDependence"], - "historicalRoleMixin:event": ["characterization", "externalDependence", "material", "mediation"], + "historicalRoleMixin:event": ["characterization", "participation", "creation", "termination", "manifestation"], "historicalRoleMixin:situation": [], - "historicalRoleMixin:type": ["characterization", "comparative", "externalDependence", "material", "mediation", "instantiation"], + "historicalRoleMixin:type": ["instantiation"], "historicalRoleMixin:enumeration": [], "historicalRoleMixin:datatype": [], - "event:kind": ["participation","creation","termination"], - "event:quantity": ["participation","creation","termination"], - "event:collective": ["participation","creation","termination"], - "event:relator": ["creation","termination","manifestation"], - "event:mode": ["creation","termination","manifestation"], - "event:quality": ["creation","termination","manifestation"], - "event:subkind": ["participation","creation","termination","manifestation"], - "event:role": ["participation","creation","termination","manifestation"], - "event:phase": ["participation","creation","termination","manifestation"], - "event:category": ["participation","creation","termination","manifestation"], - "event:mixin": ["participation","creation","termination","manifestation"], - "event:roleMixin": ["participation","creation","termination","manifestation"], - "event:phaseMixin": ["participation","creation","termination","manifestation"], - "event:historicalRole": ["participation","creation","termination","manifestation"], - "event:historicalRoleMixin": ["participation","creation","termination","manifestation"], + "historicalRoleMixin:abstract": [], + "event:kind": [], + "event:quantity": [], + "event:collective": [], + "event:relator": [], + "event:mode": [], + "event:quality": [], + "event:subkind": [], + "event:role": [], + "event:phase": [], + "event:category": [], + "event:mixin": [], + "event:roleMixin": [], + "event:phaseMixin": [], + "event:historicalRole": [], + "event:historicalRoleMixin": [], "event:event": ["historicalDependence","participational"], "event:situation": ["bringsAbout"], "event:type": ["instantiation"], "event:enumeration": [], "event:datatype": [], + "event:abstract": [], "situation:kind": [], "situation:quantity": [], "situation:collective": [], @@ -338,6 +355,7 @@ "situation:type": ["instantiation"], "situation:enumeration": [], "situation:datatype": [], + "situation:abstract": [], "type:kind": [], "type:quantity": [], "type:collective": [], @@ -358,6 +376,7 @@ "type:type": ["instantiation"], "type:enumeration": [], "type:datatype": [], + "type:abstract": [], "enumeration:kind": [], "enumeration:quantity": [], "enumeration:collective": [], @@ -378,6 +397,7 @@ "enumeration:type": [], "enumeration:enumeration": [], "enumeration:datatype": [], + "enumeration:abstract": [], "datatype:kind": [], "datatype:quantity": [], "datatype:collective": [], @@ -397,5 +417,27 @@ "datatype:situation": [], "datatype:type": [], "datatype:enumeration": [], - "datatype:datatype": [] + "datatype:datatype": [], + "datatype:abstract": [], + "abstract:kind": [], + "abstract:quantity": [], + "abstract:collective": [], + "abstract:relator": [], + "abstract:mode": [], + "abstract:quality": [], + "abstract:subkind": [], + "abstract:role": [], + "abstract:phase": [], + "abstract:category": [], + "abstract:mixin": [], + "abstract:roleMixin": [], + "abstract:phaseMixin": [], + "abstract:historicalRole": [], + "abstract:historicalRoleMixin": [], + "abstract:event": [], + "abstract:situation": [], + "abstract:type": [], + "abstract:enumeration": [], + "abstract:datatype": [], + "abstract:abstract": [] } \ No newline at end of file diff --git a/src/main/resources/association_constraints_nature.json b/src/main/resources/association_constraints_nature.json new file mode 100644 index 00000000..7986bccd --- /dev/null +++ b/src/main/resources/association_constraints_nature.json @@ -0,0 +1,123 @@ +{ + "functional-complex:functional-complex": ["comparative", "componentOf", "historicalDependence", "material"], + "functional-complex:collective": ["comparative", "historicalDependence", "material", "memberOf"], + "functional-complex:quantity": ["comparative", "historicalDependence", "material"], + "functional-complex:relator": ["comparative", "historicalDependence", "material"], + "functional-complex:intrinsic-mode": ["comparative", "historicalDependence", "material"], + "functional-complex:extrinsic-mode": ["comparative", "historicalDependence", "material"], + "functional-complex:quality": ["comparative", "historicalDependence", "material"], + "functional-complex:event": ["comparative", "creation", "participation", "termination"], + "functional-complex:situation": ["comparative"], + "functional-complex:type": ["instantiation"], + "functional-complex:abstract": [], + "collective:functional-complex": ["comparative", "historicalDependence", "material"], + "collective:collective": ["comparative", "historicalDependence", "material", "memberOf", "subCollectionOf"], + "collective:quantity": ["comparative", "historicalDependence", "material"], + "collective:relator": ["comparative", "historicalDependence", "material"], + "collective:intrinsic-mode": ["comparative", "historicalDependence", "material"], + "collective:extrinsic-mode": ["comparative", "historicalDependence", "material"], + "collective:quality": ["comparative", "historicalDependence", "material"], + "collective:event": ["comparative", "creation", "participation", "termination"], + "collective:situation": ["comparative"], + "collective:type": ["instantiation"], + "collective:abstract": [], + "quantity:functional-complex": ["comparative", "historicalDependence", "material"], + "quantity:collective": ["comparative", "historicalDependence", "material"], + "quantity:quantity": ["comparative", "historicalDependence", "material", "subQuantityOf"], + "quantity:relator": ["comparative", "historicalDependence", "material"], + "quantity:intrinsic-mode": ["comparative", "historicalDependence", "material"], + "quantity:extrinsic-mode": ["comparative", "historicalDependence", "material"], + "quantity:quality": ["comparative", "historicalDependence", "material"], + "quantity:event": ["comparative", "creation", "participation", "termination"], + "quantity:situation": ["comparative"], + "quantity:type": ["instantiation"], + "quantity:abstract": [], + "relator:functional-complex": ["comparative", "historicalDependence", "material", "mediation"], + "relator:collective": ["comparative", "historicalDependence", "material", "mediation"], + "relator:quantity": ["comparative", "historicalDependence", "material", "mediation"], + "relator:relator": ["comparative", "historicalDependence", "material", "mediation", "partOf"], + "relator:intrinsic-mode": ["comparative", "historicalDependence", "material", "mediation"], + "relator:extrinsic-mode": ["comparative", "historicalDependence", "material", "mediation"], + "relator:quality": ["comparative", "historicalDependence", "material", "mediation"], + "relator:event": ["comparative", "creation", "manifestation", "termination"], + "relator:situation": ["comparative"], + "relator:type": ["instantiation"], + "relator:abstract": [], + "intrinsic-mode:functional-complex": ["characterization", "comparative", "historicalDependence", "material"], + "intrinsic-mode:collective": ["characterization", "comparative", "historicalDependence", "material"], + "intrinsic-mode:quantity": ["characterization", "comparative", "historicalDependence", "material"], + "intrinsic-mode:relator": ["characterization", "comparative", "historicalDependence", "material", "partOf"], + "intrinsic-mode:intrinsic-mode": ["characterization", "comparative", "historicalDependence", "material"], + "intrinsic-mode:extrinsic-mode": ["characterization", "comparative", "historicalDependence", "material", "partOf"], + "intrinsic-mode:quality": ["characterization", "comparative", "historicalDependence", "material"], + "intrinsic-mode:event": ["characterization", "comparative", "creation", "manifestation", "termination"], + "intrinsic-mode:situation": ["characterization", "comparative"], + "intrinsic-mode:type": ["instantiation"], + "intrinsic-mode:abstract": [], + "extrinsic-mode:functional-complex": ["characterization", "comparative", "externalDependence", "historicalDependence", "material"], + "extrinsic-mode:collective": ["characterization", "comparative", "externalDependence", "historicalDependence", "material"], + "extrinsic-mode:quantity": ["characterization", "comparative", "externalDependence", "historicalDependence", "material"], + "extrinsic-mode:relator": ["characterization", "comparative", "externalDependence", "historicalDependence", "material", "partOf"], + "extrinsic-mode:intrinsic-mode": ["characterization", "comparative", "externalDependence", "historicalDependence", "material"], + "extrinsic-mode:extrinsic-mode": ["characterization", "comparative", "externalDependence", "historicalDependence", "material", "partOf"], + "extrinsic-mode:quality": ["characterization", "comparative", "externalDependence", "historicalDependence", "material"], + "extrinsic-mode:event": ["characterization", "comparative", "creation", "manifestation", "termination"], + "extrinsic-mode:situation": ["characterization", "comparative"], + "extrinsic-mode:type": ["instantiation"], + "extrinsic-mode:abstract": [], + "quality:functional-complex": ["characterization", "comparative", "historicalDependence", "material"], + "quality:collective": ["characterization", "comparative", "historicalDependence", "material"], + "quality:quantity": ["characterization", "comparative", "historicalDependence", "material"], + "quality:relator": ["characterization", "comparative", "historicalDependence", "material", "partOf"], + "quality:intrinsic-mode": ["characterization", "comparative", "historicalDependence", "material"], + "quality:extrinsic-mode": ["characterization", "comparative", "historicalDependence", "material"], + "quality:quality": ["characterization", "comparative", "historicalDependence", "material", "partOf"], + "quality:event": ["characterization", "comparative", "creation", "manifestation", "termination"], + "quality:situation": ["characterization", "comparative"], + "quality:type": ["instantiation"], + "quality:abstract": [], + "event:functional-complex": ["comparative"], + "event:collective": ["comparative"], + "event:quantity": ["comparative"], + "event:relator": ["comparative"], + "event:intrinsic-mode": ["comparative"], + "event:extrinsic-mode": ["comparative"], + "event:quality": ["comparative"], + "event:event": ["comparative", "historicalDependence", "participational", "partOf"], + "event:situation": ["bringsAbout", "comparative"], + "event:type": ["instantiation"], + "event:abstract": [], + "situation:functional-complex": ["comparative"], + "situation:collective": ["comparative"], + "situation:quantity": ["comparative"], + "situation:relator": ["comparative"], + "situation:intrinsic-mode": ["comparative"], + "situation:extrinsic-mode": ["comparative"], + "situation:quality": ["comparative"], + "situation:event": ["comparative", "triggers"], + "situation:situation": ["comparative", "historicalDependence", "partOf"], + "situation:type": ["instantiation"], + "situation:abstract": [], + "type:functional-complex": [], + "type:collective": [], + "type:quantity": [], + "type:relator": [], + "type:intrinsic-mode": [], + "type:extrinsic-mode": [], + "type:quality": [], + "type:event": [], + "type:situation": [], + "type:type": ["instantiation"], + "type:abstract": [], + "abstract:functional-complex": [], + "abstract:collective": [], + "abstract:quantity": [], + "abstract:relator": [], + "abstract:intrinsic-mode": [], + "abstract:extrinsic-mode": [], + "abstract:quality": [], + "abstract:event": [], + "abstract:situation": [], + "abstract:type": ["instantiation"], + "abstract:abstract": [] +} \ No newline at end of file diff --git a/src/main/resources/generalization_constraints.json b/src/main/resources/generalization_constraints.json index 815543d8..2a0e8bda 100644 --- a/src/main/resources/generalization_constraints.json +++ b/src/main/resources/generalization_constraints.json @@ -17,9 +17,10 @@ "historicalRoleMixin": ["role","roleMixin","historicalRole","historicalRoleMixin"], "event": ["event"], "situation": ["situation"], - "type": ["role","phase","historicalRole","type"], + "type": ["type"], "enumeration": ["enumeration"], - "datatype": ["datatype"] + "datatype": ["datatype"], + "abstract": ["abstract","datatype","enumeration"] }, "allowedSuperClassesFor": { "kind": ["category","mixin"], @@ -29,18 +30,19 @@ "mode": ["category","mixin"], "quality": ["category","mixin"], "subkind": ["kind","quantity","collective","relator","mode","quality","subkind","category","mixin"], - "role": ["kind","quantity","collective","relator","mode","quality","subkind","role","phase","category","mixin","roleMixin","phaseMixin","historicalRole","historicalRoleMixin","type"], - "phase": ["kind","quantity","collective","relator","mode","quality","subkind","phase","category","mixin","phaseMixin","type"], + "role": ["kind","quantity","collective","relator","mode","quality","subkind","role","phase","category","mixin","roleMixin","phaseMixin","historicalRole","historicalRoleMixin"], + "phase": ["kind","quantity","collective","relator","mode","quality","subkind","phase","category","mixin","phaseMixin"], "category": ["category","mixin"], "mixin": ["category","mixin"], "roleMixin": ["category","mixin","roleMixin","phaseMixin","historicalRoleMixin"], "phaseMixin": ["category","mixin","phaseMixin"], - "historicalRole": ["kind","quantity","collective","relator","mode","quality","subkind","category","mixin","historicalRole","historicalRoleMixin","type"], + "historicalRole": ["kind","quantity","collective","relator","mode","quality","subkind","category","mixin","historicalRole","historicalRoleMixin"], "historicalRoleMixin": ["category","mixin","historicalRoleMixin"], "event": ["event"], "situation": ["situation"], "type": ["type"], - "enumeration": ["enumeration"], - "datatype": ["datatype"] + "enumeration": ["abstract","enumeration"], + "datatype": ["abstract","datatype"], + "abstract": ["abstract"] } } \ No newline at end of file diff --git a/src/main/resources/plugin.xml b/src/main/resources/plugin.xml index 6b14efd9..d09c52eb 100644 --- a/src/main/resources/plugin.xml +++ b/src/main/resources/plugin.xml @@ -10,6 +10,7 @@ id="it.unibz.inf.ontouml.vp.actionset1.toolbar1" orientation="north" index="last"/> + - + + - + + + + - + label="Export to JSON" + menuPath="it.unibz.inf.ontouml.vp.actionset1.toolbar1/it.unibz.inf.ontouml.vp.actionset1.menu1/#"> + - + menuPath="it.unibz.inf.ontouml.vp.actionset1.toolbar1/it.unibz.inf.ontouml.vp.actionset1.menu1/#"> + - + tooltip="Opens the plugin update dialog." + icon="icons/toolbar/update-orange.png" + label="Update Plugin" + menuPath="it.unibz.inf.ontouml.vp.actionset1.toolbar1/it.unibz.inf.ontouml.vp.actionset1.menu1/#"> + + + - + menuPath="it.unibz.inf.ontouml.vp.actionset1.toolbar1/it.unibz.inf.ontouml.vp.actionset1.menu1/#"> + - - - - + menuPath="it.unibz.inf.ontouml.vp.actionset1.toolbar1/it.unibz.inf.ontouml.vp.actionset1.menu1/#"> + + + + + + + + + + + + + + - ` + + + - + - + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -149,93 +229,97 @@ - + - + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -247,81 +331,81 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -334,93 +418,97 @@ - + - + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -432,81 +520,81 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -518,11 +606,11 @@ - + - +