From e0aa5d147c61763f83182901d527a48991a3da7b Mon Sep 17 00:00:00 2001 From: Aaron Black Date: Wed, 2 Nov 2016 15:14:57 -0700 Subject: [PATCH] Reworked MDKHelper and MDKValidationWindow for donbot. Some supporting changes in EMSLoginAction, EMSLogoutAction, TicketUtils, and ManualSyncRunner. Commented out dead code in DeltaSyncRunner. --- .../nasa/jpl/mbee/mdk/MMSConfigurator.java | 1 - .../gov/nasa/jpl/mbee/mdk/api/MDKHelper.java | 463 +++++++-------- .../jpl/mbee/mdk/api/MDKValidationWindow.java | 533 ++++++------------ .../mbee/mdk/ems/actions/EMSLoginAction.java | 8 +- .../mbee/mdk/ems/actions/EMSLogoutAction.java | 4 + .../mdk/ems/sync/delta/DeltaSyncRunner.java | 31 +- .../mdk/ems/sync/manual/ManualSyncRunner.java | 4 +- .../nasa/jpl/mbee/mdk/lib/TicketUtils.java | 23 +- .../pma/analyses/AutomatedViewGeneration.java | 3 +- 9 files changed, 414 insertions(+), 656 deletions(-) diff --git a/src/main/java/gov/nasa/jpl/mbee/mdk/MMSConfigurator.java b/src/main/java/gov/nasa/jpl/mbee/mdk/MMSConfigurator.java index d9e34a140..48e561195 100644 --- a/src/main/java/gov/nasa/jpl/mbee/mdk/MMSConfigurator.java +++ b/src/main/java/gov/nasa/jpl/mbee/mdk/MMSConfigurator.java @@ -35,7 +35,6 @@ import com.nomagic.magicdraw.actions.ActionsStateUpdater; import com.nomagic.magicdraw.actions.MDActionsCategory; import gov.nasa.jpl.mbee.mdk.ems.actions.*; -import gov.nasa.jpl.mbee.mdk.lib.MDUtils; public class MMSConfigurator implements AMConfigurator { diff --git a/src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKHelper.java b/src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKHelper.java index 89ddbf7a4..fef701948 100644 --- a/src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKHelper.java +++ b/src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKHelper.java @@ -1,29 +1,29 @@ /******************************************************************************* - * Copyright (c) <2016>, California Institute of Technology ("Caltech"). + * Copyright (c) <2016>, California Institute of Technology ("Caltech"). * U.S. Government sponsorship acknowledged. * * All rights reserved. * - * Redistribution and use in source and binary forms, with or without modification, are + * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * - * - Redistributions of source code must retain the above copyright notice, this list of + * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. - * - Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials + * - Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. - * - Neither the name of Caltech nor its operating division, the Jet Propulsion Laboratory, - * nor the names of its contributors may be used to endorse or promote products derived + * - Neither the name of Caltech nor its operating division, the Jet Propulsion Laboratory, + * nor the names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS - * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY - * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ @@ -31,16 +31,21 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; + import com.nomagic.magicdraw.core.Application; import com.nomagic.magicdraw.core.Project; import com.nomagic.ui.ProgressStatusRunner; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; + import gov.nasa.jpl.mbee.mdk.MDKPlugin; import gov.nasa.jpl.mbee.mdk.MMSSyncPlugin; +import gov.nasa.jpl.mbee.mdk.api.incubating.MDKConstants; import gov.nasa.jpl.mbee.mdk.api.incubating.convert.Converters; import gov.nasa.jpl.mbee.mdk.docgen.validation.ValidationSuite; import gov.nasa.jpl.mbee.mdk.ems.MMSUtils; import gov.nasa.jpl.mbee.mdk.ems.ServerException; +import gov.nasa.jpl.mbee.mdk.ems.actions.EMSLoginAction; +import gov.nasa.jpl.mbee.mdk.ems.actions.EMSLogoutAction; import gov.nasa.jpl.mbee.mdk.ems.actions.GenerateViewPresentationAction; import gov.nasa.jpl.mbee.mdk.ems.actions.UpdateAllDocumentsAction; import gov.nasa.jpl.mbee.mdk.ems.sync.coordinated.CoordinatedSyncProjectEventListenerAdapter; @@ -55,10 +60,11 @@ import gov.nasa.jpl.mbee.mdk.lib.Changelog; import gov.nasa.jpl.mbee.mdk.lib.TicketUtils; import gov.nasa.jpl.mbee.mdk.lib.Utils; + import org.apache.http.client.methods.HttpRequestBase; -import org.python.google.common.collect.Lists; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; @@ -70,74 +76,194 @@ */ public class MDKHelper { + /************************************************************ + * + * General Helper Methods + * + ************************************************************/ + + public static Changelog getInMemoryElementChangelog(Project project) { + return LocalSyncProjectEventListenerAdapter.getProjectMapping(project).getLocalSyncTransactionCommitListener().getInMemoryLocalChangelog(); + } + + /** + * Causes program to pause execution until all added commit operations + * have been completed. + */ + public static boolean mmsUploadWait() { + if (OutputQueue.getInstance().getCurrent() != null) { + int elements = OutputQueue.getInstance().getCurrent().getNumElements(); + for (Request request : OutputQueue.getInstance()) { + elements += request.getNumElements(); + } + MagicDrawHelper.generalMessage("Uploading: " + elements + " Elements"); + while (true) { + if (OutputQueue.getInstance().getCurrent() == null) { + MagicDrawHelper.generalMessage("Upload complete"); + return true; + } + else { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + return false; + } + } + } + } + else { + return false; + } + } + + /** + * Sets boolean that can disabled popups and redirect their messages to the GUI log. + * + * @param disabled true to redirect popups to gui log, false to renable normal popup behavior + */ + public static void setPopupsDisabled(boolean disabled) { + Utils.setPopupsDisabled(disabled); + } + + public static void setSyncTransactionListenerDisabled(boolean enable) { + Project project = Application.getInstance().getProject(); + LocalSyncProjectMapping lspm = LocalSyncProjectEventListenerAdapter.getProjectMapping(project); + if (lspm == null) { + throw new IllegalStateException("LocalSyncProjectMapping is null"); + } + LocalSyncTransactionCommitListener lstcl = lspm.getLocalSyncTransactionCommitListener(); + if (lstcl == null) { + throw new IllegalStateException("LocalSyncTransactionCommitListener is null"); + } + lstcl.setDisabled(enable); + } + + public static boolean isPopupsDisabled() { + return Utils.isPopupsDisabled(); + } + + /************************************************************ + * + * MMS Login Methods + * + ************************************************************/ + + /** + * Sets the supplied username and password in memory. Does not validate its accuracy. + * + * @param username Username for MMS login + * @param password Password for MMS login + */ + public static void setMMSLoginCredentials(String username, String password) { + TicketUtils.setUsernameAndPassword(username, password); + } + + /** + * Logs onto mms using the supplied username and password Does not generate + * or interact with mmslogin dialog window + * + * @param username Username for MMS login + * @param password Password for MMS login + */ + public static boolean loginToMMS(final String username, final String password) { + TicketUtils.setUsernameAndPassword(username, password); + return new EMSLoginAction().loginAction(Application.getInstance().getProject()); + } + + /** + * Logs onto mms using the supplied username and password Does not generate + * or interact with mmslogin dialog window + * + */ + public static void logoutOfMMS() { + new EMSLogoutAction().logoutAction(); + } + + /************************************************************ + * + * MDK Validation Window Access Methods + * + ************************************************************/ + private static MDKValidationWindow validationWindow; - public static MDKValidationWindow getManualValidationWindow() { + /** + * Gets the currently stored validationWindow accessor. This might be a CSync or manual validation suite, depending + * on what operation was last performed. + * + * @return the currently stored validationWindow accessor + */ + public static MDKValidationWindow getValidationWindow() { return validationWindow; } /** - * Updates the MDKValidationWindow object with the latest delta sync results, or sets window to null if there are no results. + * Updates the MDKValidationWindow object with the latest delta sync results, or sets to null if + * there are no results. */ - public static MDKValidationWindow getCoordinatedSyncValidationWindow() { + public static void loadCoordinatedSyncValidations() { CoordinatedSyncProjectEventListenerAdapter cspela = MMSSyncPlugin.getInstance().getCoordinatedSyncProjectEventListenerAdapter(); if (cspela == null) { - return null; + return; } DeltaSyncRunner dsr = cspela.getDeltaSyncRunner(); if (dsr == null) { - return null; + return; } List vss = dsr.getValidations(); if (vss.isEmpty()) { - return null; + return; } validationWindow = new MDKValidationWindow(vss); - return validationWindow; } - - public static void updateManualValidationWindow(List vss) { + /** + * Updates the stored validationWindow accessor with a new suite of validations. Not many use cases for this as of 2.4 + * + * @param vss The new validation suite to load validationWindow accessor + */ + @Deprecated + public static void updateValidationWindow(List vss) { validationWindow = new MDKValidationWindow(vss); } /************************************************************ * - * MDK Methods + * Model Initialization Methods * ************************************************************/ /** * Checks if entire project is initialized; if not does nothing * - * @throws Exception */ - public static boolean checkInitialization() throws Exception { + public static boolean checkInitialization() { if (validationWindow == null) { - validateModelRoot(); + manualValidateModel(); } - return validationWindow.listPooledViolations("INITIALIZATION") == 0; + return validationWindow.listPooledViolations("Project Existence") == 0; } /** * Checks if entire project is initialized; if not initializes project * without committing model * - * @throws Exception */ - public static boolean confirmInitialization() throws Exception { + public static boolean confirmInitialization() + throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { if (validationWindow == null) { - validateModelRoot(); + manualValidateModel(); } // if there are initialization violations - if (validationWindow.listPooledViolations("INITIALIZATION") != 0) { + if (validationWindow.listPooledViolations("Project Existence") != 0) { // process initializations, if possible - validationWindow.commitMDChangesToMMS("INITIALIZATION"); + validationWindow.initializeProject(); mmsUploadWait(); // re-validate and re-check - validateModelRoot(); - if (validationWindow.listPooledViolations("INITIALIZATION") != 0) { + manualValidateModel(); + if (validationWindow.listPooledViolations("Project Existence") != 0) { // if not clear now, other errors in project return false; } @@ -146,72 +272,9 @@ public static boolean confirmInitialization() throws Exception { return true; } - /** - * Logs onto mms using the supplied username and password Does not generate - * or interact with mmslogin dialog window - * - * @param username - * @param password - */ - public static boolean loginToMMS(final String username, final String password) { - TicketUtils.setUsernameAndPassword(username, password); - return TicketUtils.loginToMMS(); - } - - /** - * Sets boolean that can disabled popups and redirect their messages to the GUI log. - * - * @param disabled true to redirect popups to gui log, false to renable normal popup behavior - */ - public static void setPopupsDisabled(boolean disabled) { - Utils.setPopupsDisabled(disabled); - } - - /** - * Sets the supplied username and password in memory. Does not validate its accuracy. - * - * @param username - * @param password - */ - public static void setMMSLoginCredentials(String username, String password) { - TicketUtils.setUsernameAndPassword(username, password); - } - - /** - * Causes program to pause execution until all added commit operations - * have been completed. - */ - public static boolean mmsUploadWait() { - if (OutputQueue.getInstance().getCurrent() != null) { - int elements = OutputQueue.getInstance().getCurrent().getNumElements(); - Iterator queueIterator = OutputQueue.getInstance().iterator(); - while (queueIterator.hasNext()) { - elements += queueIterator.next().getNumElements(); - } - MagicDrawHelper.generalMessage("Uploading: " + elements + " Elements"); - while (true) { - if (OutputQueue.getInstance().getCurrent() == null) { - MagicDrawHelper.generalMessage("Upload complete"); - return true; - } - else { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - return false; - } - } - } - } - else { - return false; - } - } - /********************************************************************************** * - * Single element MDK Actions + * MDK User Actions * **********************************************************************************/ @@ -223,20 +286,15 @@ public static boolean mmsUploadWait() { * generate only the view for the selected element */ public static void generateViews(Element doc, Boolean recurse) { - GenerateViewPresentationAction gvpa = new GenerateViewPresentationAction(Lists.newArrayList(doc), recurse); + List documents = new ArrayList<>(1); + documents.add(doc); + GenerateViewPresentationAction gvpa = new GenerateViewPresentationAction(documents, recurse); validationWindow = new MDKValidationWindow(gvpa.updateAction()); } - /** - * Executes "Generate Views and Commit to MMS" action on the selected - * element - * - * @param doc Selected Document Element. - */ - @Deprecated - public static void generateViewsAndCommitToMMS(Element doc) { - //OneClickUpdateDoc ocud = new OneClickUpdateDoc(Lists.newArrayList(doc)); - //validationWindow = new MDKValidationWindow(ocud.updateAction()); + public static void generateAllDocuments() { + UpdateAllDocumentsAction uad = new UpdateAllDocumentsAction(); + validationWindow = new MDKValidationWindow(uad.updateAction()); } /** @@ -244,7 +302,7 @@ public static void generateViewsAndCommitToMMS(Element doc) { * * @param validateTarget element that the validation is to be performed upon */ - public static void validateModel(Element validateTarget) { + public static void manualValidateElement(Element validateTarget) { Collection sync = new ArrayList(); sync.add(validateTarget); ManualSyncRunner manualSyncRunner = new ManualSyncRunner(sync, Application.getInstance().getProject(), true, 0); @@ -256,20 +314,8 @@ public static void validateModel(Element validateTarget) { /** * Executes "Validate Model" on model root */ - public static void validateModelRoot() { - validateModel(ElementFinder.getModelRoot()); - } - - /** - * Executes "Validate View Hierarchy" on specified element - * - * @param validateTarget element that the validation is to be performed upon - */ - @Deprecated - public static void validateViewHierarchy(Element validateTarget) { - //ValidateViewRunner vvr = new ValidateViewRunner(validateTarget, false, true, true); - //ProgressStatusRunner.runWithProgressStatus(vvr, "Validating Views", true, 0); - //validationWindow = new MDKValidationWindow(vvr.getValidations()); + public static void manualValidateModel() { + manualValidateElement(ElementFinder.getModelRoot()); } /********************************************************************************** @@ -297,59 +343,45 @@ public static ObjectNode getMmsElementsByID(Collection cs, Project proje /** * Sends a DELETE request to MMS for the indicated element. * - * @param elements The element you want to delete on the MMS + * @param elementsToDelete Collection of elements you want to directly delete on the MMS * @throws IllegalStateException * @throws ServerException */ - public static ObjectNode deleteMmsElements(Collection elements, Project project) throws IllegalStateException, IOException, URISyntaxException, ServerException { - ObjectNode objectNode = JacksonUtils.getObjectMapper().createObjectNode(); - ArrayNode elementsArrayNode = objectNode.putArray("elements"); - elements.forEach(element -> elementsArrayNode.add(Converters.getElementToIdConverter().apply(element))); - objectNode.put("source", "magicdraw"); - objectNode.put("mmsVersion", MDKPlugin.VERSION); - - HttpRequestBase request = MMSUtils.buildRequest(MMSUtils.HttpRequestType.DELETE, MMSUtils.getServiceWorkspacesSitesElementsUri(project)); + public static ObjectNode deleteMmsElements(Collection elementsToDelete, Project project) + throws IOException, URISyntaxException, ServerException { + ObjectNode requestBody = JacksonUtils.getObjectMapper().createObjectNode(); + ArrayNode elements = requestBody.putArray("elements"); + for (Element delTarget : elementsToDelete) { + ObjectNode curElement = JacksonUtils.getObjectMapper().createObjectNode(); + curElement.put(MDKConstants.SYSML_ID_KEY, Converters.getElementToIdConverter().apply(delTarget)); + elements.add(curElement); + } + requestBody.put("source", "magicdraw"); + requestBody.put("mmsVersion", MDKPlugin.VERSION); + HttpRequestBase request = MMSUtils.buildRequest(MMSUtils.HttpRequestType.DELETE, + MMSUtils.getServiceWorkspacesSitesElementsUri(project), requestBody); return MMSUtils.sendMMSRequest(request); } /** * Sends a POST request to MMS with the element JSON, creating or updating the element as appropriate. * - * @param elementsNode The JSONObject of the element to create or update. - * Generally acquired through ExportUtility.fillElement(element, null) + * @param elementsToPost Collection of elements you want to directly post on the MMS * @throws IllegalStateException */ - @Deprecated - // TODO Move to MMSUtils @donbot -// public static void postMmsElement(ObjectNode elementsNode) throws IllegalStateException { -// if (elementsNode == null) { -// throw new IllegalStateException("No element json specified to export to MMS"); -// } -// -// Project proj = Application.getInstance().getProject(); -// if (proj == null) { -// throw new IllegalStateException("No project opened."); -// } -// -// URIBuilder requestUri = MMSUtils.getServiceWorkspacesUri(); -// String url = ExportUtility.getPostElementsUrl(); -// if (requestUri == null) { -// throw new IllegalStateException("Project does not have MMS URL configured."); -// } -// -// -// -// JSONArray elems = new JSONArray(); -// elems.add(elementsNode); -// JSONObject send = new JSONObject(); -// send.put("elements", elems); -// -// String response = ExportUtility.send(url, send.toJSONString(), false, true); -// if (response == null) { -// throw new IllegalStateException("Invalid send formatting."); -// } -// } - + public static ObjectNode postMmsElement(Collection elementsToPost, Project project) + throws IOException, URISyntaxException, ServerException { + ObjectNode requestBody = JacksonUtils.getObjectMapper().createObjectNode(); + ArrayNode elements = requestBody.putArray("elements"); + for (Element postTarget : elementsToPost) { + elements.add(Converters.getElementToJsonConverter().apply(postTarget, project)); + } + requestBody.put("source", "magicdraw"); + requestBody.put("mmsVersion", MDKPlugin.VERSION); + HttpRequestBase request = MMSUtils.buildRequest(MMSUtils.HttpRequestType.POST, + MMSUtils.getServiceWorkspacesSitesElementsUri(project), requestBody); + return MMSUtils.sendMMSRequest(request); + } /** * Convenience method for confirmSiteWritePermissions(string, string) to check if a project @@ -359,102 +391,11 @@ public static ObjectNode deleteMmsElements(Collection elements, Project * @return true if the site lists "editable":"true" for the logged in user, false otherwise * or when no project is open or project lacks url and site specifications */ - public static boolean hasSiteEditPermission() throws ServerException, IOException, URISyntaxException { + public static boolean isSiteEditable() throws ServerException, IOException, URISyntaxException { Project project = Application.getInstance().getProject(); return MMSUtils.isSiteEditable(project, MMSUtils.getSiteName(project)); } - /********************************************************************************** - * - * Model wide MDK Actions - * - **********************************************************************************/ - - public static void setSyncTransactionListenerDisabled(boolean enable) { - Project project = Application.getInstance().getProject(); - LocalSyncProjectMapping lspm = LocalSyncProjectEventListenerAdapter.getProjectMapping(project); - if (lspm == null) { - throw new IllegalStateException("LocalSyncProjectMapping is null"); - } - LocalSyncTransactionCommitListener lstcl = lspm.getLocalSyncTransactionCommitListener(); - if (lstcl == null) { - throw new IllegalStateException("LocalSyncTransactionCommitListener is null"); - } - lstcl.setDisabled(enable); - } - - /** - * Executes "Generate All Documents and Commit" action - */ - @Deprecated - public static void generateAllDocumentsAndCommitToMMS() { - generateAllDocuments(); - } - - public static void generateAllDocuments() { - UpdateAllDocumentsAction uad = new UpdateAllDocumentsAction(); - validationWindow = new MDKValidationWindow(uad.updateAction()); - } - - /** - * Starts MMS Auto Sync - */ - @Deprecated - public static void startAutoSync() { - } - - /** - * Stops MMS Auto Sync - */ - @Deprecated - public static void stopAutoSync() { - } - - /** - * Executes "Update From MMS" action - */ - @Deprecated - public static void updateFromMMS() { - //UpdateFromJMS ufjms = new UpdateFromJMS(false); - //validationWindow = new MDKValidationWindow(ufjms.updateAction()); - } - - /** - * Executes "Commit to MMS" action - */ - @Deprecated - public static void commitToMMS() { - updateAndCommitToMMS(); - } - /** - * Executes "Commit to MMS" action - */ - @Deprecated - public static void updateAndCommitToMMS() { - //UpdateFromJMS ufjms = new UpdateFromJMS(true); - //validationWindow = new MDKValidationWindow(ufjms.updateAction()); - } - - /** - * Executes "Commit to MMS with Deletes" action - */ - @Deprecated - public static void updateAndCommitWithDeletesToMMS() { - //UpdateFromJMSAndCommitWithDelete ufjmsacwd = new UpdateFromJMSAndCommitWithDelete(); - //validationWindow = new MDKValidationWindow(ufjmsacwd.updateAction()); - } - - public static Changelog getInMemoryElementChangelog(Project project) { - return LocalSyncProjectEventListenerAdapter.getProjectMapping(project).getLocalSyncTransactionCommitListener().getInMemoryLocalChangelog(); - } - - public static boolean isLoginDialogDisabled() { - return Utils.isPopupsDisabled(); - } - - public static void setLoginDialogDisabled(boolean loginDialogDisabled) { - Utils.setPopupsDisabled(loginDialogDisabled); - } } \ No newline at end of file diff --git a/src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKValidationWindow.java b/src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKValidationWindow.java index 27024a0d9..a351c5cb2 100644 --- a/src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKValidationWindow.java +++ b/src/main/java/gov/nasa/jpl/mbee/mdk/api/MDKValidationWindow.java @@ -30,14 +30,16 @@ package gov.nasa.jpl.mbee.mdk.api; import com.nomagic.magicdraw.annotation.Annotation; +import com.nomagic.magicdraw.core.Application; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; + +import gov.nasa.jpl.mbee.mdk.ems.sync.manual.ManualSyncRunner; import gov.nasa.jpl.mbee.mdk.lib.Utils; import gov.nasa.jpl.mbee.mdk.docgen.validation.ValidationRule; import gov.nasa.jpl.mbee.mdk.docgen.validation.ValidationRuleViolation; import gov.nasa.jpl.mbee.mdk.docgen.validation.ValidationSuite; +import org.apache.poi.openxml4j.exceptions.InvalidOperationException; -import javax.swing.*; -import java.awt.event.ActionEvent; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; @@ -56,47 +58,36 @@ public class MDKValidationWindow { protected List> pooledViolations; // these constants correspond to the index in the subarray where the violation type or action class names are stored - private final static int RULE_VIOLATION_TYPE = 0; + private final static int VIOLATION_RULE_NAME = 0; private final static int COMMIT_ACTION = 1; private final static int ACCEPT_ACTION = 2; - // these constants are used to indicate the number of operations before [EXIST] and after [EXIST ON MMS] - // these may contain listed validations, but NEVER contain any violations we would want to process with process all - private static final int PRE_OPERATIONS = 1; - private static final int POST_OPERATIONS = 6; - - // the text indicating its displayed violation is stored in slot 0 of the subarray - // note that these are stored in upper case letters, and any passed text is converted to upper case before comparison - // these are stored in recommended order of operation, to simplify the exportALL and acceptALL functions - // new validation results should be added between [EXIST] and [EXIST ON MMS], in order or processing. - // adding new validation results outside of this area will require an adjustment to the PREOPERATION and POSTOPERATION - // constants, so that non-processable functions do not get processed during the export/accept all methods + private final static int INITIALIZATION_RULE = 0; + private final static int EQUIVALENCE_RULE = 1; + + // the text indicating the validation rule name is stored in slot 0 of the subarray // the text matching the name of the class that handles the commit action is stored in slot 1 // the text matching the name of the class that handles the accept action is stored in slot 2 - // note that for [EXIST on MMS] the accept action is to create in MD and the commit action is to delete on MMS - public static final String[][] VALIDATION_OPTIONS = { - // intiialization messages do not start with a [MESSAGE] in the validationSuite - // they use INITIALIZATION here for clarity in output - {"INITIALIZATION", "CommitProjectAction", ""}, {"[EXIST]", "ExportElement", "DeleteMagicDrawElement"}, {"[INSTANCE]", "ExportInstanceSpec", "ImportInstanceSpec"}, - {"[VIEW CONSTRAINT]", "ExportViewConstraint", "ImportViewConstraint"}, {"[NAME]", "ExportName", "ImportName"}, {"[DOC]", "ExportDoc", "ImportDoc"}, {"[ATTRIBUTE]", "ExportOwnedAttribute", "ImportOwnedAttribute"}, - {"[OWNER]", "ExportOwner", "FixModelOwner"}, {"[PROP]", "ExportProperty", "ImportProperty"}, {"[FEATURE]", "ExportProperty", ""}, {"[SITE CHAR]", "ExportSite", ""}, {"[REL]", "ExportRel", "ImportRel"}, - {"[VALUE]", "ExportValue", "ImportValue"}, {"[CONNECTOR]", "ExportConnector", "ImportConnector"}, {"[CONSTRAINT]", "ExportConstraint", "ImportConstraint"}, {"[ASSOC]", "ExportAssociation", "ImportAssociation"}, - {"[METATYPE]", "ExportMetatypes", ""}, {"[HIERARCHY]", "ExportHierarchy", "ImportHierarchy"}, {"[IMAGE]", "ExportImage", ""}, {"[EXIST ON MMS]", "DeleteAlfrescoElement", "CreateMagicDrawElement"}, {"[CREATED]", "", ""}, - {"[CREATE FAILED]", "", ""}, {"[UPDATED]", "", ""}, {"[LOCAL FAILED]", "", ""}, {"[DELETED]", "", ""}, {"[DELETE FAILED]", "", ""}}; + public static final String[][] VALIDATION_RULE_OPTIONS = { + {"Project Existence", "CommitProjectAction", ""}, + {"Element Equivalence", "CommitClientElementAction", "AcceptClientElementAction"} + }; /** - * Constructor. This will sort the validation rules results into a format expected by a user who sorted their validation result window based on message (for batch processing) + * Constructor. This will sort the validation rules results into a format expected by a user who sorted their + * validation result window based on message (for batch processing) * * @param vs validationSuite returned from a validation action */ public MDKValidationWindow(ValidationSuite vs) { - this.vss = new ArrayList(); + this.vss = new ArrayList<>(); vss.add(vs); initializeWindow(); } /** - * Constructor. This will sort the validation rules results into a format expected by a user who sorted their validation result window based on message (for batch processing) + * Constructor. This will sort the validation rules results into a format expected by a user who sorted their + * validation result window based on message (for batch processing) * * @param vss List of validationSuites returned from a set of validation actions */ @@ -109,24 +100,25 @@ public MDKValidationWindow(List vss) { * Helper method that does the work of sorting the violations stored in the ValidationSuite(s) */ private void initializeWindow() { - this.pooledViolations = new ArrayList>(); - for (int i = 0; i <= VALIDATION_OPTIONS.length; i++) { - this.pooledViolations.add(new ArrayList()); + pooledViolations = new ArrayList<>(); + for (int i = 0; i <= VALIDATION_RULE_OPTIONS.length; i++) { + pooledViolations.add(new ArrayList<>()); } // sort the ValidationRuleViolations into the appropriate list in this class + // this used to be a lot more complicated :-( for (ValidationSuite vs : vss) { if (vs != null && vs.hasErrors()) { for (ValidationRule vr : vs.getValidationRules()) { - if (vr.getViolations() == null || vr.getViolations().size() == 0) { + if (vr.getViolations() == null || vr.getViolations().isEmpty()) { continue; } - for (ValidationRuleViolation vrv : vr.getViolations()) { - String s = vrv.getComment(); - s = s.substring(0, s.indexOf(']') + 1); - if (lookupListIndex(s) != -1) { - pooledViolations.get(lookupListIndex(s)).add(vrv); - } + try { + pooledViolations.get(lookupListIndex(vr.getName())).addAll(vr.getViolations()); + } + catch (UnsupportedOperationException e) { + Application.getInstance().getGUILog().log("[ERROR] Unable to store violations for rule " + + vr.getName()); } } } @@ -134,7 +126,7 @@ private void initializeWindow() { } /** - * Returns the ValidationSuite(s) stored in object + * Returns the ValidationSuite(s) stored in the MDKValidationWindow object * * @return the ValidationSuite(s) stored in object */ @@ -149,18 +141,20 @@ public List getValidations() { * @return Number of violations of specified type * @throws Exception Unsupported violation type */ - public int listPooledViolations(String type) throws UnsupportedOperationException { - type = standardize(type); - int index; - index = lookupListIndex(type); - if (index == -1) { - throw new UnsupportedOperationException(type + " is not a supported violation result."); - } - System.out.println("There are " + pooledViolations.get(index).size() + " ValidationRuleViolatons in the " + type + " pool"); - for (ValidationRuleViolation vrv : pooledViolations.get(index)) { - System.out.println(" " + (vrv.getElement() != null ? vrv.getElement().getHumanName() : "null") + " : " + vrv.getComment()); + public int listPooledViolations(String type) { + try { + int index = lookupListIndex(type); + System.out.println("There are " + pooledViolations.get(index).size() + + " ValidationRuleViolations in the " + type + " pool"); + for (ValidationRuleViolation vrv : pooledViolations.get(index)) { + System.out.println(" " + (vrv.getElement() != null ? vrv.getElement().getHumanName() : "null") + + " : " + vrv.getComment()); + } + return pooledViolations.get(index).size(); + } catch (UnsupportedOperationException e) { + System.out.println(type + " is not a supported violation result."); } - return pooledViolations.get(index).size(); + return 0; } /** @@ -170,9 +164,9 @@ public int listPooledViolations(String type) throws UnsupportedOperationExceptio */ public int listPooledViolations() { int numViolations = 0; - for (String[] s : VALIDATION_OPTIONS) { + for (String[] s : VALIDATION_RULE_OPTIONS) { try { - numViolations += listPooledViolations(s[RULE_VIOLATION_TYPE]); + numViolations += listPooledViolations(s[VIOLATION_RULE_NAME]); } catch (Exception e) { // do nothing, not a user problem if one of the listed types should be updated } @@ -187,7 +181,6 @@ public int listPooledViolations() { * @return */ public List getPooledValidations(String type) { - type = standardize(type); return pooledViolations.get(lookupListIndex(type)); } @@ -197,31 +190,13 @@ public List getPooledValidations(String type) { * @param type String of the type to look for. Expected format: '[type]' * @return index of the list of validation results of the specified type */ - private int lookupListIndex(String type) { - type = standardize(type); - for (int index = 0; index < VALIDATION_OPTIONS.length; index++) { - if (VALIDATION_OPTIONS[index][RULE_VIOLATION_TYPE].equalsIgnoreCase(type)) { + private int lookupListIndex(String type) throws UnsupportedOperationException{ + for (int index = 0; index < VALIDATION_RULE_OPTIONS.length; index++) { + if (VALIDATION_RULE_OPTIONS[index][VIOLATION_RULE_NAME].equalsIgnoreCase(type)) { return index; } } - return -1; - } - - /** - * Helper function that standardizes any validation rule type, to prevent dumb errors - * - * @param s - * @return - */ - private String standardize(String s) { - if (s.equals("") || s.equals("INITIALIZATION")) { - return "INITIALIZATION"; - } - s = s.toUpperCase(); - if (s.charAt(0) != '[' && s.charAt(s.length() - 1) != ']') { - s = "[" + s + "]"; - } - return s; + throw new UnsupportedOperationException(type + " is not a supported violation rule."); } private String getVRVElementID(ValidationRuleViolation vrv) { @@ -244,9 +219,9 @@ else if (vrve != null) { ************************************************************************/ /** - * Accepts the MMS version into MD for the specified violation type + * Processes validation rule violations that have been stored in the MDKValidationWindow object * - * @param violationType the type of violation to be accepted + * @param violationRuleName the type of violation to be accepted * @param commit will commit to MMS if true, will accept from MMS is false * @param targets limits processing of violations to only those elements that are * contained in the collection. if null, does not limit processing. @@ -258,130 +233,78 @@ else if (vrve != null) { * exception will be thrown if specified with targets. * @throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException */ - private void processValidationResults(String violationType, Collection targets, Collection targetIDs, boolean commit) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + private void processValidationResults(String violationRuleName, Collection targets, + Collection targetIDs, boolean commit) + throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalStateException, IllegalAccessException { if (targets != null && targetIDs != null) { - throw new IllegalAccessException("Both element target lists specified."); + throw new IllegalStateException("Both element target lists specified."); } - violationType = standardize(violationType); - MagicDrawHelper.generalMessage((commit ? "Commit" : "Accept") + "ing " + (targets != null ? "selected " : "") + "instances of " + violationType + " violations."); + MagicDrawHelper.generalMessage((commit ? "Commit" : "Accept") + "ing " + (targets != null ? "selected " : "") + "instances of " + violationRuleName + " violations."); - int ruleIndex = lookupListIndex(violationType); - String className = VALIDATION_OPTIONS[ruleIndex][(commit ? COMMIT_ACTION : ACCEPT_ACTION)]; + int ruleIndex; + try { + ruleIndex = lookupListIndex(violationRuleName); + } catch (InvalidOperationException e) { + MagicDrawHelper.generalMessage("[ERROR]" + violationRuleName + " is not a supported violation rule."); + return; + } + String className = VALIDATION_RULE_OPTIONS[ruleIndex][(commit ? COMMIT_ACTION : ACCEPT_ACTION)]; // if nothing to do, say so and return if (pooledViolations.get(ruleIndex).isEmpty()) { - MagicDrawHelper.generalMessage("[INFO] There are no instances of " + violationType + " to " + (commit ? "commit" : "accept") + "."); + MagicDrawHelper.generalMessage("[INFO] There are no instances of " + violationRuleName + " to " + (commit ? "commit" : "accept") + "."); return; } else if (className.equals("")) { - MagicDrawHelper.generalMessage("[INFO] There is no " + (commit ? "commit" : "accept") + " action for instances of " + violationType + " to process."); + MagicDrawHelper.generalMessage("[INFO] There is no " + (commit ? "commit" : "accept") + " action for instances of " + violationRuleName + " to process."); return; } // get the appropriate violation list List violationList = pooledViolations.get(ruleIndex); - // there are not accept initialization actions, not any commit actions except for one with a specific message - // if it's not an actionable initialization violation, there is nothing to do so return - if (violationType.equals("INITIALIZATION")) { - if (!commit || !violationList.get(0).getComment().equals("The project doesn't exist on the web.")) { + // there is only one initialization violation with a commit action, so check for it. + // if it's not an actionable initialization violation, there is nothing to do so return. + if (violationRuleName.equals(VALIDATION_RULE_OPTIONS[INITIALIZATION_RULE][VIOLATION_RULE_NAME])) { + if (!commit || !violationList.get(0).getComment().equals(ManualSyncRunner.INITIALIZE_PROJECT_COMMENT)) { return; } } - // find the index of the relevant action type; throw exception if it's not found + // find the index of the relevant action type within the vrv; throw exception if it's not found int actionIndex = 0; - while (actionIndex < violationList.get(0).getActions().size() && !(violationList.get(0).getActions().get(actionIndex).getClass().getSimpleName().equals(className))) { + while (actionIndex < violationList.get(0).getActions().size() + && !(violationList.get(0).getActions().get(actionIndex).getClass().getSimpleName().equals(className))) { actionIndex++; } - if (actionIndex >= violationList.get(0).getActions().size() || !(violationList.get(0).getActions().get(actionIndex).getClass().getSimpleName().equals(className))) { - throw new ClassNotFoundException("Unable to find " + className + " for violation type " + violationType); - } - - // project initialization is specialized and might not include a nmaction to run - if (violationType.equals("INITIALIZATION")) { - for (ValidationRuleViolation vrv : violationList) { - // disable popups, invoke execute on one of the nmactions, re-enable popups - Utils.forceDialogReturnFalse(); - vrv.getActions().get(actionIndex).actionPerformed(new ActionEvent(new JButton(), 5, "")); - } + if (actionIndex >= violationList.get(0).getActions().size() + || !(violationList.get(0).getActions().get(actionIndex).getClass().getSimpleName().equals(className))) { + throw new ClassNotFoundException("Unable to find " + className + " for violation type " + violationRuleName); } - // hierarchies don't export nicely using the standard method - else if (violationType.equals("[HIERARCHY]")) { - - // type cast the action class appropriately, and then pass it a dummy action event to trigger - for (ValidationRuleViolation vrv : violationList) { - if ((targets == null || targets.remove(vrv.getElement())) && (targetIDs == null || targetIDs.remove(getVRVElementID(vrv)))) { - if (commit) { - vrv.getActions().get(actionIndex).actionPerformed(new ActionEvent(new JButton(), 5, "")); - } - else { - vrv.getActions().get(actionIndex).actionPerformed(new ActionEvent(new JButton(), 5, "")); - } - } + // use reflection to get methods for getAnnotaiton and execute from the selected object + java.lang.reflect.Method getAnnotation = + violationList.get(0).getActions().get(actionIndex).getClass().getMethod("getAnnotation"); + java.lang.reflect.Method execute = + violationList.get(0).getActions().get(actionIndex).getClass().getMethod("execute", Collection.class); + + // get annotations from the nmaction objects by invoking the getAnnotation method on them + Collection annos = new LinkedList<>(); + for (ValidationRuleViolation vrv : violationList) { + if ((targets == null || targets.remove(vrv.getElement())) + && (targetIDs == null || targetIDs.remove(getVRVElementID(vrv)))) { + Annotation anno = (Annotation) getAnnotation.invoke(vrv.getActions().get(actionIndex)); + annos.add(anno); + System.out.println(" " + (commit ? "Committed " : "Accepted ") + + (vrv.getElement() != null ? vrv.getElement().getHumanName() : "null") + " : " + vrv.getComment()); } } - // for everything else, which runs nicely - else { - - // use reflection to get methods for getAnnotaiton and execute from the selected object - // using full path for Method and Class to avoid confusion with MD objects - java.lang.reflect.Method getAnnotation = violationList.get(0).getActions().get(actionIndex).getClass().getMethod("getAnnotation"); - java.lang.reflect.Method execute = violationList.get(0).getActions().get(actionIndex).getClass().getMethod("execute", Collection.class); - - // get annotations from the nmaction objects by invoking the getAnnotation method on them - Collection annos = new LinkedList(); - for (ValidationRuleViolation vrv : violationList) { - if ((targets == null || targets.remove(vrv.getElement())) && (targetIDs == null || targetIDs.remove(getVRVElementID(vrv)))) { - Annotation anno = (Annotation) getAnnotation.invoke(vrv.getActions().get(actionIndex)); - annos.add(anno); - System.out.println(" " + (commit ? "Committed " : "Accepted ") + (vrv.getElement() != null ? vrv.getElement().getHumanName() : "null") + " : " + vrv.getComment()); - } - } - - // disable popups, invoke execute on one of the nmactions, re-enable popups - Utils.forceDialogReturnFalse(); - execute.invoke(violationList.get(0).getActions().get(actionIndex), annos); - } - } - - /************************************************************************** - * - * Helper methods to process all violation types - * - **************************************************************************/ - - /** - * Process all commits of the MD version to MMS for all violation types for elements in the targets collection - * - * @param targets Collection of elements whose validations should be processed; if null all will be processed - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - private Collection processAllMDChangesToMMS(Collection targets) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - processValidationResults(VALIDATION_OPTIONS[0 + PRE_OPERATIONS][RULE_VIOLATION_TYPE], targets, null, true); - for (int i = 1 + PRE_OPERATIONS; i < VALIDATION_OPTIONS.length - 1 - POST_OPERATIONS; i++) { - processValidationResults(VALIDATION_OPTIONS[i][RULE_VIOLATION_TYPE], targets, null, true); - } - processValidationResults(VALIDATION_OPTIONS[VALIDATION_OPTIONS.length - 1 - POST_OPERATIONS][RULE_VIOLATION_TYPE], targets, null, true); - return targets; - } - - /** - * Processes all accepts of the MMS version into MD for all violation types for elements in the targets collection - * - * @param targets Collection of elements whose validations should be processed; if null all will be processed - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - private Collection processAllMMSChangesIntoMD(Collection targets) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - processValidationResults(VALIDATION_OPTIONS[VALIDATION_OPTIONS.length - 1 - POST_OPERATIONS][RULE_VIOLATION_TYPE], targets, null, false); - for (int i = 1 + PRE_OPERATIONS; i < VALIDATION_OPTIONS.length - 1 - POST_OPERATIONS; i++) { - processValidationResults(VALIDATION_OPTIONS[i][RULE_VIOLATION_TYPE], targets, null, false); - } - processValidationResults(VALIDATION_OPTIONS[PRE_OPERATIONS][RULE_VIOLATION_TYPE], targets, null, false); - return targets; + // disable popups, invoke execute on one of the nmactions, re-enable popups + Utils.forceDialogReturnFalse(); + execute.invoke(violationList.get(0).getActions().get(actionIndex), annos); + Utils.resetForcedReturns(); } /************************************************************************** @@ -392,21 +315,14 @@ private Collection processAllMMSChangesIntoMD(Collection targe /** * Accepts the MMS version into MD for all violation types - * - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public void acceptAllMMSChangesIntoMD() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { - processAllMMSChangesIntoMD(null); - } - - /** - * Accepts the MMS version into MD for the specified violation type - * - * @param violationType the type of violation to be accepted - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException */ - public void acceptMMSChangesIntoMD(String violationType) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - processValidationResults(violationType, null, null, false); + public void acceptAllMMSChangesIntoMD() { + try { + processValidationResults(VALIDATION_RULE_OPTIONS[EQUIVALENCE_RULE][VIOLATION_RULE_NAME], null, null, false); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException | IllegalStateException e) { + MagicDrawHelper.generalMessage("[ERROR]" + e.getMessage()); + } } /** @@ -414,62 +330,49 @@ public void acceptMMSChangesIntoMD(String violationType) throws ClassNotFoundExc * * @param targets the collection of elements whose validations are to be processed * @return returns elements in the target collection that could not be processed / that did not have violations - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException */ - public Collection acceptSpecificMMSChangesIntoMD(Collection targets) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { - Collection notFound = new ArrayList(); + public Collection acceptSpecificMMSChangesIntoMD(Collection targets) { + Collection notFound = new ArrayList<>(); notFound.addAll(targets); - processAllMMSChangesIntoMD(notFound); - return notFound; - } - - /** - * Accepts the MMS version into MD for the specified violation type, if the associated element is in the targets collection - * - * @param violationType the type of violation to be accepted - * @param targets the collection of elements whose validations are to be processed - * @return returns elements in the target collection that could not be processed / that did not have violations - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public Collection acceptSpecificTypeMDChangesToMMS(String violationType, Collection targets) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - Collection notFound = new ArrayList(); - notFound.addAll(targets); - processValidationResults(violationType, notFound, null, false); + try { + processValidationResults(VALIDATION_RULE_OPTIONS[EQUIVALENCE_RULE][VIOLATION_RULE_NAME], notFound, null, false); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException | IllegalStateException e) { + MagicDrawHelper.generalMessage("[ERROR]" + e.getMessage()); + } return notFound; } /** - * Accepts the MMS version into MD for the specified violation type, if the associated element id is in the targetIDs collection + * Commits the MD version to MMS for the specified violation type, if the associated element id is in the targetIDs collection * * @param violationType the type of violation to be accepted - * @param targets the collection of element IDs whose validations are to be processed + * @param targetIDs the collection of element IDs whose validations are to be processed * @return returns elements in the target collection that could not be processed / that did not have violations - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException */ - public Collection acceptSpecificTypeMDChangesToMMSByID(String violationType, Collection targetIDs) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - Collection notFound = new ArrayList(); + public Collection acceptSpecificMDChangesToMMSByID(String violationType, Collection targetIDs) { + Collection notFound = new ArrayList<>(); notFound.addAll(targetIDs); - processValidationResults(violationType, null, notFound, false); + try { + processValidationResults(VALIDATION_RULE_OPTIONS[EQUIVALENCE_RULE][VIOLATION_RULE_NAME], null, notFound, false); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException | IllegalStateException e) { + MagicDrawHelper.generalMessage("[ERROR]" + e.getMessage()); + } return notFound; } /** * Commits the MD version to MMS for all violation types * - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException */ - public void commitAllMDChangesToMMS() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { - processAllMDChangesToMMS(null); - } - - /** - * Commits the MD version to MMS for the specified violation type - * - * @param violationType the type of violation to be accepted - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public void commitMDChangesToMMS(String violationType) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - processValidationResults(violationType, null, null, true); + public void commitAllMDChangesToMMS() { + try { + processValidationResults(VALIDATION_RULE_OPTIONS[EQUIVALENCE_RULE][VIOLATION_RULE_NAME], null, null, true); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException | IllegalStateException e) { + MagicDrawHelper.generalMessage("[ERROR]" + e.getMessage()); + } } /** @@ -479,25 +382,15 @@ public void commitMDChangesToMMS(String violationType) throws ClassNotFoundExcep * @return returns elements in the target collection that could not be processed / that did not have violations * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException */ - public Collection commitSpecificMDChangesToMMS(Collection targets) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { - Collection notFound = new ArrayList(); - notFound.addAll(targets); - processAllMDChangesToMMS(notFound); - return notFound; - } - - /** - * Commits the MD version to MMS for the specified violation type, if the associated element is in the targets collection - * - * @param violationType the type of violation to be accepted - * @param targets the collection of elements whose validations are to be processed - * @return returns elements in the target collection that could not be processed / that did not have violations - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public Collection commitSpecificTypeMDChangesToMMS(String violationType, Collection targets) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - Collection notFound = new ArrayList(); + public Collection commitSpecificMDChangesToMMS(Collection targets) { + Collection notFound = new ArrayList<>(); notFound.addAll(targets); - processValidationResults(violationType, notFound, null, true); + try { + processValidationResults(VALIDATION_RULE_OPTIONS[EQUIVALENCE_RULE][VIOLATION_RULE_NAME], notFound, null, true); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException | IllegalStateException e) { + MagicDrawHelper.generalMessage("[ERROR]" + e.getMessage()); + } return notFound; } @@ -505,82 +398,28 @@ public Collection commitSpecificTypeMDChangesToMMS(String violationType * Commits the MD version to MMS for the specified violation type, if the associated element id is in the targetIDs collection * * @param violationType the type of violation to be accepted - * @param targets the collection of element IDs whose validations are to be processed + * @param targetIDs the collection of element IDs whose validations are to be processed * @return returns elements in the target collection that could not be processed / that did not have violations - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public Collection commitSpecificTypeMDChangesToMMSByID(String violationType, Collection targetIDs) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - Collection notFound = new ArrayList(); - notFound.addAll(targetIDs); - processValidationResults(violationType, null, notFound, true); - return notFound; - } - - /** - * Creates elements in MagicDraw for any missing MMS elements (accepts their existence from MMS) - * Equivalent to [EXIST on MMS] -> Create MagicDraw element - * - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public void createAllMMSElementsNotFoundInMD() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - processValidationResults("[EXIST on MMS]", null, null, false); - } - - /** - * Creates elements in MagicDraw for missing MMS elements whose ids are in the targetIDs collection (accepts their existence from MMS) - * Equivalent to [EXIST on MMS] -> Create MagicDraw element - * - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public Collection createSpecificMMSElementsNotFoundInMD(Collection targetIDs) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - Collection notFound = new ArrayList(); - notFound.addAll(targetIDs); - processValidationResults("[EXIST on MMS]", null, notFound, false); - return notFound; - } - - - /** - * Deletes all elements from MD that were not found in MMS (accepts their non-existence from MMS) - * Equivalent to [EXIST] -> Delete MagicDraw element - * - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public void deleteAllMDElementsNotFoundOnMMS() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - processValidationResults("[EXIST]", null, null, false); - } - - /** - * Deletes all MMS elements that were not found in MD (commits their non-existence to MMS) - * Equivalent to [EXIST on MMS] -> Delete MMS element - * - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public void deleteAllMMSElementsNotFoundInMD() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - processValidationResults("[EXIST on MMS]", null, null, true); - } - - /** - * Deletes MMS elements that were not found in MD whose ids are in the targetIDs collection (commits their non-existence to MMS) - * Equivalent to [EXIST on MMS] -> Delete MMS element - * - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException */ - public Collection deleteSpecificMMSElementsNotFoundInMD(Collection targetIDs) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - Collection notFound = new ArrayList(); + public Collection commitSpecificMDChangesToMMSByID(String violationType, Collection targetIDs) { + Collection notFound = new ArrayList<>(); notFound.addAll(targetIDs); - processValidationResults("[EXIST on MMS]", null, notFound, true); + try { + processValidationResults(VALIDATION_RULE_OPTIONS[EQUIVALENCE_RULE][VIOLATION_RULE_NAME], null, notFound, true); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException | IllegalStateException e) { + MagicDrawHelper.generalMessage("[ERROR]" + e.getMessage()); + } return notFound; } - /** - * Exports all MD elements that were not found in MMS (commits their existence to MMS) - * Equivalent to [EXIST] -> Commit element - * - * @throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException - */ - public void exportAllMDElementsToMMS() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - processValidationResults("[EXIST]", null, null, true); + public void initializeProject() { + try { + processValidationResults(VALIDATION_RULE_OPTIONS[INITIALIZATION_RULE][VIOLATION_RULE_NAME], null, null, true); + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException | IllegalStateException e) { + MagicDrawHelper.generalMessage("[ERROR]" + e.getMessage()); + } } /******************************************************************************** @@ -596,37 +435,18 @@ public void exportAllMDElementsToMMS() throws ClassNotFoundException, NoSuchMeth * @param targets Elements to confirm the presence of in the validations * @return Returns The subset of the elements that were not found in the specified validation type pool */ - public Collection confirmElementValidationTypeResult(String validationType, Collection targets) { - Collection notFound = new ArrayList(); - notFound.addAll(targets); - validationType = standardize(validationType); + public Collection confirmElementViolation(String validationType, Collection targets) { + Collection remainingElements = new ArrayList<>(); + remainingElements.addAll(targets); int index = lookupListIndex(validationType); for (ValidationRuleViolation vrv : pooledViolations.get(index)) { - if (notFound.remove(vrv.getElement())) { - if (notFound.isEmpty()) { - return notFound; + if (remainingElements.remove(vrv.getElement())) { + if (remainingElements.isEmpty()) { + return remainingElements; } } } - return notFound; - } - - /** - * Searches through all pooled violations for elements in the passed collection - * - * @param targets Elements to confirm the presence of in the validations - * @return Returns the subset of the elements that were not found in any pool - */ - public Collection confirmElementValidationResult(Collection targets) { - Collection notFound = new ArrayList(); - notFound.addAll(targets); - for (String[] sar : VALIDATION_OPTIONS) { - notFound = confirmElementValidationTypeResult(sar[RULE_VIOLATION_TYPE], notFound); - if (notFound.isEmpty()) { - return notFound; - } - } - return notFound; + return remainingElements; } /** @@ -636,40 +456,20 @@ public Collection confirmElementValidationResult(Collection ta * @param targetIDs Collection of strings to confirm the presence of in the validations * @return Returns the subset of the element IDss that were not found in the indicated pool */ - public Collection confirmElementValidationTypeResultByID(String validationType, Collection targetIDs) { - Collection notFound = new ArrayList(); - notFound.addAll(targetIDs); - validationType = standardize(validationType); + public Collection confirmElementViolationByID(String validationType, Collection targetIDs) { + Collection remainingElements = new ArrayList<>(); + remainingElements.addAll(targetIDs); int index = lookupListIndex(validationType); for (ValidationRuleViolation vrv : pooledViolations.get(index)) { - if (notFound.remove(getVRVElementID(vrv))) { - if (notFound.isEmpty()) { - return notFound; + if (remainingElements.remove(getVRVElementID(vrv))) { + if (remainingElements.isEmpty()) { + return remainingElements; } } } - return notFound; + return remainingElements; } - /** - * Searches through all pooled violations for element IDs in the passed collection - * - * @param targetIDs Collection of strings to confirm the presence of in the validations - * @return Returns the subset of the element IDs that were not found in any pool - */ - public Collection confirmElementValidationResultByID(Collection targetIDs) { - Collection notFound = new ArrayList(); - notFound.addAll(targetIDs); - for (String[] sar : VALIDATION_OPTIONS) { - notFound = confirmElementValidationTypeResultByID(sar[RULE_VIOLATION_TYPE], notFound); - if (notFound.isEmpty()) { - return notFound; - } - } - return notFound; - } - - /******************************************************************************** * * Deprecated methods @@ -678,7 +478,8 @@ public Collection confirmElementValidationResultByID(Collection // @Deprecated /* - * Non-reflection method for getting annotations and executing actions. Saved only in case it's instructive for something later on. Should not be made public or called. + * Non-reflection method for getting annotations and executing actions. Saved only in case it's instructive for + * something later on. Should not be made public or called. * * Exports all [ATTRIBUTE] validation results to MD * diff --git a/src/main/java/gov/nasa/jpl/mbee/mdk/ems/actions/EMSLoginAction.java b/src/main/java/gov/nasa/jpl/mbee/mdk/ems/actions/EMSLoginAction.java index 58967e54d..93950a36a 100644 --- a/src/main/java/gov/nasa/jpl/mbee/mdk/ems/actions/EMSLoginAction.java +++ b/src/main/java/gov/nasa/jpl/mbee/mdk/ems/actions/EMSLoginAction.java @@ -54,15 +54,15 @@ public void setLogoutAction(EMSLogoutAction logout) { @Override public void actionPerformed(ActionEvent e) { - loginAction(Application.getInstance().getProject(), "", ""); + loginAction(Application.getInstance().getProject()); ActionsStateUpdater.updateActionsState(); } - public boolean loginAction(Project project, String username, String password) { - return loginAction(project, username, password, true); + public boolean loginAction(Project project) { + return loginAction(project, true); } - public static boolean loginAction(Project project, String username, String password, boolean initJms) { + public static boolean loginAction(Project project, boolean initJms) { if (project == null) { Utils.showPopupMessage("You need to have a project open first!"); return false; diff --git a/src/main/java/gov/nasa/jpl/mbee/mdk/ems/actions/EMSLogoutAction.java b/src/main/java/gov/nasa/jpl/mbee/mdk/ems/actions/EMSLogoutAction.java index cc0d0f56d..9e8b6edb8 100644 --- a/src/main/java/gov/nasa/jpl/mbee/mdk/ems/actions/EMSLogoutAction.java +++ b/src/main/java/gov/nasa/jpl/mbee/mdk/ems/actions/EMSLogoutAction.java @@ -53,6 +53,10 @@ public void setLoginAction(EMSLoginAction login) { @Override public void actionPerformed(ActionEvent e) { + logoutAction(); + } + + public void logoutAction() { TicketUtils.clearUsernameAndPassword(); for (Project p : Application.getInstance().getProjectsManager().getProjects()) { MMSSyncPlugin.getInstance().getJmsSyncProjectEventListenerAdapter().projectClosed(p); diff --git a/src/main/java/gov/nasa/jpl/mbee/mdk/ems/sync/delta/DeltaSyncRunner.java b/src/main/java/gov/nasa/jpl/mbee/mdk/ems/sync/delta/DeltaSyncRunner.java index d1b57adff..f5ef55b3e 100644 --- a/src/main/java/gov/nasa/jpl/mbee/mdk/ems/sync/delta/DeltaSyncRunner.java +++ b/src/main/java/gov/nasa/jpl/mbee/mdk/ems/sync/delta/DeltaSyncRunner.java @@ -49,23 +49,22 @@ public class DeltaSyncRunner implements RunnableWithProgress { private boolean failure = true; - private ValidationSuite changelogSuite = new ValidationSuite("Updated Elements/Failed Updates"); - private ValidationRule locallyChangedValidationRule = new ValidationRule("updated", "updated", ViolationSeverity.INFO); - private ValidationRule cannotUpdate = new ValidationRule("cannotUpdate", "cannotUpdate", ViolationSeverity.ERROR); - private ValidationRule cannotRemove = new ValidationRule("cannotDelete", "cannotDelete", ViolationSeverity.WARNING); - private ValidationRule cannotCreate = new ValidationRule("cannotCreate", "cannotCreate", ViolationSeverity.ERROR); +// private ValidationSuite changelogSuite = new ValidationSuite("Updated Elements/Failed Updates"); +// private ValidationRule locallyChangedValidationRule = new ValidationRule("Updated Locally", "updated", ViolationSeverity.INFO); +// private ValidationRule cannotUpdate = new ValidationRule("Cannot Update", "cannotUpdate", ViolationSeverity.ERROR); +// private ValidationRule cannotRemove = new ValidationRule("Cannot Delete", "cannotDelete", ViolationSeverity.WARNING); +// private ValidationRule cannotCreate = new ValidationRule("Cannot Create", "cannotCreate", ViolationSeverity.ERROR); private Changelog failedLocalChangelog = new Changelog<>(); private Changelog failedJmsChangelog = new Changelog<>(), successfulJmsChangelog = new Changelog<>(); private List vss = new ArrayList<>(); - - { - changelogSuite.addValidationRule(locallyChangedValidationRule); - changelogSuite.addValidationRule(cannotUpdate); - changelogSuite.addValidationRule(cannotRemove); - changelogSuite.addValidationRule(cannotCreate); - } +// { +// changelogSuite.addValidationRule(locallyChangedValidationRule); +// changelogSuite.addValidationRule(cannotUpdate); +// changelogSuite.addValidationRule(cannotRemove); +// changelogSuite.addValidationRule(cannotCreate); +// } /*public DeltaSyncRunner(boolean shouldCommit, boolean skipUpdate, boolean shouldDelete) { this.shouldCommit = shouldCommit; @@ -73,10 +72,10 @@ public class DeltaSyncRunner implements RunnableWithProgress { this.shouldDelete = shouldDelete; }*/ - @Deprecated - public DeltaSyncRunner(boolean shouldCommit, boolean shouldCommitDeletes) { - this(shouldCommit, shouldCommitDeletes, true); - } +// @Deprecated +// public DeltaSyncRunner(boolean shouldCommit, boolean shouldCommitDeletes) { +// this(shouldCommit, shouldCommitDeletes, true); +// } public DeltaSyncRunner(boolean shouldCommmit, boolean shouldCommitDeletes, boolean shouldUpdate) { this.shouldCommit = shouldCommmit; diff --git a/src/main/java/gov/nasa/jpl/mbee/mdk/ems/sync/manual/ManualSyncRunner.java b/src/main/java/gov/nasa/jpl/mbee/mdk/ems/sync/manual/ManualSyncRunner.java index 11b2781bc..8c5a0b3e0 100644 --- a/src/main/java/gov/nasa/jpl/mbee/mdk/ems/sync/manual/ManualSyncRunner.java +++ b/src/main/java/gov/nasa/jpl/mbee/mdk/ems/sync/manual/ManualSyncRunner.java @@ -33,6 +33,8 @@ * Created by igomes on 9/26/16. */ public class ManualSyncRunner implements RunnableWithProgress { + + public static final String INITIALIZE_PROJECT_COMMENT = "The project doesn't exist on the web."; private final Collection rootElements; private final Project project; private final boolean recurse; @@ -183,7 +185,7 @@ public boolean checkProject() { String workspace = MMSUtils.getServiceWorkspacesUri(project).getPath(); if (workspace.contains("master")) { - v = new ValidationRuleViolation(project.getModel(), "The project doesn't exist on the web."); + v = new ValidationRuleViolation(project.getModel(), INITIALIZE_PROJECT_COMMENT); v.addAction(new CommitProjectAction(project, true)); } else { v = new ValidationRuleViolation(project.getModel(), "The trunk project doesn't exist on the web. Export the trunk first."); diff --git a/src/main/java/gov/nasa/jpl/mbee/mdk/lib/TicketUtils.java b/src/main/java/gov/nasa/jpl/mbee/mdk/lib/TicketUtils.java index 495484e42..4652d4009 100644 --- a/src/main/java/gov/nasa/jpl/mbee/mdk/lib/TicketUtils.java +++ b/src/main/java/gov/nasa/jpl/mbee/mdk/lib/TicketUtils.java @@ -81,21 +81,30 @@ public static boolean isTicketSet() { } /** + * Logs in to MMS, using pre-specified credentials or prompting the user for new credentials. * - * @return True if successfully logged in to MMS + * If username and password have been pre-specified, will not display the dialog even if popups are + * enabled. Else will display the login dialog and use the returned value. + * + * @return TRUE if successfully logged in to MMS, FALSE otherwise. + * Will always return FALSE if popups are disabled and username/password are not pre-specified */ public static boolean loginToMMS() { - if (!Utils.isPopupsDisabled()) { + if (!username.isEmpty() && !password.isEmpty()){ + acquireTicket(password); + } + else if (!Utils.isPopupsDisabled()) { acquireTicket(showLoginDialog()); } else { - acquireTicket(password); + return false; } return !ticket.isEmpty(); } /** * Shows a login dialog window and uses its filled in values to set the username and password. + * Stores the entered username for future use / convenience, passes the entered password to acquireTicket(). */ private static String showLoginDialog() { // Pop up dialog for logging into Alfresco @@ -186,8 +195,10 @@ public static void clearUsernameAndPassword() { } /** - * Uses the stored username and password to query MMS for a ticket. Will first check to see if an existing ticket is - * still valid, and will not resend for the ticket if it remains valid. + * Uses the stored username and passed password to query MMS for a ticket. + * + * Will first check to see if there is an existing ticket, and if so if it is valid. If valid, will not resend + * for new ticket. If invalid or not present, will send for new ticket. * * Since it can only be called by logInToMMS(), assumes that the username and password were recently * acquired from the login dialogue or pre-specified if that's disabled. @@ -203,7 +214,7 @@ private static void acquireTicket(String pass) { // build request // @donbot retained Application.getInstance().getProject() instead of making project agnostic because you can only - // log in to the currently opening project + // log in to the currently opening project Project project = Application.getInstance().getProject(); URIBuilder requestUri = MMSUtils.getServiceUri(project); if (requestUri == null || username.isEmpty() || pass.isEmpty()) { diff --git a/src/main/java/gov/nasa/jpl/mbee/pma/analyses/AutomatedViewGeneration.java b/src/main/java/gov/nasa/jpl/mbee/pma/analyses/AutomatedViewGeneration.java index bee888133..ac08f4cf1 100644 --- a/src/main/java/gov/nasa/jpl/mbee/pma/analyses/AutomatedViewGeneration.java +++ b/src/main/java/gov/nasa/jpl/mbee/pma/analyses/AutomatedViewGeneration.java @@ -7,6 +7,7 @@ import com.nomagic.teamwork.common.users.SessionInfo; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement; import gov.nasa.jpl.mbee.mdk.api.MDKHelper; +import gov.nasa.jpl.mbee.mdk.ems.MMSUtils; import gov.nasa.jpl.mbee.mdk.ems.ServerException; import javax.xml.bind.DatatypeConverter; @@ -245,7 +246,7 @@ private void checkSiteEditPermission() throws IOException, IllegalAccessExceptio throw new IllegalAccessException("Automated View Generation failed - User " + teamworkUsername + " can not log in to MMS server."); // LOG: Invalid account } - if (!MDKHelper.hasSiteEditPermission()) { + if (!MMSUtils.isSiteEditable(Application.getInstance().getProject(), MMSUtils.getSiteName(Application.getInstance().getProject()))) { String message = "[FAILURE] User " + teamworkUsername + " does not have permission to MMS site or MMS is unsupported version."; logMessage(message); error = 103;