From b6a914bb720981d264b0f0692aee2e7d0ce35ef2 Mon Sep 17 00:00:00 2001 From: Tiago Prince Sales Date: Thu, 1 Oct 2020 18:29:28 +0200 Subject: [PATCH] Language Updates (#64) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 <> --- .github/workflows/maven.yml | 16 + .mvn/wrapper/MavenWrapperDownloader.java | 169 +- pom.xml | 24 +- .../unibz/inf/ontouml/vp/OntoUMLPlugin.java | 135 +- .../ApplyPropertiesController.java | 489 +++-- .../ApplyStereotypeController.java | 717 ++++--- .../DiagramVerificationController.java | 231 +- .../vp/controllers/GUFOExportController.java | 433 ++-- .../controllers/GitHubAccessController.java | 138 +- .../vp/controllers/JsonExportController.java | 198 +- .../vp/controllers/ModelActionController.java | 41 + .../ModelVerificationController.java | 192 +- .../OntoUMLServerAccessController.java | 486 +++-- .../controllers/ReloadClassesController.java | 171 +- .../vp/controllers/ReportErrorController.java | 47 +- .../controllers/SettingsMenuController.java | 180 +- .../controllers/SmartModellingController.java | 373 +--- .../controllers/UpdatePluginController.java | 193 +- .../ontouml/vp/listeners/DiagramListener.java | 104 +- .../vp/listeners/IssueLogMenuListener.java | 86 +- .../ontouml/vp/listeners/ModelListener.java | 465 ++-- .../vp/listeners/ProjectDiagramListener.java | 101 +- .../ontouml/vp/listeners/ProjectListener.java | 229 +- .../vp/listeners/ProjectModelListener.java | 92 +- .../vp/model/AssociationModelDescription.java | 112 + .../inf/ontouml/vp/model/Configurations.java | 444 ++-- .../inf/ontouml/vp/model/GitHubRelease.java | 144 +- .../ontouml/vp/model/GitHubReleaseAsset.java | 126 +- .../vp/model/ProjectConfigurations.java | 873 ++++---- .../ontouml/vp/model/PropertyDescription.java | 67 + .../inf/ontouml/vp/model/ServerRequest.java | 19 +- .../inf/ontouml/vp/model/uml/Association.java | 686 ++++-- .../vp/model/uml/AssociationClass.java | 246 ++- .../unibz/inf/ontouml/vp/model/uml/Class.java | 1151 +++++----- .../ontouml/vp/model/uml/Generalization.java | 173 +- .../vp/model/uml/GeneralizationSet.java | 293 ++- .../inf/ontouml/vp/model/uml/Literal.java | 144 +- .../unibz/inf/ontouml/vp/model/uml/Model.java | 578 +++-- .../ontouml/vp/model/uml/ModelElement.java | 600 ++++-- .../inf/ontouml/vp/model/uml/Package.java | 308 ++- .../inf/ontouml/vp/model/uml/Property.java | 798 +++---- .../inf/ontouml/vp/model/uml/Reference.java | 60 +- .../inf/ontouml/vp/utils/ActionIdManager.java | 523 +++-- .../vp/utils/OntoUMLConstraintsManager.java | 225 +- .../inf/ontouml/vp/utils/RestrictedTo.java | 168 ++ .../ontouml/vp/utils/SmartColoringUtils.java | 262 +-- .../inf/ontouml/vp/utils/Stereotype.java | 135 ++ .../ontouml/vp/utils/StereotypesManager.java | 762 +++---- .../ontouml/vp/utils/ViewManagerUtils.java | 1320 +++++++----- .../ontouml/vp/views/ConfigurationsView.java | 459 ++-- .../inf/ontouml/vp/views/GUFOExportView.java | 1871 ++++++++--------- .../ontouml/vp/views/HTMLEnabledMessage.java | 84 +- .../inf/ontouml/vp/views/IssueLogMenu.java | 105 +- .../inf/ontouml/vp/views/JCheckBoxTree.java | 1775 ++++++++-------- .../inf/ontouml/vp/views/ProgressPanel.java | 92 +- .../vp/views/SelectRestrictionsView.java | 325 ++- .../inf/ontouml/vp/views/SetOrderView.java | 297 +-- .../resources/association_constraints.json | 134 +- .../association_constraints_nature.json | 123 ++ .../resources/generalization_constraints.json | 16 +- src/main/resources/plugin.xml | 96 + 61 files changed, 11132 insertions(+), 9772 deletions(-) create mode 100644 .github/workflows/maven.yml create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelActionController.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/AssociationModelDescription.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/model/PropertyDescription.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/RestrictedTo.java create mode 100644 src/main/java/it/unibz/inf/ontouml/vp/utils/Stereotype.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/pom.xml b/pom.xml index 3c1cbb7e..b46ea52d 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ it.unibz.inf.ontouml ontouml-vp-plugin - 0.4.0-alpha1 + 0.4.0-alpha2 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 308dc96e..888c64fe 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/OntoUMLPlugin.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/OntoUMLPlugin.java @@ -4,92 +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; /** - * 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.4.0alpha1"; - 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"; - - 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.0alpha2"; + 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/ApplyPropertiesController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyPropertiesController.java index 2e747c36..452f2a89 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyPropertiesController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyPropertiesController.java @@ -1,28 +1,26 @@ 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.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. @@ -32,171 +30,324 @@ */ public class ApplyPropertiesController 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 ActionIdManager.PROPERTY_SET_RESTRICTED_TO: - this.setRestrictedTo(context, clickedClass); - break; - - case ActionIdManager.PROPERTY_SET_IS_ABSTRACT: - final boolean isAbstract = clickedClass.isAbstract(); - forEachSelectedClass(context, cla -> cla.setAbstract(!isAbstract)); - break; - - case ActionIdManager.PROPERTY_SET_IS_DERIVED: - final boolean isDerived = ModelElement.getIsDerived(clickedClass); - forEachSelectedClass(context, selected -> { - ModelElement.setIsDerived(selected, !isDerived); - }); - break; - case ActionIdManager.PROPERTY_SET_IS_EXTENSIONAL: - setBooleanTaggedValue(context, clickedClass, StereotypesManager.PROPERTY_IS_EXTENSIONAL); - break; - - case ActionIdManager.PROPERTY_SET_IS_POWERTYPE: - setBooleanTaggedValue(context, clickedClass, StereotypesManager.PROPERTY_IS_POWERTYPE); - break; - - case ActionIdManager.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 = StereotypesManager.getUniqueStereotypeName(_class); - final Set allClassStereotypes = StereotypesManager.getOntoUMLClassStereotypeNames(); - - switch (action.getActionId()) { - case ActionIdManager.PROPERTY_SET_RESTRICTED_TO: - if (allClassStereotypes.contains(stereotype)) { - final boolean isSmartModelingEnabled = - Configurations.getInstance() - .getProjectConfigurations() - .isSmartModellingEnabled(); - final List nonFixedRestrictedTo = - Arrays.asList(StereotypesManager.STR_CATEGORY, - StereotypesManager.STR_MIXIN, - StereotypesManager.STR_PHASE_MIXIN, - StereotypesManager.STR_ROLE_MIXIN, - StereotypesManager.STR_HISTORICAL_ROLE_MIXIN); - - action.setEnabled(!isSmartModelingEnabled || - nonFixedRestrictedTo.contains(stereotype)); - } else { - action.setEnabled(false); - } - break; - case ActionIdManager.PROPERTY_SET_IS_ABSTRACT: - action.setEnabled(true); - action.setSelected(_class.isAbstract()); - break; - case ActionIdManager.PROPERTY_SET_IS_DERIVED: - action.setEnabled(true); - action.setSelected(ModelElement.getIsDerived(_class)); - break; - case ActionIdManager.PROPERTY_SET_IS_EXTENSIONAL: - action.setEnabled(StereotypesManager.STR_COLLECTIVE.equals(stereotype)); - action.setSelected(Class.getIsExtensional(_class)); - break; - case ActionIdManager.PROPERTY_SET_IS_POWERTYPE: - action.setEnabled(StereotypesManager.STR_TYPE.equals(stereotype)); - action.setSelected(Class.getIsPowertype(_class)); - break; - case ActionIdManager.PROPERTY_SET_ORDER: - action.setEnabled(_class.hasStereotype(StereotypesManager.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 = StereotypesManager.reapplyStereotypeAndGetTaggedValue(clickedClass, metaProperty); - final boolean value = booleanTaggedValue != null && Boolean.parseBoolean(booleanTaggedValue.getValueAsString()); - - forEachSelectedClass(context, cla -> { - ITaggedValue taggedValue = StereotypesManager.reapplyStereotypeAndGetTaggedValue(cla, metaProperty); - - if (taggedValue == null) + @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); - }); - } + taggedValue.setValue(!value); + }); + } - private void setOrderProperty(VPContext context, IClass clickedClass) { - final ITaggedValue baseTaggedValue = - StereotypesManager.reapplyStereotypeAndGetTaggedValue(clickedClass, StereotypesManager.PROPERTY_ORDER); + private void setOrderProperty(IClass clickedClass) { + final ITaggedValue baseTaggedValue = + StereotypesManager.reapplyStereotypeAndGetTaggedValue( + clickedClass, StereotypesManager.PROPERTY_ORDER); - if (baseTaggedValue == null) - return; + if (baseTaggedValue == null) { + return; + } - final SetOrderView dialog = new SetOrderView(baseTaggedValue.getValueAsString()); - ApplicationManager.instance().getViewManager().showDialog(dialog); - final String order = dialog.getOrder(); + final SetOrderView dialog = new SetOrderView(baseTaggedValue.getValueAsString()); + ApplicationManager.instance().getViewManager().showDialog(dialog); + final String order = dialog.getOrder(); - forEachSelectedClass(context, cla -> { - ITaggedValue taggedValue = StereotypesManager.reapplyStereotypeAndGetTaggedValue(cla, StereotypesManager.PROPERTY_ORDER); + ModelElement.forEachSelectedElement( + clickedClass, + selectedClass -> { + ITaggedValue taggedValue = + StereotypesManager.reapplyStereotypeAndGetTaggedValue( + selectedClass, StereotypesManager.PROPERTY_ORDER); - if (taggedValue == null) + 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 SelectRestrictionsView dialog = new SelectRestrictionsView(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 + } + + 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/ApplyStereotypeController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotypeController.java index e59e8cfd..b6ee4cc9 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotypeController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ApplyStereotypeController.java @@ -1,24 +1,25 @@ 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.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. @@ -28,335 +29,389 @@ */ public class ApplyStereotypeController 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) { + @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); - - 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; + 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); + } + }); } + } - for (IDiagramElement diagramElement : diagramElements) { - if (diagramElement.getModelElement().getModelType().equals(context.getModelElement().getModelType())) - defineActionBehavior(action, diagramElement.getModelElement()); - } + return selectedOrInvertedAssociations; + } - } + private boolean isStereotypeActionAllowed(String actionId, IClass _class) { + final Set children = Class.getChildren(_class); - private void applyStereotype(VPAction action, IModelElement element) { - switch (action.getActionId()) { - case ActionIdManager.TYPE: - case ActionIdManager.TYPE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_TYPE); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.HISTORICAL_ROLE: - case ActionIdManager.HISTORICAL_ROLE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_HISTORICAL_ROLE); - break; - case ActionIdManager.HISTORICAL_ROLE_MIXIN: - case ActionIdManager.HISTORICAL_ROLE_MIXIN_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_HISTORICAL_ROLE_MIXIN); - break; - case ActionIdManager.EVENT: - case ActionIdManager.EVENT_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_EVENT); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.SITUATION: - case ActionIdManager.SITUATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_SITUATION); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.ENUMERATION: - case ActionIdManager.ENUMERATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_ENUMERATION); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.DATATYPE: - case ActionIdManager.DATATYPE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_DATATYPE); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.SUBKIND: - case ActionIdManager.SUBKIND_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_SUBKIND); - break; - case ActionIdManager.ROLE_MIXIN: - case ActionIdManager.ROLE_MIXIN_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_ROLE_MIXIN); - break; - case ActionIdManager.ROLE: - case ActionIdManager.ROLE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_ROLE); - break; - case ActionIdManager.RELATOR: - case ActionIdManager.RELATOR_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_RELATOR); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.QUANTITY: - case ActionIdManager.QUANTITY_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_QUANTITY); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.QUALITY: - case ActionIdManager.QUALITY_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_QUALITY); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.PHASE_MIXIN: - case ActionIdManager.PHASE_MIXIN_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_PHASE_MIXIN); - break; - case ActionIdManager.PHASE: - case ActionIdManager.PHASE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_PHASE); - break; - case ActionIdManager.MODE: - case ActionIdManager.MODE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_MODE); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.MIXIN: - case ActionIdManager.MIXIN_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_MIXIN); - break; - case ActionIdManager.KIND: - case ActionIdManager.KIND_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_KIND); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.COLLECTIVE: - case ActionIdManager.COLLECTIVE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_COLLECTIVE); - Class.setDefaultRestrictedTo((IClass) element); - break; - case ActionIdManager.CATEGORY: - case ActionIdManager.CATEGORY_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_CATEGORY); - break; - case ActionIdManager.INSTANTIATION: - case ActionIdManager.INSTANTIATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_INSTANTIATION); - break; - case ActionIdManager.TERMINATION: - case ActionIdManager.TERMINATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_TERMINATION); - break; - case ActionIdManager.PARTICIPATIONAL: - case ActionIdManager.PARTICIPATIONAL_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_PARTICIPATIONAL); - break; - case ActionIdManager.PARTICIPATION: - case ActionIdManager.PARTICIPATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_PARTICIPATION); - break; - case ActionIdManager.HISTORICAL_DEPENDENCE: - case ActionIdManager.HISTORICAL_DEPENDENCE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_HISTORICAL_DEPENDENCE); - break; - case ActionIdManager.CREATION: - case ActionIdManager.CREATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_CREATION); - break; - case ActionIdManager.MANIFESTATION: - case ActionIdManager.MANIFESTATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_MANIFESTATION); - break; - case ActionIdManager.BRINGS_ABOUT: - case ActionIdManager.BRINGS_ABOUT_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_BRINGS_ABOUT); - break; - case ActionIdManager.TRIGGERS: - case ActionIdManager.TRIGGERS_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_TRIGGERS); - break; - case ActionIdManager.MATERIAL: - case ActionIdManager.MATERIAL_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_MATERIAL); - break; - case ActionIdManager.COMPARATIVE: - case ActionIdManager.COMPARATIVE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_COMPARATIVE); - break; - case ActionIdManager.MEDIATION: - case ActionIdManager.MEDIATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_MEDIATION); - break; - case ActionIdManager.CHARACTERIZATION: - case ActionIdManager.CHARACTERIZATION_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_CHARACTERIZATION); - break; - case ActionIdManager.EXTERNAL_DEPENDENCE: - case ActionIdManager.EXTERNAL_DEPENDENCE_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_EXTERNAL_DEPENDENCE); - break; - case ActionIdManager.COMPONENT_OF: - case ActionIdManager.COMPONENT_OF_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_COMPONENT_OF); - break; - case ActionIdManager.MEMBER_OF: - case ActionIdManager.MEMBER_OF_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_MEMBER_OF); - break; - case ActionIdManager.SUB_COLLECTION_OF: - case ActionIdManager.SUB_COLLECTION_OF_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_SUB_COLLECTION_OF); - break; - case ActionIdManager.SUB_QUANTITY_OF: - case ActionIdManager.SUB_QUANTITY_OF_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_SUB_QUANTITY_OF); - break; - case ActionIdManager.BEGIN: - case ActionIdManager.BEGIN_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_BEGIN); - break; - case ActionIdManager.END: - case ActionIdManager.END_FIXED: - StereotypesManager.applyStereotype(element, StereotypesManager.STR_END); - break; + for (IClass child : children) { + final List allowedActions = + OntoUMLConstraintsManager.getAllowedActionsBasedOnChild(child); + if (!allowedActions.contains(actionId)) { + return false; } + } - 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); + final Set parents = Class.getParents(_class); - if (isSmartModelingEnabled && isAssociation) - SmartModellingController.setAssociationMetaProperties((IAssociation) element); - } - - private void defineActionBehavior(VPAction action, IModelElement element) { - - if (element.getModelType().equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION)) { - final IAssociation association = (IAssociation) element; - SmartModellingController.manageAssociationStereotypes(association, action); - return; - } - - if (element.getModelType().equals(IModelElementFactory.MODEL_TYPE_CLASS)) { - final IClass _class = (IClass) element; - SmartModellingController.manageClassStereotypes(_class, action); - return; + for (IClass parent : parents) { + final List allowedActions = + OntoUMLConstraintsManager.getAllowedActionsBasedOnParent(parent); + if (!allowedActions.contains(actionId)) { + return false; } - } - - 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 + } + + 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/DiagramVerificationController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationController.java index cb488cc2..025b4fb2 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/DiagramVerificationController.java @@ -1,7 +1,5 @@ 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; @@ -9,127 +7,122 @@ 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. - * - */ +/** 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; - } - - } - - public 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(); - } - } - } - } -} \ No newline at end of file + 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/GUFOExportController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/GUFOExportController.java index aeda99fc..7406e08f 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/GUFOExportController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/GUFOExportController.java @@ -1,20 +1,10 @@ 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.Configurations; import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; @@ -23,226 +13,219 @@ 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(); - } - } - } - } - -} \ No newline at end of file + 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 index 8541f6b6..74f16251 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/GitHubAccessController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/GitHubAccessController.java @@ -1,5 +1,11 @@ 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; @@ -13,74 +19,76 @@ import java.nio.file.Path; import java.util.ArrayList; import java.util.List; - import javax.net.ssl.HttpsURLConnection; -import com.google.gson.JsonArray; -import com.google.gson.JsonParser; +public class GitHubAccessController { -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; + public static final String GITHUB_API = "https://api.github.com"; + public static final String REPOS = "/repos"; + public static final String RELEASES = "/releases"; -public class GitHubAccessController { + 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(); - final public static String GITHUB_API = "https://api.github.com"; - final public static String REPOS = "/repos"; - final public static 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; - } + 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 index cb41e49e..5d9a1405 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/JsonExportController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/JsonExportController.java @@ -5,122 +5,118 @@ 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). + * 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; + 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(); } - } -} \ No newline at end of file + 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/ModelVerificationController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationController.java index 760ac02e..2536543e 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ModelVerificationController.java @@ -1,118 +1,112 @@ 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.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(); - } - } - } - } - -} \ No newline at end of file + 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 index f88eb03d..c69f06e7 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/OntoUMLServerAccessController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/OntoUMLServerAccessController.java @@ -1,5 +1,13 @@ 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; @@ -10,228 +18,270 @@ 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; - -import it.unibz.inf.ontouml.vp.model.Configurations; -import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; -import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; - /** - * - * Class responsible for making requests to the OntoUML Server based on standard - * end points and configured server URL. - * + * 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." - + "\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 (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; - } - + 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/ReloadClassesController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesController.java index 08d571f3..c21dc404 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReloadClassesController.java @@ -1,7 +1,5 @@ package it.unibz.inf.ontouml.vp.controllers; -import java.util.Set; - import com.vp.plugin.ApplicationManager; import com.vp.plugin.DiagramManager; import com.vp.plugin.action.VPAction; @@ -9,68 +7,117 @@ 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.utils.StereotypesManager; +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(); - } + @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); - @Override - public void update(VPAction action) { - } - - @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 Set stereotypes = StereotypesManager.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); -// } -// } - } - } - } + for (String targetStereotype : stereotypes) { + // // Method getAllowedAssociations() was removed + // final List allowedAssociations = + // OntoUMLConstraintsManager.getAllowedAssociations(sourceStereotype, + // targetStereotype); -} \ No newline at end of file + // 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/ReportErrorController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorController.java index f76d537f..fb639ba6 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/ReportErrorController.java @@ -1,36 +1,33 @@ 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.ViewManagerUtils; +import java.awt.Desktop; +import java.net.URI; public class ReportErrorController 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) { - ViewManagerUtils.reportBugErrorDialog(true); - unsupportedException.printStackTrace(); - } catch (SecurityException securityException) { - ViewManagerUtils.reportBugErrorDialog(true); - securityException.printStackTrace(); - } catch(Exception e) { - ViewManagerUtils.reportBugErrorDialog(false); - e.printStackTrace(); - } - } + private static final String REPORT_URL = "https://forms.gle/btx7CDSy9kn5yb3WA"; - @Override - public void update(VPAction arg0) {} + @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 index 68f2ba2f..921dc2fc 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/SettingsMenuController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/SettingsMenuController.java @@ -8,116 +8,88 @@ 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 + * 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; - } - - } + 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 index d524900b..9757368b 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/SmartModellingController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/SmartModellingController.java @@ -1,323 +1,70 @@ package it.unibz.inf.ontouml.vp.controllers; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -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; - -import it.unibz.inf.ontouml.vp.utils.OntoUMLConstraintsManager; -import it.unibz.inf.ontouml.vp.utils.StereotypesManager; +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); - - 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 StereotypesManager.STR_CHARACTERIZATION: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_COMPARATIVE: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "0..*"); - association.setDerived(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_COMPONENT_OF: - setCardinalityIfEmpty(source, "1..*"); - setCardinalityIfEmpty(target, "1"); - setAggregationKind(association); - return; - case StereotypesManager.STR_MATERIAL: - if (targetStereotype.equals(StereotypesManager.STR_ROLE) || targetStereotype.equals(StereotypesManager.STR_ROLE_MIXIN)) - setCardinalityIfEmpty(source, "1..*"); - else - setCardinalityIfEmpty(source, "0..*"); - - if (sourceStereotype.equals(StereotypesManager.STR_ROLE) || sourceStereotype.equals(StereotypesManager.STR_ROLE_MIXIN)) - setCardinalityIfEmpty(target, "1..*"); - else - setCardinalityIfEmpty(target, "0..*"); - - association.setDerived(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_EXTERNAL_DEPENDENCE: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "1..*"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_MEDIATION: - if (targetStereotype.equals(StereotypesManager.STR_ROLE) || targetStereotype.equals(StereotypesManager.STR_ROLE_MIXIN)) - setCardinalityIfEmpty(source, "1..*"); - else - setCardinalityIfEmpty(source, "0..*"); - - setCardinalityIfEmpty(target, "1"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_MEMBER_OF: - setCardinalityIfEmpty(source, "1..*"); - setCardinalityIfEmpty(target, "1..*"); - setAggregationKind(association); - return; - case StereotypesManager.STR_SUB_COLLECTION_OF: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - setAggregationKind(association); - return; - case StereotypesManager.STR_SUB_QUANTITY_OF: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - source.setReadOnly(true); - setAggregationKind(association); - return; - case StereotypesManager.STR_CREATION: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - source.setReadOnly(true); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_HISTORICAL_DEPENDENCE: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "1"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_MANIFESTATION: - setCardinalityIfEmpty(source, "0..*"); - setCardinalityIfEmpty(target, "1..*"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_PARTICIPATION: - if ( - targetStereotype.equals(StereotypesManager.STR_HISTORICAL_ROLE) || - targetStereotype.equals(StereotypesManager.STR_HISTORICAL_ROLE_MIXIN) - ) - setCardinalityIfEmpty(source, "1..*"); - else - setCardinalityIfEmpty(source, "0..*"); - - setCardinalityIfEmpty(target, "1..*"); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypesManager.STR_PARTICIPATIONAL: - setCardinalityIfEmpty(source, "1..*"); - setCardinalityIfEmpty(target, "1"); - source.setReadOnly(true); - target.setReadOnly(true); - setAggregationKind(association); - return; - case StereotypesManager.STR_TERMINATION: - setCardinalityIfEmpty(source, "1"); - setCardinalityIfEmpty(target, "1"); - source.setReadOnly(true); - target.setReadOnly(true); - removeAggregationKind(association); - return; - case StereotypesManager.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 StereotypesManager.STR_CATEGORY: - _class.setAbstract(true); - break; - case StereotypesManager.STR_ROLE_MIXIN: - _class.setAbstract(true); - break; - case StereotypesManager.STR_PHASE_MIXIN: - _class.setAbstract(true); - break; - case StereotypesManager.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 = OntoUMLConstraintsManager.getAllowedStereotypeActionsOnAssociation(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 = OntoUMLConstraintsManager.getAllowedStereotypeActionsOnGeneral(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 = OntoUMLConstraintsManager.getAllowedStereotypeActionsSpecific(subStereotype); - - if (allowedCombinationsSuper == null || !allowedCombinationsSuper.contains(action.getActionId())) - action.setEnabled(false); - } - - return; - } - + 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/UpdatePluginController.java b/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginController.java index 63db85ce..a9f97256 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginController.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/controllers/UpdatePluginController.java @@ -1,5 +1,12 @@ 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; @@ -9,102 +16,96 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -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; - 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(); - } - } - } - + 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/listeners/DiagramListener.java b/src/main/java/it/unibz/inf/ontouml/vp/listeners/DiagramListener.java index 621f0f80..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.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() - ) { - SmartColoringUtils.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) { - SmartColoringUtils.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 index b5bd2b30..2915533a 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/listeners/IssueLogMenuListener.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/listeners/IssueLogMenuListener.java @@ -1,55 +1,53 @@ package it.unibz.inf.ontouml.vp.listeners; -import javax.swing.*; - 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()); - } + 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 8c249b9d..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 java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Set; - 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; 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 = StereotypesManager.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 = StereotypesManager.getSortalStereotypeNames(); - interestStereotypes.addAll(StereotypesManager.getUltimateSortalStereotypeNames()); - interestStereotypes.add(StereotypesManager.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)) { - SmartColoringUtils.paint(_class); - } - } - - private void enforceAndPropagateRestrictedTo(PropertyChangeEvent event) { - final IClass _class = event.getSource() instanceof IClass ? (IClass) event.getSource() : null; - final String stereotype = StereotypesManager.getUniqueStereotypeName(_class); - final Object newValue = event.getNewValue(); - final Object oldValue = event.getOldValue(); - - if (stereotype == null) { - return; - } - - switch (stereotype) { - case StereotypesManager.STR_EVENT: - case StereotypesManager.STR_DATATYPE: - case StereotypesManager.STR_ENUMERATION: - case StereotypesManager.STR_KIND: - case StereotypesManager.STR_COLLECTIVE: - case StereotypesManager.STR_QUANTITY: - case StereotypesManager.STR_RELATOR: - case StereotypesManager.STR_MODE: - case StereotypesManager.STR_QUALITY: - case StereotypesManager.STR_TYPE: - if (!newValue.equals(oldValue)) { - Class.setDefaultRestrictedTo(_class); - propagateRestrictionsToDescendants(_class); - } - break; - case StereotypesManager.STR_CATEGORY: - case StereotypesManager.STR_ROLE_MIXIN: - case StereotypesManager.STR_PHASE_MIXIN: - case StereotypesManager.STR_MIXIN: - case StereotypesManager.STR_HISTORICAL_ROLE_MIXIN: - if (!newValue.equals(oldValue)) { - propagateRestrictionsToDescendants(_class); - } - break; - case StereotypesManager.STR_SUBKIND: - case StereotypesManager.STR_ROLE: - case StereotypesManager.STR_PHASE: - case StereotypesManager.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 ? StereotypesManager.getUniqueStereotypeName(_class) : null; - - if (_class == null || stereotype == null) { - return; - } - - switch (stereotype) { - case StereotypesManager.STR_SUBKIND: - case StereotypesManager.STR_ROLE: - case StereotypesManager.STR_PHASE: - case StereotypesManager.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 = StereotypesManager.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 = StereotypesManager.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 5d01bed1..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 @@ -1,122 +1,137 @@ package it.unibz.inf.ontouml.vp.listeners; -import java.time.ZonedDateTime; -import java.util.List; - import com.vp.plugin.ApplicationManager; import com.vp.plugin.model.IProject; import com.vp.plugin.model.IProjectListener; - 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(); - StereotypesManager.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(); - } - } - - 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) { - 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) { - checkUpdates(); - } - - @Override - public void projectPreSave(IProject project) {} - - @Override - public void projectRenamed(IProject project) {} - - @Override - public void projectSaved(IProject project) { - checkUpdates(); - } - + 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/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/Configurations.java b/src/main/java/it/unibz/inf/ontouml/vp/model/Configurations.java index 073835da..ada7bbf6 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/Configurations.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/Configurations.java @@ -1,14 +1,5 @@ package it.unibz.inf.ontouml.vp.model; -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; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; @@ -19,226 +10,231 @@ 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 + * 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; - } - + 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/GitHubRelease.java b/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubRelease.java index 3f74b8d8..faa17556 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubRelease.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubRelease.java @@ -1,108 +1,102 @@ package it.unibz.inf.ontouml.vp.model; -import java.time.ZonedDateTime; -import java.util.ArrayList; -import java.util.List; - 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 { - final private static String PROP_TAG_NAME = "tag_name"; - final private static String PROP_CREATED_AT = "created_at"; - final private static String PROP_PRERELEASE = "prerelease"; - final private static String PROP_ASSETS = "assets"; - final private static String PROP_ID = "id"; + 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; + @Expose() private String tagName; - // Since Gson shows problems with the default serialization of ZonedDateTime we rely on strings - @Expose() - private String createdAt; + // Since Gson shows problems with the default serialization of ZonedDateTime we rely on strings + @Expose() private String createdAt; - @Expose() - private boolean isPrerelease; + @Expose() private boolean isPrerelease; - @Expose() - private List assets; + @Expose() private List assets; - @Expose() - private GitHubReleaseAsset installationFileAsset; + @Expose() private GitHubReleaseAsset installationFileAsset; - @SerializedName("releaseId") - @Expose() - private String id; + @SerializedName("releaseId") + @Expose() + private String id; - public GitHubRelease() { - tagName = null; - createdAt = null; - isPrerelease = false; - assets = null; - installationFileAsset = null; - id = null; - } + public GitHubRelease() { + tagName = null; + createdAt = null; + isPrerelease = false; + assets = null; + installationFileAsset = null; + id = null; + } - public GitHubRelease(JsonObject source) { - if (source == null) { - throw new NullPointerException(); - } + 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(); + 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; + assets = new ArrayList<>(); + installationFileAsset = null; - JsonArray assetsArray = source.get(PROP_ASSETS).getAsJsonArray(); - assetsArray.forEach(item -> { - GitHubReleaseAsset asset = item.isJsonObject() ? new GitHubReleaseAsset(item.getAsJsonObject()) : null; + JsonArray assetsArray = source.get(PROP_ASSETS).getAsJsonArray(); + assetsArray.forEach( + item -> { + GitHubReleaseAsset asset = + item.isJsonObject() ? new GitHubReleaseAsset(item.getAsJsonObject()) : null; - if (asset != null) { + if (asset != null) { assets.add(asset); - } + } - if (asset.isInstallationFileAsset()) { + if (asset.isInstallationFileAsset()) { installationFileAsset = asset; - } - }); - } - - public ZonedDateTime getCreatedAt() { - if (createdAt != null) - return ZonedDateTime.parse(createdAt); + } + }); + } - return null; - } + public ZonedDateTime getCreatedAt() { + if (createdAt != null) return ZonedDateTime.parse(createdAt); - public boolean isPrerelease() { - return isPrerelease; - } + return null; + } - public String getTagName() { - return tagName; - } + public boolean isPrerelease() { + return isPrerelease; + } - public List getAssets() { - return assets; - } + public String getTagName() { + return tagName; + } - public GitHubReleaseAsset getInstallationFileAsset() { - return installationFileAsset; - } + public List getAssets() { + return assets; + } - public String getId() { - return id; - } + public GitHubReleaseAsset getInstallationFileAsset() { + return installationFileAsset; + } - @Override - public boolean equals(Object obj) { - return obj instanceof GitHubRelease ? getId().equals(((GitHubRelease) obj).getId()) : false; - } + 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 index 1fd7a0a4..cd2d48fd 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubReleaseAsset.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/GitHubReleaseAsset.java @@ -5,70 +5,66 @@ import com.google.gson.annotations.SerializedName; public class GitHubReleaseAsset { - - final private static String PROP_NAME = "name"; - final private static String PROP_ID = "id"; - final private static String PROP_BROWSER_DOWNLOAD_URL = "browser_download_url"; - final private static String PROP_CONTENT_TYPE = "content_type"; - - final private static 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; - } + 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/ProjectConfigurations.java b/src/main/java/it/unibz/inf/ontouml/vp/model/ProjectConfigurations.java index f39ca880..9c4cc3ef 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/ProjectConfigurations.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/ProjectConfigurations.java @@ -1,467 +1,428 @@ package it.unibz.inf.ontouml.vp.model; -import java.util.HashSet; - 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 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 + + 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/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/ServerRequest.java b/src/main/java/it/unibz/inf/ontouml/vp/model/ServerRequest.java index 0049a059..d4aef0f8 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/model/ServerRequest.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/model/ServerRequest.java @@ -1,18 +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; - } + private boolean doStop = false; - protected synchronized boolean keepRunning() { - return this.doStop == false; - } + public synchronized void doStop() { + this.doStop = true; + } - @Override - public void run() {} + 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 index e7a94acf..c8f21101 100644 --- 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 @@ -1,214 +1,530 @@ package it.unibz.inf.ontouml.vp.model.uml; -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.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 - * + * 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())); + 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; - String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); - } + public Association(IAssociation source) { + this.sourceModelElement = source; - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - setAbstract(source.isAbstract()); - setDerived(source.isDerived()); - } - - @Override - public String getId() { - return getSourceModelElement().getId(); - } + this.type = ModelElement.TYPE_RELATION; + this.id = source.getId(); + setName(source.getName()); + setDescription(source.getDescription()); - @Override - public IAssociation getSourceModelElement() { - return this.sourceModelElement; - } + addProperty(new Property((IAssociationEnd) source.getFromEnd())); + addProperty(new Property((IAssociationEnd) source.getToEnd())); - @Override - public String getOntoUMLType() { - return this.type; - } + String[] stereotypes = source.toStereotypeArray(); + for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { + addStereotype(stereotypes[i]); + } - 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); - } + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + setAbstract(source.isAbstract()); + setDerived(source.isDerived()); + } - public void addProperty(Property property) { - if (this.properties == null) - this.properties = new ArrayList(); + public Association(IAssociation source, HashSet modelElements) { + this.sourceModelElement = source; - this.properties.add(property); - } + 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())); + } - public void removeProperty(Property property) { + if (modelElements.contains(source.getToEnd().getId())) { + addProperty(new Property((IAssociationEnd) source.getToEnd())); + } - if (this.properties.contains(property)) - this.properties.remove(property); - } + String[] stereotypes = source.toStereotypeArray(); + for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { + addStereotype(stereotypes[i]); + } - public boolean isAbstract() { - return this.isAbstract; - } + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + setAbstract(source.isAbstract()); + setDerived(source.isDerived()); + } - public void setAbstract(boolean isAbstract) { - this.isAbstract = isAbstract; - } + @Override + public String getId() { + return getSourceModelElement().getId(); + } - public boolean isDerived() { - return this.isDerived; - } + @Override + public IAssociation getSourceModelElement() { + return this.sourceModelElement; + } - public void setDerived(boolean isDerived) { - this.isDerived = isDerived; - } + @Override + public String getOntoUMLType() { + return this.type; + } -} \ No newline at end of file + 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 index cf47d771..c72f5bab 100644 --- 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 @@ -4,180 +4,172 @@ 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.StereotypesManager; - +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 - * + * 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; + private final IAssociationClass sourceModelElement; + + @SerializedName("type") + @Expose + private final String type; - @SerializedName("type") - @Expose - private final String type; + @SerializedName("id") + @Expose + private final String id; - @SerializedName("id") - @Expose - private final String id; + @SerializedName("name") + @Expose + private String name; - @SerializedName("name") - @Expose - private String name; + @SerializedName("description") + @Expose + private String description; - @SerializedName("description") - @Expose - private String description; + @SerializedName("properties") + @Expose + private List properties; - @SerializedName("properties") - @Expose - private List properties; + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; + @SerializedName("stereotypes") + @Expose + private List stereotypes; - @SerializedName("stereotypes") - @Expose - private List stereotypes; + @SerializedName("isAbstract") + @Expose + private boolean isAbstract; - @SerializedName("isAbstract") - @Expose - private boolean isAbstract; + @SerializedName("isDerived") + @Expose + private boolean isDerived; - @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()); + 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()); + Property sourceEnd = new Property(source, source.getFrom()); + Property targetEnd = new Property(source, source.getTo()); - addStereotype(StereotypesManager.STR_DERIVATION); + addStereotype(Stereotype.DERIVATION); - addProperty(sourceEnd); - addProperty(targetEnd); - } + addProperty(sourceEnd); + addProperty(targetEnd); + } - @Override - public String getId() { - return getSourceModelElement().getId(); - } + @Override + public String getId() { + return getSourceModelElement().getId(); + } - @Override - public IAssociationClass getSourceModelElement() { - return this.sourceModelElement; - } + @Override + public IAssociationClass getSourceModelElement() { + return this.sourceModelElement; + } - @Override - public String getOntoUMLType() { - return this.type; - } + @Override + public String getOntoUMLType() { + return this.type; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description); - } + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + } - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } - public List getStereotypes() { - return this.stereotypes; - } + public List getStereotypes() { + return this.stereotypes; + } - public void setStereotypes(List stereotypes) { - this.stereotypes = stereotypes; - } + public void setStereotypes(List stereotypes) { + this.stereotypes = stereotypes; + } - public String getStereotype(int position) { - return this.stereotypes.get(position); - } + public String getStereotype(int position) { + return this.stereotypes.get(position); + } - public void addStereotype(String name) { - if (this.stereotypes == null) - this.stereotypes = new ArrayList(); + public void addStereotype(String name) { + if (this.stereotypes == null) this.stereotypes = new ArrayList(); - this.stereotypes.add(name); - } + this.stereotypes.add(name); + } - public void removeStereotype(String name) { + public void removeStereotype(String name) { - if (this.stereotypes.contains(name)) - this.stereotypes.remove(name); - } + if (this.stereotypes.contains(name)) this.stereotypes.remove(name); + } - public List getProperties() { - return properties; - } + public List getProperties() { + return properties; + } - public void setProperties(List properties) { - this.properties = properties; - } + public void setProperties(List properties) { + this.properties = properties; + } - public Property getProperty(int position) { - return this.properties.get(position); - } + public Property getProperty(int position) { + return this.properties.get(position); + } - public void addProperty(Property property) { - if (this.properties == null) - this.properties = new ArrayList(); + public void addProperty(Property property) { + if (this.properties == null) this.properties = new ArrayList(); - this.properties.add(property); - } + this.properties.add(property); + } - public void removeProperty(Property property) { + public void removeProperty(Property property) { - if (this.properties.contains(property)) - this.properties.remove(property); - } + if (this.properties.contains(property)) this.properties.remove(property); + } - public boolean isAbstract() { - return this.isAbstract; - } + public boolean isAbstract() { + return this.isAbstract; + } - public void setAbstract(boolean isAbstract) { - this.isAbstract = isAbstract; - } + public void setAbstract(boolean isAbstract) { + this.isAbstract = isAbstract; + } - public boolean isDerived() { - return this.isDerived; - } + public boolean isDerived() { + return this.isDerived; + } - public void setDerived(boolean isDerived) { - this.isDerived = 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 index 72f759e7..42f86493 100644 --- 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 @@ -1,18 +1,5 @@ package it.unibz.inf.ontouml.vp.model.uml; -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; @@ -28,594 +15,660 @@ 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 + * 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; + private final IModelElement sourceModelElement; - @SerializedName("type") - @Expose - private final String type; + @SerializedName("type") + @Expose + private final String type; - @SerializedName("id") - @Expose - private final String id; + @SerializedName("id") + @Expose + private final String id; - @SerializedName("name") - @Expose - private String name; + @SerializedName("name") + @Expose + private String name; - @SerializedName("description") - @Expose - private String description; + @SerializedName("description") + @Expose + private String description; - @SerializedName("properties") - @Expose - private Set properties; + @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; + } + } - @SerializedName("literals") - @Expose - private LinkedList literals; + if (hasIsExtensional(source)) { + this.isExtensional = parser.parse("" + isExtensional(source)); + } else { + this.isExtensional = parser.parse("null"); + } - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; + if (hasIsPowertype(source)) { + this.isPowertype = parser.parse("" + isPowertype(source)); + } else { + this.isPowertype = parser.parse("null"); + } - @SerializedName("stereotypes") - @Expose - private List stereotypes; + if (hasOrder(source)) { + this.order = getOrder(source); + } + } + } - @SerializedName("isAbstract") - @Expose - private boolean isAbstract; + @Override + public IModelElement getSourceModelElement() { + return this.sourceModelElement; + } + + @Override + public String getId() { + return getSourceModelElement().getId(); + } - @SerializedName("isDerived") - @Expose - private boolean isDerived; + @Override + public String getOntoUMLType() { + return this.type; + } - @SerializedName("allowed") - @Expose - private JsonArray restrictedTo; + public String getName() { + return name; + } - @SerializedName("isExtensional") - @Expose - private JsonElement isExtensional; + 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); + } - @SerializedName("isPowertype") - @Expose - private JsonElement isPowertype; + public static Set getParents(IClass _class) { + final Set parents = new HashSet(); + final ISimpleRelationship[] relationships = _class.toToRelationshipArray(); - @SerializedName("order") - @Expose - private String order; + 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); - 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; - } + if (parent instanceof IClass) { + parents.add((IClass) parent); + } + } + } - public Class(IClass source) { - this((IModelElement) source); + return parents; + } - final IAttribute[] attributes = source.toAttributeArray(); - for (int i = 0; attributes != null && i < attributes.length; i++) { - addProperties(new Property(attributes[i])); - } + public static Set getChildren(IClass _class) { + final Set children = new HashSet(); + final ISimpleRelationship[] relationships = _class.toFromRelationshipArray(); - final String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); - } + 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 (this.stereotypes != null && this.stereotypes.contains(StereotypesManager.STR_ENUMERATION)) { - IEnumerationLiteral[] literalArray = source.toEnumerationLiteralArray(); - for (int i = 0; literalArray != null && i < literalArray.length; i++) - addLiteral(new Literal(literalArray[i])); + if (child instanceof IClass) { + children.add((IClass) child); + } } + } - setAbstract(source.isAbstract()); - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + return children; + } - if (source.getName().trim().startsWith("/")) { - setName(source.getName().substring(1)); - this.isDerived = true; - } else { - setName(source.getName().trim()); - } + public static Set getAncestors(IClass _class) { + final Set ancestors = new HashSet(); + final Set parents = getChildren(_class); - setDescription(source.getDescription()); + for (IClass parent : parents) { + ancestors.addAll(getDescendants(parent)); + ancestors.add(parent); + } - loadTags(source); - } + return ancestors; + } - public Class(IDataType source) { - this((IModelElement) source); + public static Set getDescendants(IClass _class) { + final Set descendants = new HashSet(); + final Set children = getChildren(_class); - addStereotype(StereotypesManager.STR_DATATYPE); - setAbstract(false); - setDerived(false); + for (IClass child : children) { + descendants.addAll(getDescendants(child)); + descendants.add(child); + } - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + return descendants; + } - if (source.getName().trim().startsWith("/")) { - setName(source.getName().substring(1)); - this.isDerived = true; - } else { - setName(source.getName().trim()); - } + public static void applyOnChildren(IClass _class, Consumer function) { + final Set children = getChildren(_class); - // TODO: change this to apply only to default VP datatypes - if (restrictedTo == null) { - restrictedTo = new JsonArray(); - restrictedTo.add("abstract"); - } + for (IClass child : children) { + function.accept(child); + } + } - } + public static void applyOnParents(IClass _class, Consumer function) { + final Set parents = getParents(_class); - public Class(IClass source, HashSet modelElements) { - this((IModelElement) source); + for (IClass parent : parents) { + function.accept(parent); + } + } - 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])); - } + public static void applyOnDescendants(IClass _class, Function function) { + final Set children = getChildren(_class); - final String[] stereotypes = source.toStereotypeArray(); - for (int i = 0; stereotypes != null && i < stereotypes.length; i++) { - addStereotype(stereotypes[i]); + for (IClass child : children) { + final boolean shouldContinue = function.apply(child); + if (shouldContinue) { + applyOnDescendants(child, function); } + } + } - if (this.stereotypes != null && this.stereotypes.contains(StereotypesManager.STR_ENUMERATION)) { - IEnumerationLiteral[] literalArray = source.toEnumerationLiteralArray(); - for (int i = 0; literalArray != null && i < literalArray.length; i++) - addLiteral(new Literal(literalArray[i])); + 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); } + } + } - setAbstract(source.isAbstract()); - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + public static void setRestrictedTo(IClass _class, String restrictions) { + if (_class.getTaggedValues() == null) { + return; + } - if (source.getName().trim().startsWith("/")) { - setName(source.getName().substring(1)); - this.isDerived = true; - } else { - setName(source.getName().trim()); - } + System.out.println("WILL TRY TO SET VALUE: " + restrictions); - 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); - } - } - } + Iterator values = _class.getTaggedValues().taggedValueIterator(); - @Override - public IModelElement getSourceModelElement() { - return this.sourceModelElement; - } + while (values != null && values.hasNext()) { + final ITaggedValue value = (ITaggedValue) values.next(); - @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()); - } + 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() : ""; - 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(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); - } - - return ; - } - } - } - - private static void setDefaultRestrictedTo(IClass element, String stereotypeName) { - final String defaultNature = StereotypesManager.getDefaultRestrictedTo(stereotypeName); - setRestrictedTo(element, defaultNature); - } - - public static void setDefaultRestrictedTo(IClass _class) { - setDefaultRestrictedTo(_class, - StereotypesManager.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; - } - } + if (!currentRestrictions.equals(newRestrictions)) { + value.setValue(newRestrictions); + } - 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(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 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 getIsPowertype(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); + System.out.println("NEW VALUE: " + value.getValueAsText()); + + return; } - } - - 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 getIsExtensional(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); + } + } + + 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; } - } - - 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; - } - -} \ No newline at end of file + } + + 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 index 128f7624..22954d0e 100644 --- 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 @@ -7,123 +7,120 @@ import com.vp.plugin.model.IModelElement; /** - * - * Implementation of ModelElement to handle IGeneralization objects to be - * serialized as ontouml-schema/Generalization - * + * 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; + private final IGeneralization sourceModelElement; - @SerializedName("type") - @Expose - private final String type; + @SerializedName("type") + @Expose + private final String type; - @SerializedName("id") - @Expose - private final String id; + @SerializedName("id") + @Expose + private final String id; - @SerializedName("name") - @Expose - private String name; + @SerializedName("name") + @Expose + private String name; - @SerializedName("description") - @Expose - private String description; + @SerializedName("description") + @Expose + private String description; - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; + @SerializedName("propertyAssignments") + @Expose + private JsonObject propertyAssignments; - @SerializedName("general") - @Expose - private Reference general; + @SerializedName("general") + @Expose + private Reference general; - @SerializedName("specific") - @Expose - private Reference specific; + @SerializedName("specific") + @Expose + private Reference specific; - public Generalization(IGeneralization source) { - this.sourceModelElement = source; + public Generalization(IGeneralization source) { + this.sourceModelElement = source; - this.type = ModelElement.TYPE_GENERALIZATION; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); + 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())); + setGeneral(new Reference(source.getFrom())); + setSpecific(new Reference(source.getTo())); - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - } + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } - @Override - public String getId() { - return getSourceModelElement() != null ? getSourceModelElement().getId() : null; - } + @Override + public String getId() { + return getSourceModelElement() != null ? getSourceModelElement().getId() : null; + } - @Override - public IGeneralization getSourceModelElement() { - return this.sourceModelElement; - } + @Override + public IGeneralization getSourceModelElement() { + return this.sourceModelElement; + } - @Override - public String getOntoUMLType() { - return this.type; - } + @Override + public String getOntoUMLType() { + return this.type; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description);; - } + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } - public Reference getGeneral() { - return general; - } + public Reference getGeneral() { + return general; + } - public void setGeneral(Reference general) { - this.general = general; - } + public void setGeneral(Reference general) { + this.general = general; + } - public Reference getSpecific() { - return specific; - } + public Reference getSpecific() { + return specific; + } - public void setSpecific(Reference specific) { - this.specific = 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(); - } - + 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 index f85cd0b5..06fdd2d2 100644 --- 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 @@ -4,187 +4,180 @@ 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 - * + * 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; + 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())); - @SerializedName("type") - @Expose - private final String type; + 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])); + } - @SerializedName("id") - @Expose - private final String id; + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } - @SerializedName("name") - @Expose - private String name; + @Override + public String getId() { + return getSourceModelElement().getId(); + } - @SerializedName("description") - @Expose - private String description; + @Override + public IModelElement getSourceModelElement() { + return this.sourceModelElement; + } - @SerializedName("propertyAssignments") - @Expose - private JsonObject propertyAssignments; + @Override + public String getOntoUMLType() { + return type; + } - @SerializedName("categorizer") - @Expose - private Reference categorizer; + public String getName() { + return name; + } - @SerializedName("generalizations") - @Expose - private List generalizations; + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } - @SerializedName("isDisjoint") - @Expose - private boolean isDisjoint; + public String getDescription() { + return description; + } - @SerializedName("isComplete") - @Expose - private boolean isComplete; + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } - public GeneralizationSet(IGeneralizationSet source) { - this.sourceModelElement = source; + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } - this.type = ModelElement.TYPE_GENERALIZATION_SET; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } - setComplete(source.isCovering()); - setDisjoint(source.isDisjoint()); + public boolean isDisjoint() { + return 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; + public void setDisjoint(boolean isDisjoint) { + this.isDisjoint = isDisjoint; + } - this.type = ModelElement.TYPE_GENERALIZATION_SET; - this.id = source.getId(); - setName(source.getName()); - setDescription(source.getDescription()); + public boolean isComplete() { + return isComplete; + } - setComplete(source.isCovering()); - setDisjoint(source.isDisjoint()); + public void setComplete(boolean isComplete) { + this.isComplete = isComplete; + } - if (source.getPowerType() != null) - setCategorizer(new Reference(source.getPowerType())); + public Reference getCategorizer() { + return this.categorizer; + } - 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)); - } + public void setCategorizer(Reference categorizer) { + this.categorizer = categorizer; + } - @Override - public String getId() { - return getSourceModelElement().getId(); - } + public List getGeneralizations() { + return generalizations; + } - @Override - public IModelElement getSourceModelElement() { - return this.sourceModelElement; - } + public void setGeneralizations(List generalizations) { + this.generalizations = generalizations; + } - @Override - public String getOntoUMLType() { - return type; - } + public void addGeneralization(Reference ref) { + if (this.generalizations == null) this.generalizations = new ArrayList(); - 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); - } + 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 index 2fc3b757..649901b2 100644 --- 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 @@ -1,4 +1,4 @@ - package it.unibz.inf.ontouml.vp.model.uml; +package it.unibz.inf.ontouml.vp.model.uml; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; @@ -7,74 +7,74 @@ 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 + 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 index 2ad8eeb0..fb0cf77c 100644 --- 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 @@ -1,10 +1,5 @@ package it.unibz.inf.ontouml.vp.model.uml; -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; @@ -20,368 +15,347 @@ 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); - } + 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 List getElements() { - return contents; - } + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } - public void setElements(List elementsList) { - this.contents = elementsList; - } + public String getDescription() { + return description; + } - public void addElement(ModelElement element) { - if (this.contents == null) - this.contents = new ArrayList(); + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + } - this.contents.add(element); - } + public List getElements() { + return contents; + } - public boolean removeElement(ModelElement element) { - return this.contents.remove(element); - } + public void setElements(List elementsList) { + this.contents = elementsList; + } - private void addModelElement(IModelElement projectElement, HashSet idElements) { + public void addElement(ModelElement element) { + if (this.contents == null) this.contents = new ArrayList(); - switch (projectElement.getModelType()) { - case IModelElementFactory.MODEL_TYPE_PACKAGE: - addElement(new Package((IPackage) projectElement, idElements)); - break; + this.contents.add(element); + } - case IModelElementFactory.MODEL_TYPE_MODEL: - addElement(new Model((IModel) projectElement, idElements)); - break; + public boolean removeElement(ModelElement element) { + return this.contents.remove(element); + } - case IModelElementFactory.MODEL_TYPE_CLASS: - addElement(new Class((IClass) projectElement, idElements)); - break; + private void addModelElement(IModelElement projectElement, HashSet idElements) { - case IModelElementFactory.MODEL_TYPE_DATA_TYPE: - addElement(new Class((IDataType) projectElement)); - break; + switch (projectElement.getModelType()) { + case IModelElementFactory.MODEL_TYPE_PACKAGE: + addElement(new Package((IPackage) projectElement, idElements)); + break; - case IModelElementFactory.MODEL_TYPE_GENERALIZATION: - IGeneralization gen = (IGeneralization) projectElement; - IModelElement fromElement = gen.getFrom(); + case IModelElementFactory.MODEL_TYPE_MODEL: + addElement(new Model((IModel) projectElement, idElements)); + break; - if (fromElement == null) - break; + case IModelElementFactory.MODEL_TYPE_CLASS: + addElement(new Class((IClass) projectElement, idElements)); + break; - String fromType = fromElement.getModelType(); + case IModelElementFactory.MODEL_TYPE_DATA_TYPE: + addElement(new Class((IDataType) projectElement)); + break; - if (fromType == null) - break; + case IModelElementFactory.MODEL_TYPE_GENERALIZATION: + IGeneralization gen = (IGeneralization) projectElement; + IModelElement fromElement = gen.getFrom(); - boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + if (fromElement == null) break; - if (!isFromClass && !isFromAssociation) - break; + String fromType = fromElement.getModelType(); - IModelElement toElement = gen.getTo(); + if (fromType == null) break; - if (toElement == null) - break; + boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - String toType = toElement.getModelType(); + if (!isFromClass && !isFromAssociation) break; - if (toType == null) - break; + IModelElement toElement = gen.getTo(); - boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + if (toElement == null) break; - if (!isToClass && !isToAssociation) - break; + String toType = toElement.getModelType(); - addElement(new Generalization((IGeneralization) projectElement)); - break; + if (toType == null) break; - case IModelElementFactory.MODEL_TYPE_ASSOCIATION: - addElement(new Association((IAssociation) projectElement, idElements)); - break; + boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: - addElement(new GeneralizationSet((IGeneralizationSet) projectElement, idElements)); - break; + if (!isToClass && !isToAssociation) break; - case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: - addElement(new AssociationClass((IAssociationClass) projectElement)); - } - } + addElement(new Generalization((IGeneralization) projectElement)); + break; - private void addModelElements(IModelElement[] modelElements, HashSet idElements) { - for (int i = 0; modelElements != null && i < modelElements.length; i++) { - final IModelElement projectElement = modelElements[i]; + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + addElement(new Association((IAssociation) projectElement, idElements)); + break; - if (!idElements.contains(projectElement.getId())) - continue; + case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: + addElement(new GeneralizationSet((IGeneralizationSet) projectElement, idElements)); + break; - addModelElement(projectElement, idElements); + 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]; - private void addModelElements(IModelElement[] modelElements) { - for (int i = 0; modelElements != null && i < modelElements.length; i++) { - final IModelElement projectElement = modelElements[i]; + if (!idElements.contains(projectElement.getId())) continue; - switch (projectElement.getModelType()) { - case IModelElementFactory.MODEL_TYPE_PACKAGE: - addElement(new Package((IPackage) projectElement)); - break; + addModelElement(projectElement, idElements); + } + } - case IModelElementFactory.MODEL_TYPE_MODEL: - addElement(new Model((IModel) projectElement)); - break; + private void addModelElements(IModelElement[] modelElements) { + for (int i = 0; modelElements != null && i < modelElements.length; i++) { + final IModelElement projectElement = modelElements[i]; - case IModelElementFactory.MODEL_TYPE_CLASS: - addElement(new Class((IClass) projectElement)); - break; + switch (projectElement.getModelType()) { + case IModelElementFactory.MODEL_TYPE_PACKAGE: + addElement(new Package((IPackage) projectElement)); + break; - case IModelElementFactory.MODEL_TYPE_DATA_TYPE: - addElement(new Class((IDataType) projectElement)); - break; + case IModelElementFactory.MODEL_TYPE_MODEL: + addElement(new Model((IModel) projectElement)); + break; - case IModelElementFactory.MODEL_TYPE_GENERALIZATION: - IGeneralization gen = (IGeneralization) projectElement; - IModelElement fromElement = gen.getFrom(); + case IModelElementFactory.MODEL_TYPE_CLASS: + addElement(new Class((IClass) projectElement)); + break; - if (fromElement == null) - break; + case IModelElementFactory.MODEL_TYPE_DATA_TYPE: + addElement(new Class((IDataType) projectElement)); + break; - String fromType = fromElement.getModelType(); + case IModelElementFactory.MODEL_TYPE_GENERALIZATION: + IGeneralization gen = (IGeneralization) projectElement; + IModelElement fromElement = gen.getFrom(); - if (fromType == null) - break; + if (fromElement == null) break; - boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + String fromType = fromElement.getModelType(); - if (!isFromClass && !isFromAssociation) - break; + if (fromType == null) break; - IModelElement toElement = gen.getTo(); + boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - if (toElement == null) - break; + if (!isFromClass && !isFromAssociation) break; - String toType = toElement.getModelType(); + IModelElement toElement = gen.getTo(); - if (toType == null) - break; + if (toElement == null) break; - boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + String toType = toElement.getModelType(); - if (!isToClass && !isToAssociation) - break; + if (toType == null) break; - addElement(new Generalization((IGeneralization) projectElement)); - break; + boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - case IModelElementFactory.MODEL_TYPE_ASSOCIATION: - addElement(new Association((IAssociation) projectElement)); - break; + if (!isToClass && !isToAssociation) break; - case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: - addElement(new GeneralizationSet((IGeneralizationSet) projectElement)); - break; + addElement(new Generalization((IGeneralization) projectElement)); + break; - case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: - addElement(new AssociationClass((IAssociationClass) projectElement)); - } - } - } + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + addElement(new Association((IAssociation) projectElement)); + break; - private static boolean containsDiagramModel(HashSet idElements) { - final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + case IModelElementFactory.MODEL_TYPE_GENERALIZATION_SET: + addElement(new GeneralizationSet((IGeneralizationSet) projectElement)); + break; - Iterator ite = idElements.iterator(); + case IModelElementFactory.MODEL_TYPE_ASSOCIATION_CLASS: + addElement(new AssociationClass((IAssociationClass) projectElement)); + } + } + } - while (ite.hasNext()) { - String id = ite.next(); + private static boolean containsDiagramModel(HashSet idElements) { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); - if (project.getDiagramById(id) == null) - continue; - else - return true; + Iterator ite = idElements.iterator(); - } + while (ite.hasNext()) { + String id = ite.next(); - return false; - } + if (project.getDiagramById(id) == null) continue; + else return true; + } -} \ No newline at end of file + 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 index aefff2fc..2f94735a 100644 --- 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 @@ -3,16 +3,24 @@ 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 @@ -20,213 +28,399 @@ */ 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; + 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; } - 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()); - } + 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; + if (obj.size() == 0) return null; - return obj; - } + return obj; + } - public static boolean getIsDerived(IModelElement element) { - return element.getName().trim().startsWith("/"); - } + public static boolean isAbstract(IModelElement element) { + final String elementType = element.getModelType(); - public static void setIsDerived(IModelElement element, boolean isDerived) { - final String currentName = element.getName() != null ? - element.getName().trim() : ""; + switch (elementType) { + case IModelElementFactory.MODEL_TYPE_ASSOCIATION: + return ((IAssociation) element).isAbstract(); - if (getIsDerived(element)) { - element.setName(currentName.substring(1)); - } else { - element.setName("/" + currentName); - } - } + 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; + } -} \ No newline at end of file + 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 index 806862b8..e1b1fb04 100644 --- 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 @@ -5,7 +5,6 @@ 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; @@ -17,206 +16,197 @@ * @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; - } + 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)); - } + 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()); + 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(); + IModelElement[] childArray = source.toChildArray(); - if (childArray == null) - return; + if (childArray == null) return; - for (int i = 0; i < childArray.length; i++) { - if (idElements.contains(childArray[i].getId())) { - addModelElement(childArray[i], idElements); - } + for (int i = 0; i < childArray.length; i++) { + if (idElements.contains(childArray[i].getId())) { + addModelElement(childArray[i], idElements); } + } - setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); - } + setPropertyAssignments(ModelElement.transformPropertyAssignments(source)); + } - @Override - public IPackage getSourceModelElement() { - return sourceModelElement; - } + @Override + public IPackage getSourceModelElement() { + return sourceModelElement; + } - @Override - public String getId() { - return getSourceModelElement().getId(); - } + @Override + public String getId() { + return getSourceModelElement().getId(); + } - @Override - public String getOntoUMLType() { - return this.type; - } + @Override + public String getOntoUMLType() { + return this.type; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = ModelElement.safeGetString(name); - } + public void setName(String name) { + this.name = ModelElement.safeGetString(name); + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = ModelElement.safeGetString(description); - ; - } + public void setDescription(String description) { + this.description = ModelElement.safeGetString(description); + ; + } - public JsonObject getPropertyAssignments() { - return propertyAssignments; - } + public JsonObject getPropertyAssignments() { + return propertyAssignments; + } - public void setPropertyAssignments(JsonObject propertyAssignments) { - this.propertyAssignments = propertyAssignments; - } + public void setPropertyAssignments(JsonObject propertyAssignments) { + this.propertyAssignments = propertyAssignments; + } - public LinkedList getContents() { - return contents; - } + public LinkedList getContents() { + return contents; + } - public void setContents(LinkedList contents) { - this.contents = contents; - } + public void setContents(LinkedList contents) { + this.contents = contents; + } - public void addElement(ModelElement element) { - if (getContents() == null) { - setContents(new LinkedList()); - } + public void addElement(ModelElement element) { + if (getContents() == null) { + setContents(new LinkedList()); + } - this.contents.add(element); - } + this.contents.add(element); + } - private void addModelElement(IModelElement projectElement, HashSet idElements) { + private void addModelElement(IModelElement projectElement, HashSet idElements) { - switch (projectElement.getModelType()) { - case IModelElementFactory.MODEL_TYPE_PACKAGE: - addElement(new Package((IPackage) projectElement, idElements)); - break; + 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_MODEL: + addElement(new Model((IModel) projectElement, idElements)); + break; - case IModelElementFactory.MODEL_TYPE_CLASS: - addElement(new Class((IClass) 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_DATA_TYPE: + addElement(new Class((IDataType) projectElement)); + break; - case IModelElementFactory.MODEL_TYPE_GENERALIZATION: - IGeneralization gen = (IGeneralization) projectElement; - IModelElement fromElement = gen.getFrom(); + case IModelElementFactory.MODEL_TYPE_GENERALIZATION: + IGeneralization gen = (IGeneralization) projectElement; + IModelElement fromElement = gen.getFrom(); - if (fromElement == null) - break; + if (fromElement == null) break; - String fromType = fromElement.getModelType(); + String fromType = fromElement.getModelType(); - if (fromType == null) - break; + if (fromType == null) break; - boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + boolean isFromClass = fromType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isFromAssociation = fromType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - if (!isFromClass && !isFromAssociation) - break; + if (!isFromClass && !isFromAssociation) break; - IModelElement toElement = gen.getTo(); + IModelElement toElement = gen.getTo(); - if (toElement == null) - break; + if (toElement == null) break; - String toType = toElement.getModelType(); + String toType = toElement.getModelType(); - if (toType == null) - break; + if (toType == null) break; - boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); - boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); + boolean isToClass = toType.equals(IModelElementFactory.MODEL_TYPE_CLASS); + boolean isToAssociation = toType.equals(IModelElementFactory.MODEL_TYPE_ASSOCIATION); - if (!isToClass && !isToAssociation) - break; + if (!isToClass && !isToAssociation) break; - addElement(new Generalization((IGeneralization) projectElement)); - break; + addElement(new Generalization((IGeneralization) projectElement)); + break; - case IModelElementFactory.MODEL_TYPE_ASSOCIATION: - addElement(new Association((IAssociation) projectElement, idElements)); - 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)); - } - } + 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 index 1efc0e14..c3b221e2 100644 --- 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 @@ -3,383 +3,453 @@ 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.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 - * + * 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); + 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); + ; + } - 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 Reference getPropertyType() { + return propertyType; + } - public void setDerived(boolean isDerived) { - this.isDerived = isDerived; - } + public void setPropertyType(Reference propertyType) { + this.propertyType = propertyType; + } - 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 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 index a88a154e..25eb1d9e 100644 --- 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 @@ -5,41 +5,37 @@ 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. - * + * 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 + @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 index bf891917..519a15f6 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/ActionIdManager.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/ActionIdManager.java @@ -2,207 +2,324 @@ 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 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 StereotypesManager.STR_TYPE: - return TYPE; - case StereotypesManager.STR_HISTORICAL_ROLE: - return HISTORICAL_ROLE; - case StereotypesManager.STR_HISTORICAL_ROLE_MIXIN: - return HISTORICAL_ROLE_MIXIN; - case StereotypesManager.STR_EVENT: - return EVENT; - case StereotypesManager.STR_SITUATION: - return SITUATION; - case StereotypesManager.STR_CATEGORY: - return CATEGORY; - case StereotypesManager.STR_MIXIN: - return MIXIN; - case StereotypesManager.STR_ROLE_MIXIN: - return ROLE_MIXIN; - case StereotypesManager.STR_PHASE_MIXIN: - return PHASE_MIXIN; - case StereotypesManager.STR_KIND: - return KIND; - case StereotypesManager.STR_COLLECTIVE: - return COLLECTIVE; - case StereotypesManager.STR_QUANTITY: - return QUANTITY; - case StereotypesManager.STR_RELATOR: - return RELATOR; - case StereotypesManager.STR_QUALITY: - return QUALITY; - case StereotypesManager.STR_MODE: - return MODE; - case StereotypesManager.STR_SUBKIND: - return SUBKIND; - case StereotypesManager.STR_ROLE: - return ROLE; - case StereotypesManager.STR_PHASE: - return PHASE; - case StereotypesManager.STR_ENUMERATION: - return ENUMERATION; - case StereotypesManager.STR_DATATYPE: - return DATATYPE; - default: - return null; - } - } - - public static String associationStereotypeToActionID(String stereotype) { - switch(stereotype) { - case StereotypesManager.STR_INSTANTIATION: - return INSTANTIATION; - case StereotypesManager.STR_TERMINATION: - return TERMINATION; - case StereotypesManager.STR_PARTICIPATIONAL: - return PARTICIPATIONAL; - case StereotypesManager.STR_PARTICIPATION: - return PARTICIPATION; - case StereotypesManager.STR_HISTORICAL_DEPENDENCE: - return HISTORICAL_DEPENDENCE; - case StereotypesManager.STR_CREATION: - return CREATION; - case StereotypesManager.STR_MANIFESTATION: - return MANIFESTATION; - case StereotypesManager.STR_BRINGS_ABOUT: - return BRINGS_ABOUT; - case StereotypesManager.STR_TRIGGERS: - return TRIGGERS; - case StereotypesManager.STR_SUB_QUANTITY_OF: - return SUB_QUANTITY_OF; - case StereotypesManager.STR_SUB_COLLECTION_OF: - return SUB_COLLECTION_OF; - case StereotypesManager.STR_MEMBER_OF: - return MEMBER_OF; - case StereotypesManager.STR_MEDIATION: - return MEDIATION; - case StereotypesManager.STR_MATERIAL: - return MATERIAL; - case StereotypesManager.STR_EXTERNAL_DEPENDENCE: - return EXTERNAL_DEPENDENCE; - case StereotypesManager.STR_COMPONENT_OF: - return COMPONENT_OF; - case StereotypesManager.STR_COMPARATIVE: - return COMPARATIVE; - case StereotypesManager.STR_CHARACTERIZATION: - return CHARACTERIZATION; - default: - return null; - } - } + // 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/OntoUMLConstraintsManager.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLConstraintsManager.java index 63667d24..4edacbe0 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLConstraintsManager.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/OntoUMLConstraintsManager.java @@ -1,5 +1,15 @@ 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; @@ -9,102 +19,125 @@ import java.util.Map; import java.util.stream.Collectors; -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; +public class OntoUMLConstraintsManager { -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; + private static final Type mapOfListsType = + new TypeToken>>() {}.getType(); -public class OntoUMLConstraintsManager { + 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()); + } + } - final private static Type mapOfListsType = new TypeToken>>() {}.getType(); - - private static String GENERALIZATION_CONSTRAINTS_FILENAME = "generalization_constraints.json"; - private static String ASSOCIATION_CONSTRAINTS_FILENAME = "association_constraints.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 getAllowedStereotypeActionsOnGeneral(String stereotype) { - if(allowedSuperClassesFor == null || allowedSubClassesFor == null) { - loadConstraints(); - } - - List allowedStereotypes = allowedSubClassesFor.get(stereotype); - - if(allowedStereotypes == null) { - allowedStereotypes = new ArrayList(); - } - - return allowedStereotypes - .stream() - .map(allowed -> ActionIdManager.classStereotypeToActionID(allowed)) - .collect(Collectors.toList()); - } - - public static List getAllowedStereotypeActionsSpecific(String stereotype) { - if(allowedSuperClassesFor == null || allowedSubClassesFor == null) { - loadConstraints(); - } - - List allowedStereotypes = allowedSuperClassesFor.get(stereotype); - - if(allowedStereotypes == null) { - allowedStereotypes = new ArrayList(); - } - - return allowedStereotypes - .stream() - .map(allowed -> ActionIdManager.classStereotypeToActionID(allowed)) - .collect(Collectors.toList()); - } - - - public static List getAllowedStereotypeActionsOnAssociation(String sourceStereotype, String targetStereotype) { - if(associationConstraints == null) { - loadConstraints(); - } - - List allowedStereotypes = associationConstraints.get(sourceStereotype + ":" + targetStereotype); - - if(allowedStereotypes == null) { - allowedStereotypes = new ArrayList(); - } - - return allowedStereotypes - .stream() - .map(allowed -> ActionIdManager.associationStereotypeToActionID(allowed)) - .collect(Collectors.toList()); - } - -} \ No newline at end of file + return intersectingAllowedStereotypes.stream() + .map( + allowedStereotype -> ActionIdManager.associationStereotypeToActionID(allowedStereotype)) + .collect(Collectors.toList()); + } +} 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/SmartColoringUtils.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoringUtils.java index 841cc2d9..40f2e50e 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoringUtils.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/SmartColoringUtils.java @@ -1,17 +1,16 @@ 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.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 @@ -22,123 +21,134 @@ */ public class SmartColoringUtils { - 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); - - /** - * 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 = StereotypesManager.getUniqueStereotypeName(_class); - String restrictedTo = Class.getRestrictedTo(_class); - - if (restrictedTo == null || restrictedTo.isEmpty()) { - final Set allStereotypes = StereotypesManager.getOntoUMLClassStereotypeNames(); - - if (!allStereotypes.contains(stereotype)) { - return null; - } else { - return COLOR_FOR_NON_SPECIFIC; - } - } - - final Set ultimateSortalStereotypes = StereotypesManager.getUltimateSortalStereotypeNames(); - - switch (restrictedTo) { - case StereotypesManager.RESTRICTED_TO_ABSTRACT: - return COLOR_FOR_ABSTRACT; - case StereotypesManager.RESTRICTED_TO_COLLECTIVE: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_COLLECTIVE_DARK : COLOR_FOR_COLLECTIVE; - case StereotypesManager.RESTRICTED_TO_EVENT: - return COLOR_FOR_EVENT; - case StereotypesManager.RESTRICTED_TO_SITUATION: - return COLOR_FOR_SITUATION; - case StereotypesManager.RESTRICTED_TO_MODE: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_MODE_DARK : COLOR_FOR_MODE; - case StereotypesManager.RESTRICTED_TO_FUNCTIONAL_COMPLEX: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_FUNCTIONAL_COMPLEX_DARK - : COLOR_FOR_FUNCTIONAL_COMPLEX; - case StereotypesManager.RESTRICTED_TO_QUALITY: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_QUALITY_DARK : COLOR_FOR_QUALITY; - case StereotypesManager.RESTRICTED_TO_QUANTITY: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_QUANTITY_DARK : COLOR_FOR_QUANTITY; - case StereotypesManager.RESTRICTED_TO_RELATOR: - return ultimateSortalStereotypes.contains(stereotype) ? COLOR_FOR_RELATOR_DARK : COLOR_FOR_RELATOR; - case StereotypesManager.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(StereotypesManager.RESTRICTED_TO_FUNCTIONAL_COMPLEX, - StereotypesManager.RESTRICTED_TO_COLLECTIVE, StereotypesManager.RESTRICTED_TO_QUANTITY); - - if (objectNatures.containsAll(restrictedToList)) { - return COLOR_FOR_FUNCTIONAL_COMPLEX; - } - - final List intrinsicNature = Arrays.asList(StereotypesManager.RESTRICTED_TO_MODE, - StereotypesManager.RESTRICTED_TO_QUALITY); - - if (intrinsicNature.containsAll(restrictedToList)) { - return COLOR_FOR_MODE; - } - - return COLOR_FOR_NON_SPECIFIC; - } + 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/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/StereotypesManager.java b/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypesManager.java index f4cd32b7..abe9899b 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypesManager.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/StereotypesManager.java @@ -1,14 +1,5 @@ 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; @@ -19,548 +10,293 @@ 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 { - 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); - } + 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 : 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); - } + } + + // 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(); - 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); - } + if (definitionsContainer == null) { + definitionsContainer = + IModelElementFactory.instance().createTaggedValueDefinitionContainer(); } - 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); - } + 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]); } - // 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); + // Removes deprecated references to "allowed" + if (definitions.containsKey("allowed")) { + final ITaggedValueDefinition allowed = definitions.get("allowed"); + allowed.delete(); } - // 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); - - if (stereotype == null || !element.getModelType().equals(stereotype.getBaseType())){ - return; + // 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); } - 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()); - } + // 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); } - IModelElementFactory factory = IModelElementFactory.instance(); - ITaggedValueContainer container = element.getTaggedValues(); - Map taggedValueMap = new HashMap<>(); + // 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); + } - if (container == null) { - container = factory.createTaggedValueContainer(); - element.setTaggedValues(container); + // 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); } - 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(); - } - } + stereotype.setTaggedValueDefinitions(definitionsContainer); + } - } + System.out.println("KEYS: " + stereotypesMap.keySet()); - // 2. Removes old stereotypes - if (element.stereotypeCount() > 0) { - for (IStereotype s : element.toStereotypeModelArray()) { - element.removeStereotype(s); - } - } + // 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; + } - // 3. Adds new stereotype - element.addStereotype(stereotype); + public static void applyStereotype(IModelElement element, String stereotypeName) { + final IStereotype stereotype = getStereotype(stereotypeName); - // 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(); + if (stereotype == null || !element.getModelType().equals(stereotype.getBaseType())) { + return; + } - for (ITaggedValue taggedValue : taggedValues) { - Object oldValue = taggedValueMap.get(taggedValue.getName()); - if (oldValue != null) { - taggedValue.setValue(oldValue.toString()); - } - } + 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(); + } + } + } - System.out.println("Number of tagged values: " + count); + // 2. Removes old stereotypes + if (element.stereotypeCount() > 0) { + for (IStereotype s : element.toStereotypeModelArray()) { + element.removeStereotype(s); } - } - - 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 ""; + } + + // 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()); + } } - } - public static ITaggedValue reapplyStereotypeAndGetTaggedValue(IClass _class, String taggedValueName) { - reapplyCurrentStereotype(_class); + System.out.println("Number of tagged values: " + count); + } + } - ITaggedValue taggedValue = getTaggedValue(_class, taggedValueName); - if (taggedValue == null) - return null; + public static ITaggedValue reapplyStereotypeAndGetTaggedValue( + IClass _class, String taggedValueName) { + reapplyCurrentStereotype(_class); - //Retrieves desired tagged value - return getTaggedValue(_class, taggedValueName); - } + ITaggedValue taggedValue = getTaggedValue(_class, taggedValueName); + if (taggedValue == null) return null; - public static boolean reapplyCurrentStereotype(IClass _class) { - String stereotype = _class.toStereotypeArray() != null && _class.toStereotypeArray().length > 0 ? - _class.toStereotypeArray()[0] : null; + // Retrieves desired tagged value + return getTaggedValue(_class, taggedValueName); + } - // Escape in case the stereotype is missing or incorrect - if (stereotype == null || !getOntoUMLClassStereotypeNames().contains(stereotype)) - return false; + private static boolean reapplyCurrentStereotype(IClass _class) { + String stereotype = + _class.toStereotypeArray() != null && _class.toStereotypeArray().length > 0 + ? _class.toStereotypeArray()[0] + : null; - System.out.println("Reapplying " + stereotype + " to " + _class.getName()); - // Reapply stereotype making sure that the tagged values are there - applyStereotype(_class, stereotype); + // Escape in case the stereotype is missing or incorrect + if (stereotype == null || !Stereotype.getOntoUMLClassStereotypeNames().contains(stereotype)) + return false; - return true; - } + System.out.println("Reapplying " + stereotype + " to " + _class.getName()); + // Reapply stereotype making sure that the tagged values are there + applyStereotype(_class, stereotype); - public static ITaggedValue getTaggedValue(IModelElement element, String name) { - ITaggedValueContainer container = element.getTaggedValues(); + return true; + } - if (container == null) - return null; + private static ITaggedValue getTaggedValue(IModelElement element, String name) { + ITaggedValueContainer container = element.getTaggedValues(); - try { - return container.getTaggedValueByName(name); - } catch (Exception e) { - return null; - } - } + if (container == null) return null; - public static void deleteTaggedValue(IModelElement element, String name) { - ITaggedValueContainer container = element.getTaggedValues(); + try { + return container.getTaggedValueByName(name); + } catch (Exception e) { + return null; + } + } - 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); - } + private static IStereotype getStereotype(String stereotypeName) { + IStereotype stereotype = + STEREOTYPE_ELEMENTS != null ? STEREOTYPE_ELEMENTS.get(stereotypeName) : null; - return stereotype; - } + if (stereotype == null && Stereotype.getOntoUMLStereotypeNames().contains(stereotypeName)) { + generate(); + stereotype = STEREOTYPE_ELEMENTS.get(stereotypeName); + } -} \ No newline at end of file + 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 index a0f86f53..0f2fdabb 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/utils/ViewManagerUtils.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/utils/ViewManagerUtils.java @@ -1,27 +1,5 @@ package it.unibz.inf.ontouml.vp.utils; -import java.awt.FileDialog; -import java.awt.Frame; -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.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JScrollPane; - import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -35,572 +13,760 @@ 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. - * + * 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); - } - } - - 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 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(); - } - - ViewManagerUtils.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 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("\nIf you desire to install a different version of the plugin, click on \"Select release\"."); - msg.append("\nBe 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( - "\nTo install this update, click on \"Install latest release\", or click on \"Select a release\" to install a different version."); - msg.append("\nBe 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.\nPlease 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))); - } - - public 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 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/views/ConfigurationsView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/ConfigurationsView.java index d3486a2d..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.model.Configurations; import it.unibz.inf.ontouml.vp.model.ProjectConfigurations; - -import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; 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/GUFOExportView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/GUFOExportView.java index d6dedca9..da0d4b2f 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/GUFOExportView.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/GUFOExportView.java @@ -1,5 +1,22 @@ 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; @@ -11,7 +28,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Vector; - import javax.swing.DefaultCellEditor; import javax.swing.JButton; import javax.swing.JComboBox; @@ -27,1017 +43,962 @@ 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.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; - 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) { + 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) { + } + }); + + 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; - } + } + }); + + 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()); + } + } + } + } - private static String[] getLanguagesCode() { + public HashSet getSavedElements() { - 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"}; - } + if (tabbedPane.getSelectedIndex() == 0) return elementsPackageTree; + else return elementsDiagramTree; + } - /** - * Sets a direct reference to the container dialog after initialization. - */ - public void setContainerDialog(IDialog dialog) { - this._dialog = dialog; - } + public String getTableElementMapping() { + HashMap>> results = + new HashMap>>(); + String elementId = ""; - /** - * 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()); + for (int row = 0; row < table.getRowCount(); row++) { - if (tabbedPane.getSelectedIndex() == 0) - configurations.setExportGUFOElementsPackageTree(elementsPackageTree); - else - configurations.setExportGUFOElementsDiagramTree(elementsDiagramTree); - } + HashMap content; + HashMap> label; - /** - * Updates components with project configurations' information. - * - * @param configurations - */ - private void updateComponentsValues(ProjectConfigurations configurations) { + String element = table.getValueAt(row, 0).toString(); + String language = table.getValueAt(row, 1).toString(); + String text = table.getValueAt(row, 2).toString(); - if (configurations.getExportGUFOIRI() != null && !configurations.getExportGUFOIRI().equals("")) - IRItxt.setText(configurations.getExportGUFOIRI()); + for (IModelElement iModelElement : elementsMapping) { - if (configurations.getExportGUFOFormat() != null && !configurations.getExportGUFOFormat().equals("")) - formatBox.setSelectedItem(configurations.getExportGUFOFormat()); + if (iModelElement.getName() == null) continue; - 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; + if (iModelElement.getName().equals(element)) { + elementId = iModelElement.getId(); + } } - for (TreePath path : paths) { - Object[] object = path.getPath(); - for (Object o : object) { - - if (o instanceof DefaultMutableTreeNode) { + if (!results.containsKey(elementId)) { + label = new HashMap>(); + content = new HashMap(); + label.put("label", content); + results.put(elementId, label); - 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()); - } - } + } else { + label = results.get(elementId); + content = label.get("label"); } - } - - public HashSet getSavedElements() { + content.put(language, text); + } - if (tabbedPane.getSelectedIndex() == 0) - return elementsPackageTree; - else - return elementsDiagramTree; - } + Gson gson = new Gson(); + String json = gson.toJson(results); - public String getTableElementMapping() { - HashMap>> results = new HashMap>>(); - String elementId = ""; + JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); - for (int row = 0; row < table.getRowCount(); row++) { + return convertedObject.toString(); + } - HashMap content; - HashMap> label; + public String getTablePackageMapping() { + final IProject project = ApplicationManager.instance().getProjectManager().getProject(); + HashMap> results = new HashMap<>(); + String elementId = ""; - String element = table.getValueAt(row, 0).toString(); - String language = table.getValueAt(row, 1).toString(); - String text = table.getValueAt(row, 2).toString(); + for (int row = 0; row < table2.getRowCount(); row++) { + HashMap content; - for (IModelElement iModelElement : elementsMapping) { + String packages = table2.getValueAt(row, 0).toString(); + String prefix = table2.getValueAt(row, 1).toString(); + String uri = table2.getValueAt(row, 2).toString(); - if (iModelElement.getName() == null) - continue; + for (IModelElement element : packagesMapping) { - 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); + if (element.getName() == null) continue; + if (element.getName().equals(packages)) elementId = element.getId(); } - 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(); + if (project.getName().equals(packages)) elementId = project.getId(); - 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); + if (!results.containsKey(elementId)) { + content = new HashMap<>(); + content.put("prefix", prefix); + content.put("uri", uri); + } else { + content = results.get(elementId); } - Gson gson = new Gson(); - String json = gson.toJson(results); - - JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); - - return convertedObject.toString(); + results.put(elementId, content); + content.put("prefix", prefix); + content.put("uri", uri); + } - } + Gson gson = new Gson(); + String json = gson.toJson(results); - public static String getDisplayName(Object obj) { - if (obj == null) - return ""; + JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); - if (obj instanceof String) - return obj.toString(); + return convertedObject.toString(); + } - if (obj instanceof IDiagramUIModel) { - IDiagramUIModel diagram = (IDiagramUIModel) obj; + public static String getDisplayName(Object obj) { + if (obj == null) return ""; - return diagram.getName() != null ? diagram.getName() : "Diagram"; - } + if (obj instanceof String) return obj.toString(); - if (obj instanceof IAttribute) { - IAttribute attribute = (IAttribute) obj; + if (obj instanceof IDiagramUIModel) { + IDiagramUIModel diagram = (IDiagramUIModel) obj; - String attributeName = attribute.getName() != null ? attribute.getName() : ""; + return diagram.getName() != null ? diagram.getName() : "Diagram"; + } - String attributeType = ""; - if (attribute.getType() != null) - attributeType = attribute.getTypeAsString(); + if (obj instanceof IAttribute) { + IAttribute attribute = (IAttribute) obj; - return attributeName + " : " + attributeType; - } + String attributeName = attribute.getName() != null ? attribute.getName() : ""; - if (obj instanceof IAssociation) { - IAssociation association = (IAssociation) obj; - String assocName = ""; + String attributeType = ""; + if (attribute.getType() != null) attributeType = attribute.getTypeAsString(); - if (association.getName() != null && !association.getName().equals("")) - assocName = association.getName() + " "; + return attributeName + " : " + attributeType; + } - String nameFrom = association.getFrom() == null ? "" : association.getFrom().getName(); - String nameTo = association.getTo() == null ? "" : association.getTo().getName(); + if (obj instanceof IAssociation) { + IAssociation association = (IAssociation) obj; + String assocName = ""; - return assocName + "(" + nameFrom + " -> " + nameTo + ")"; - } + if (association.getName() != null && !association.getName().equals("")) + assocName = association.getName() + " "; - if (obj instanceof IAssociationEnd) { - IAssociationEnd assocEnd = (IAssociationEnd) obj; + String nameFrom = association.getFrom() == null ? "" : association.getFrom().getName(); + String nameTo = association.getTo() == null ? "" : association.getTo().getName(); - String endName = assocEnd.getName() != null ? assocEnd.getName() : ""; - String typeName = assocEnd.getType() != null ? assocEnd.getTypeAsString() : ""; + return assocName + "(" + nameFrom + " -> " + nameTo + ")"; + } - return endName + " : " + typeName; - } + if (obj instanceof IAssociationEnd) { + IAssociationEnd assocEnd = (IAssociationEnd) obj; - if (obj instanceof IGeneralization) { - IGeneralization generalization = (IGeneralization) obj; + String endName = assocEnd.getName() != null ? assocEnd.getName() : ""; + String typeName = assocEnd.getType() != null ? assocEnd.getTypeAsString() : ""; - String childTypeName = generalization.getTo() != null ? generalization.getTo().getName() : ""; - String parentTypeName = generalization.getFrom() != null ? generalization.getFrom().getName() : ""; + return endName + " : " + typeName; + } - return "(" + childTypeName + " -> " + parentTypeName + ")"; - } + if (obj instanceof IGeneralization) { + IGeneralization generalization = (IGeneralization) obj; - if (obj instanceof IAssociationClass) { - IAssociationClass assocClass = (IAssociationClass) obj; + String childTypeName = generalization.getTo() != null ? generalization.getTo().getName() : ""; + String parentTypeName = + generalization.getFrom() != null ? generalization.getFrom().getName() : ""; - String nameFrom = assocClass.getFrom() != null ? assocClass.getFrom().getName() : ""; - String nameTo = assocClass.getTo() != null ? assocClass.getTo().getName() : ""; + return "(" + childTypeName + " -> " + parentTypeName + ")"; + } - return "(" + nameFrom + " -> " + nameTo + ")"; + if (obj instanceof IAssociationClass) { + IAssociationClass assocClass = (IAssociationClass) obj; - } + String nameFrom = assocClass.getFrom() != null ? assocClass.getFrom().getName() : ""; + String nameTo = assocClass.getTo() != null ? assocClass.getTo().getName() : ""; - if (obj instanceof IModelElement) { - IModelElement element = (IModelElement) obj; - return element.getName() != null ? element.getName() : "ModelElement " + element.getId(); - } + return "(" + nameFrom + " -> " + nameTo + ")"; + } - return "Element"; - } + 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 2ea52a61..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,56 +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 javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; -import it.unibz.inf.ontouml.vp.utils.ViewManagerUtils; - 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) { - ViewManagerUtils.reportBugErrorDialog(true); - unsupportedException.printStackTrace(); - } catch (SecurityException securityException) { - ViewManagerUtils.reportBugErrorDialog(true); - securityException.printStackTrace(); - } catch(Exception exception) { - ViewManagerUtils.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 index b721214a..ced9b926 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/IssueLogMenu.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/IssueLogMenu.java @@ -1,60 +1,63 @@ package it.unibz.inf.ontouml.vp.views; -import javax.swing.*; - 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; - } - } + 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 32377a0c..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,940 +43,954 @@ 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.ViewManagerUtils; - 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(); - - // 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); - - 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))); - - checkBox.setSelected(cn.isSelected); - checkBox.setText(getNameNode(node)); - - checkBox.setOpaque(cn.isSelected && cn.hasChildren && !cn.allChildrenSelected); - - return this; - } - - } - - private String getNameNode(ElementNode node) { - return GUFOExportView.getDisplayName(node.getUserObject()); - } - - 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); - - DefaultTreeSelectionModel dtsm = new DefaultTreeSelectionModel() { - private static final long serialVersionUID = -8190634240451667286L; - - public void setSelectionPath(TreePath path) { - boolean checkMode = !nodesCheckingState.get(path).isSelected; - checkSubTree(path, checkMode); - updatePredecessorsWithCheckMode(path, checkMode); - // Firing the check change event - fireCheckChangeEvent(new CheckChangeEvent(new Object())); - // Repainting tree after the data structures were updated - findSimilarNodes((ElementNode) path.getLastPathComponent()); - - selectTypeNodes((ElementNode) path.getLastPathComponent()); - - if (((ElementNode) path.getLastPathComponent()).getUserObject() instanceof IGeneralizationSet) - selectAllGeneralizationsFromSet((ElementNode) path.getLastPathComponent(), checkMode); - - selfPointer.repaint(); - } - - public void addSelectionPath(TreePath path) { - } - - public void removeSelectionPath(TreePath path) { - } - - public void setSelectionPaths(TreePath[] pPaths) { - } - }; - - this.setSelectionModel(dtsm); - } - - @SuppressWarnings("unchecked") - private void visitAllNodesAndCheckSimilar(ElementNode root, ElementNode nodeToCompare) { - - // if same Object - if (((ElementNode) root).getUserObject().equals(nodeToCompare.getUserObject())) { - - TreeNode[] old_treeNode = nodeToCompare.getPath(); - TreePath oldTp = new TreePath(old_treeNode); - - TreeNode[] new_treeNode = root.getPath(); - TreePath newTp = new TreePath(new_treeNode); - - // if different paths - if (!oldTp.toString().equals(newTp.toString())) { - - boolean checkMode = nodesCheckingState.get(oldTp).isSelected; - - 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(); - - visitAllNodesAndCheckSimilar(n, nodeToCompare); - } - } - } - - @SuppressWarnings("unchecked") - private void visitAllAndCheckSameId(ElementNode root, String id, boolean checkMode) { - - if (root.getUserObject() instanceof IModelElement) { - IModelElement rootModelElement = ((IModelElement) ((DefaultMutableTreeNode) root).getUserObject()); - - // if same Object - if (rootModelElement.getId().equals(id)) { - - TreeNode[] new_treeNode = root.getPath(); - TreePath newTp = new TreePath(new_treeNode); - - CheckedNode cn = nodesCheckingState.get(newTp); - cn.isSelected = checkMode; - - if (checkMode) - checkedPaths.add(newTp); - else - checkedPaths.remove(newTp); + 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); + + 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))); + + checkBox.setSelected(cn.isSelected); + checkBox.setText(getNameNode(node)); + + checkBox.setOpaque(cn.isSelected && cn.hasChildren && !cn.allChildrenSelected); + + return this; + } + } + + private String getNameNode(ElementNode node) { + return GUFOExportView.getDisplayName(node.getUserObject()); + } + + 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); + + DefaultTreeSelectionModel dtsm = + new DefaultTreeSelectionModel() { + private static final long serialVersionUID = -8190634240451667286L; + + public void setSelectionPath(TreePath path) { + boolean checkMode = !nodesCheckingState.get(path).isSelected; + checkSubTree(path, checkMode); + updatePredecessorsWithCheckMode(path, checkMode); + // Firing the check change event + fireCheckChangeEvent(new CheckChangeEvent(new Object())); + // Repainting tree after the data structures were updated + findSimilarNodes((ElementNode) path.getLastPathComponent()); + + selectTypeNodes((ElementNode) path.getLastPathComponent()); + + if (((ElementNode) path.getLastPathComponent()).getUserObject() + instanceof IGeneralizationSet) + selectAllGeneralizationsFromSet((ElementNode) path.getLastPathComponent(), checkMode); + + selfPointer.repaint(); + } + + public void addSelectionPath(TreePath path) {} + + public void removeSelectionPath(TreePath path) {} + + public void setSelectionPaths(TreePath[] pPaths) {} + }; + + this.setSelectionModel(dtsm); + } + + private void visitAllNodesAndCheckSimilar(ElementNode root, ElementNode nodeToCompare) { - } - } + // if same Object + if (((ElementNode) root).getUserObject().equals(nodeToCompare.getUserObject())) { - if (root.getChildCount() >= 0) { - for (Enumeration e = root.children(); e.hasMoreElements();) { - ElementNode n = (ElementNode) e.nextElement(); + TreeNode[] old_treeNode = nodeToCompare.getPath(); + TreePath oldTp = new TreePath(old_treeNode); - visitAllAndCheckSameId(n, id, checkMode); - } - } - } + TreeNode[] new_treeNode = root.getPath(); + TreePath newTp = new TreePath(new_treeNode); - protected void findSimilarNodes(ElementNode node) { + // if different paths + if (!oldTp.toString().equals(newTp.toString())) { - for (int i = 0; i < node.getChildCount(); i++) - findSimilarNodes((ElementNode) node.getChildAt(i)); + boolean checkMode = nodesCheckingState.get(oldTp).isSelected; - ElementNode root = (ElementNode) this.getModel().getRoot(); - visitAllNodesAndCheckSimilar(root, node); - } + CheckedNode cn = nodesCheckingState.get(newTp); + cn.isSelected = checkMode; - @SuppressWarnings("unchecked") - private void visitAllNodesAndCheckType(ElementNode root, ElementNode nodeToCompare) { - String typeOriginal = ""; - String typeCurrentNode = ""; + if (checkMode) checkedPaths.add(newTp); + else checkedPaths.remove(newTp); + } + } - if (nodeToCompare.getUserObject() instanceof IClass) - typeOriginal = ((IClass) nodeToCompare.getUserObject()).getName(); + if (root.getChildCount() >= 0) { + for (Enumeration e = root.children(); e.hasMoreElements(); ) { + ElementNode n = (ElementNode) e.nextElement(); - if (nodeToCompare.getUserObject() instanceof IAttribute) - typeOriginal = ((IAttribute) nodeToCompare.getUserObject()).getTypeAsString(); + visitAllNodesAndCheckSimilar(n, nodeToCompare); + } + } + } - if (root.getUserObject() instanceof IClass) - typeCurrentNode = ((IClass) root.getUserObject()).getName(); + private void visitAllAndCheckSameId(ElementNode root, String id, boolean checkMode) { - if (root.getUserObject() instanceof IDataType) - typeCurrentNode = ((IDataType) root.getUserObject()).getName(); + if (root.getUserObject() instanceof IModelElement) { + IModelElement rootModelElement = + ((IModelElement) ((DefaultMutableTreeNode) root).getUserObject()); - if (typeOriginal != null && typeCurrentNode.contentEquals(typeOriginal)) { + // if same Object + if (rootModelElement.getId().equals(id)) { - TreeNode[] old_treeNode = nodeToCompare.getPath(); - TreePath oldTp = new TreePath(old_treeNode); + TreeNode[] new_treeNode = root.getPath(); + TreePath newTp = new TreePath(new_treeNode); - TreeNode[] new_treeNode = root.getPath(); - TreePath newTp = new TreePath(new_treeNode); + CheckedNode cn = nodesCheckingState.get(newTp); + cn.isSelected = checkMode; - // if different paths - if (!oldTp.toString().equals(newTp.toString())) { - boolean checkMode = nodesCheckingState.get(oldTp).isSelected; - - if ((root.getUserObject() instanceof IClass || root.getUserObject() instanceof IDataType) - && checkMode == true) { - - 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(); - - visitAllNodesAndCheckType(n, nodeToCompare); - } - } - } - - protected void selectTypeNodes(ElementNode node) { - ElementNode root = (ElementNode) this.getModel().getRoot(); - visitAllNodesAndCheckType(root, node); - } - - protected void selectAllGeneralizationsFromSet(ElementNode node, boolean checkMode) { - - if (!(node.getUserObject() instanceof IGeneralizationSet)) - return; - - IGeneralizationSet gSet = ((IGeneralizationSet) ((DefaultMutableTreeNode) node).getUserObject()); - - IGeneralization[] generalizations = gSet.toGeneralizationArray(); - - if (generalizations == null) - return; - - 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); - } - - // 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; - - 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 }; - - if (modelElement instanceof IModel) { - IModel model = (IModel) modelElement; - - ElementNode newParent; - newParent = new ElementNode(model); - - newRoot.add(newParent); - - for (IModelElement element : model.toChildArray(rootLevelElements)) - setChildrenRecursively(element, newParent); - } + if (checkMode) checkedPaths.add(newTp); + else checkedPaths.remove(newTp); + } + } - if (modelElement instanceof IPackage) { - IPackage pckg = (IPackage) modelElement; + if (root.getChildCount() >= 0) { + for (Enumeration e = root.children(); e.hasMoreElements(); ) { + ElementNode n = (ElementNode) e.nextElement(); - ElementNode newParent; - newParent = new ElementNode(pckg); + visitAllAndCheckSameId(n, id, checkMode); + } + } + } - newRoot.add(newParent); + protected void findSimilarNodes(ElementNode node) { - for (IModelElement element : pckg.toChildArray(rootLevelElements)) - setChildrenRecursively(element, newParent); - } + for (int i = 0; i < node.getChildCount(); i++) + findSimilarNodes((ElementNode) node.getChildAt(i)); - if (modelElement instanceof IClass) { - IClass _class = (IClass) modelElement; - ElementNode newParent; + ElementNode root = (ElementNode) this.getModel().getRoot(); + visitAllNodesAndCheckSimilar(root, node); + } - newParent = new ElementNode(_class); + private void visitAllNodesAndCheckType(ElementNode root, ElementNode nodeToCompare) { + String typeOriginal = ""; + String typeCurrentNode = ""; - IAttribute[] attributes = _class.toAttributeArray(); + if (nodeToCompare.getUserObject() instanceof IClass) + typeOriginal = ((IClass) nodeToCompare.getUserObject()).getName(); - for (int j = 0; attributes != null && j < attributes.length; j++) - newParent.add(new ElementNode(attributes[j])); + if (nodeToCompare.getUserObject() instanceof IAttribute) + typeOriginal = ((IAttribute) nodeToCompare.getUserObject()).getTypeAsString(); - newRoot.add(newParent); - } + if (root.getUserObject() instanceof IClass) + typeCurrentNode = ((IClass) root.getUserObject()).getName(); - if (modelElement instanceof IAssociation) { - IAssociation association = (IAssociation) modelElement; - ElementNode newParent; + if (root.getUserObject() instanceof IDataType) + typeCurrentNode = ((IDataType) root.getUserObject()).getName(); - newParent = new ElementNode(association); + if (typeOriginal != null && typeCurrentNode.contentEquals(typeOriginal)) { - IAssociationEnd fromEnd = (IAssociationEnd) association.getFromEnd(); - IAssociationEnd toEnd = (IAssociationEnd) association.getToEnd(); + TreeNode[] old_treeNode = nodeToCompare.getPath(); + TreePath oldTp = new TreePath(old_treeNode); - if (fromEnd != null) - newParent.add(new ElementNode(fromEnd)); + TreeNode[] new_treeNode = root.getPath(); + TreePath newTp = new TreePath(new_treeNode); + + // if different paths + if (!oldTp.toString().equals(newTp.toString())) { + boolean checkMode = nodesCheckingState.get(oldTp).isSelected; + + if ((root.getUserObject() instanceof IClass || root.getUserObject() instanceof IDataType) + && checkMode == true) { + + 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(); + + visitAllNodesAndCheckType(n, nodeToCompare); + } + } + } + + protected void selectTypeNodes(ElementNode node) { + ElementNode root = (ElementNode) this.getModel().getRoot(); + visitAllNodesAndCheckType(root, node); + } + + protected void selectAllGeneralizationsFromSet(ElementNode node, boolean checkMode) { + + if (!(node.getUserObject() instanceof IGeneralizationSet)) return; + + IGeneralizationSet gSet = + ((IGeneralizationSet) ((DefaultMutableTreeNode) node).getUserObject()); + + IGeneralization[] generalizations = gSet.toGeneralizationArray(); + + if (generalizations == null) return; + + 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); + } + + // 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; + + 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 + }; + + if (modelElement instanceof IModel) { + IModel model = (IModel) modelElement; + + ElementNode newParent; + newParent = new ElementNode(model); + + newRoot.add(newParent); + + for (IModelElement element : model.toChildArray(rootLevelElements)) + setChildrenRecursively(element, newParent); + } + + if (modelElement instanceof IPackage) { + IPackage pckg = (IPackage) modelElement; + + ElementNode newParent; + newParent = new ElementNode(pckg); - if (toEnd != null) - newParent.add(new ElementNode(toEnd)); + newRoot.add(newParent); - newRoot.add(newParent); - } + for (IModelElement element : pckg.toChildArray(rootLevelElements)) + setChildrenRecursively(element, newParent); + } - if (modelElement instanceof IDataType) { - IDataType _class = (IDataType) modelElement; + if (modelElement instanceof IClass) { + IClass _class = (IClass) modelElement; + ElementNode newParent; - ElementNode newParent; - newParent = new ElementNode(_class); + newParent = new ElementNode(_class); - newRoot.add(newParent); - } + IAttribute[] attributes = _class.toAttributeArray(); - if (modelElement instanceof IGeneralizationSet) { - IGeneralizationSet generalizationSet = (IGeneralizationSet) modelElement; - ElementNode newParent; + for (int j = 0; attributes != null && j < attributes.length; j++) + newParent.add(new ElementNode(attributes[j])); - newParent = new ElementNode(generalizationSet); - newRoot.add(newParent); - } + newRoot.add(newParent); + } - if (modelElement instanceof IGeneralization) { - IGeneralization generalization = (IGeneralization) modelElement; - ElementNode newParent; + if (modelElement instanceof IAssociation) { + IAssociation association = (IAssociation) modelElement; + ElementNode newParent; - if (generalization.getFrom() != null && generalization.getTo() != null) { - newParent = new ElementNode(generalization); - newRoot.add(newParent); - } - } + newParent = new ElementNode(association); - if (modelElement instanceof IAssociationClass) { - IAssociationClass associationClass = (IAssociationClass) modelElement; - ElementNode newParent; + IAssociationEnd fromEnd = (IAssociationEnd) association.getFromEnd(); + IAssociationEnd toEnd = (IAssociationEnd) association.getToEnd(); - newParent = new ElementNode(associationClass); - newRoot.add(newParent); - } + if (fromEnd != null) newParent.add(new ElementNode(fromEnd)); - return newRoot; - } + if (toEnd != null) newParent.add(new ElementNode(toEnd)); - private static ElementNode setChildrenFromDiagrams(IDiagramUIModel diagram, ElementNode parent) { - ElementNode newRoot = parent; + newRoot.add(newParent); + } - 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); + 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); + } + } - ElementNode newParent; - newParent = new ElementNode(pckg); + if (modelElement instanceof IAssociationClass) { + IAssociationClass associationClass = (IAssociationClass) modelElement; + ElementNode newParent; - newRoot.add(newParent); + newParent = new ElementNode(associationClass); + newRoot.add(newParent); + } - IModelElement[] elements = pckg.toChildArray(); + return newRoot; + } - for (int j = 0; elements != null && j < elements.length; j++) - setChildrenRecursively(elements[i], newParent); - } - } + private static ElementNode setChildrenFromDiagrams(IDiagramUIModel diagram, ElementNode parent) { + ElementNode newRoot = parent; - for (int i = 0; classes != null && i < classes.length; i++) { - if (classes[i].getModelElement() != null) { - IClass _class = (IClass) classes[i].getModelElement(); + 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(_class); + for (int i = 0; models != null && i < models.length; i++) { + if (models[i].getModelElement() != null) { + IModel model = (IModel) models[i].getModelElement(); - IAttribute[] attributes = _class.toAttributeArray(); + ElementNode newParent; + newParent = new ElementNode(model); - for (int j = 0; attributes != null && j < attributes.length; j++) - newParent.add(new ElementNode(attributes[j])); + newRoot.add(newParent); - newRoot.add(newParent); - } - } + IModelElement[] elements = model.toChildArray(); - for (int i = 0; associations != null && i < associations.length; i++) { - if (associations[i].getModelElement() != null) { - IAssociation association = (IAssociation) associations[i].getModelElement(); - ElementNode newParent; - - newParent = new ElementNode(association); - - IAssociationEnd fromEnd = (IAssociationEnd) association.getFromEnd(); - IAssociationEnd toEnd = (IAssociationEnd) association.getToEnd(); - - if (fromEnd != null) - newParent.add(new ElementNode(fromEnd)); + for (int j = 0; elements != null && j < elements.length; j++) + setChildrenRecursively(elements[i], newParent); + } + } - if (toEnd != null) - newParent.add(new ElementNode(toEnd)); + for (int i = 0; pckgs != null && i < pckgs.length; i++) { + if (pckgs[i].getModelElement() != null) { + IPackage pckg = (IPackage) pckgs[i].getModelElement(); - newRoot.add(newParent); + ElementNode newParent; + newParent = new ElementNode(pckg); - } - } + 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; + IModelElement[] elements = pckg.toChildArray(); - newParent = new ElementNode(generalizationSet); - newRoot.add(newParent); - } - } + for (int j = 0; elements != null && j < elements.length; j++) + setChildrenRecursively(elements[i], 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); - } - } - - 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); - } - } - - return newRoot; - } - - @SuppressWarnings("unchecked") - 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); - - 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 (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 (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(); - - visitAllNodesAndCheckSameId(n, id); - } - } - } - - public void setNodesCheck(HashSet idElements) { - resetCheckingState(); - ElementNode root = (ElementNode) treeModel.getRoot(); - - Iterator ite = idElements.iterator(); - - while (ite.hasNext()) { - String id = ite.next(); - visitAllNodesAndCheckSameId(root, id); - } - - } - - public static class ElementNode extends DefaultMutableTreeNode { - - private static final long serialVersionUID = 1L; - - public ElementNode(Object userObject) { - super(userObject); - } - - @Override - public void add(MutableTreeNode newChild) { - super.add(newChild); - sort(); - } - - @SuppressWarnings("unchecked") - public void sort() { - Collections.sort(children, 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; - } - } - - 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); - } - - }; - - } - } - -} \ No newline at end of file + 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); + + IAttribute[] attributes = _class.toAttributeArray(); + + for (int j = 0; attributes != null && j < attributes.length; j++) + newParent.add(new ElementNode(attributes[j])); + + newRoot.add(newParent); + } + } + + for (int i = 0; associations != null && i < associations.length; i++) { + if (associations[i].getModelElement() != null) { + IAssociation association = (IAssociation) associations[i].getModelElement(); + ElementNode newParent; + + newParent = new ElementNode(association); + + IAssociationEnd fromEnd = (IAssociationEnd) association.getFromEnd(); + IAssociationEnd toEnd = (IAssociationEnd) association.getToEnd(); + + if (fromEnd != null) newParent.add(new ElementNode(fromEnd)); + + if (toEnd != null) newParent.add(new ElementNode(toEnd)); + + 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; + + 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; + + 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; + + newParent = new ElementNode(associationClass); + newRoot.add(newParent); + } + } + + return newRoot; + } + + 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); + + 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 (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 (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(); + + visitAllNodesAndCheckSameId(n, id); + } + } + } + + public void setNodesCheck(HashSet idElements) { + resetCheckingState(); + ElementNode root = (ElementNode) treeModel.getRoot(); + + Iterator ite = idElements.iterator(); + + while (ite.hasNext()) { + String id = ite.next(); + visitAllNodesAndCheckSameId(root, id); + } + } + + public static class ElementNode extends DefaultMutableTreeNode { + + private static final long serialVersionUID = 1L; + + public ElementNode(Object userObject) { + super(userObject); + } + + @Override + public void add(MutableTreeNode newChild) { + super.add(newChild); + sort(); + } + + @SuppressWarnings("unchecked") + public void sort() { + Collections.sort(children, 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; + } + } + + 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); + } + }; + } + } +} 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 59ead0ce..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 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(); - ViewManagerUtils.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/SelectRestrictionsView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/SelectRestrictionsView.java index 7c4d35b1..a676740a 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/SelectRestrictionsView.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/SelectRestrictionsView.java @@ -1,14 +1,14 @@ 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.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; @@ -16,182 +16,145 @@ import javax.swing.JPanel; import javax.swing.border.EmptyBorder; -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; +public class SelectRestrictionsView implements IDialogHandler { -import it.unibz.inf.ontouml.vp.model.Configurations; -import it.unibz.inf.ontouml.vp.utils.StereotypesManager; + private IDialog dialog; + private JPanel selectionPanel; + + private boolean cancelledExit = true; + private String restrictedTo; + private List restrictedToList; + private List selectableRestrictedTo; -public class SelectRestrictionsView implements IDialogHandler { + 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)); - private IDialog _dialog; - private JPanel _selectionsPane; - private boolean cancelledExit = true; - private String initialSelecteion; - - public SelectRestrictionsView(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(); - - 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); - - 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 = StereotypesManager.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(StereotypesManager.RESTRICTED_TO_COLLECTIVE); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_COLLECTIVE)); - // Line 1, Column 2 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_MODE); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_MODE)); - // Line 1, Column 3 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_ABSTRACT); - this._selectionsPane.add(checkBox); - if (isSmartModelingEnabled) { - checkBox.setSelected(false); - checkBox.setEnabled(false); - } else { - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_ABSTRACT)); - } - - // Line 2, Column 1 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_FUNCTIONAL_COMPLEX); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_FUNCTIONAL_COMPLEX)); - // Line 2, Column 2 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_QUALITY); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_QUALITY)); - // Line 2, Column 3 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_EVENT); - this._selectionsPane.add(checkBox); - if (isSmartModelingEnabled) { - checkBox.setSelected(false); - checkBox.setEnabled(false); - } else { - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_EVENT)); - } - - // Line 3, Column 1 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_QUANTITY); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_QUANTITY)); - // Line 3, Column 2 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_RELATOR); - this._selectionsPane.add(checkBox); - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_RELATOR)); - // Line 3, Column 3 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_SITUATION); - this._selectionsPane.add(checkBox); - if (isSmartModelingEnabled) { - checkBox.setSelected(false); - checkBox.setEnabled(false); - } else { - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_SITUATION)); - } - - // Line 4, Column 1 (empty) - this._selectionsPane.add(new JLabel()); - // Line 4, Column 2 (empty) - this._selectionsPane.add(new JLabel()); - // Line 4, Column 3 - checkBox = new JCheckBox(StereotypesManager.RESTRICTED_TO_TYPE); - this._selectionsPane.add(checkBox); - if (isSmartModelingEnabled) { - checkBox.setSelected(false); - checkBox.setEnabled(false); - } else { - checkBox.setSelected(selectedList.contains(StereotypesManager.RESTRICTED_TO_TYPE)); - } - } - -} \ No newline at end of file + 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/SetOrderView.java b/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderView.java index ba161659..cf5e0e65 100644 --- a/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderView.java +++ b/src/main/java/it/unibz/inf/ontouml/vp/views/SetOrderView.java @@ -1,5 +1,9 @@ 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; @@ -7,7 +11,6 @@ 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; @@ -16,160 +19,164 @@ import javax.swing.JTextField; import javax.swing.border.EmptyBorder; -import com.vp.plugin.ApplicationManager; -import com.vp.plugin.view.IDialog; -import com.vp.plugin.view.IDialogHandler; - -import it.unibz.inf.ontouml.vp.OntoUMLPlugin; - 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"); - } + 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"); - } + 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("*"); - } + 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(); - } - }); + addButton.setSize(5, 5); + subtractButton.setSize(5, 5); + asteriskButton.setSize(5, 5); - 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; - } + final JButton cancelButton = new JButton("Cancel"); + final JButton applyButton = new JButton("Apply"); - @Override - public void prepare(IDialog dialog) { - this._dialog = dialog; - dialog.setTitle("Set type order"); - dialog.pack(); - } - - @Override - public boolean canClosed() { - return true; - } + applyButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + cancelledExit = false; + _dialog.close(); + } + }); - @Override - public void shown() {} + cancelButton.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + cancelledExit = true; + _dialog.close(); + } + }); - public String getOrder() { - return this.cancelledExit ? this.currentString : this._inputField.getText(); + 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; } - - 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; - } - } - -} \ No newline at end of file + } +} 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 cf3f0f74..78fcda4f 100644 --- a/src/main/resources/plugin.xml +++ b/src/main/resources/plugin.xml @@ -108,11 +108,25 @@ --> + + + + + + + + + + + + + + @@ -141,6 +155,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -153,6 +241,10 @@ + + + + @@ -339,6 +431,10 @@ + + + +