diff options
8 files changed, 1638 insertions, 1525 deletions
diff --git a/extraplugins/table/org.eclipse.papyrus.infra.nattable/src/org/eclipse/papyrus/infra/nattable/manager/axis/CompositeAxisManager.java b/extraplugins/table/org.eclipse.papyrus.infra.nattable/src/org/eclipse/papyrus/infra/nattable/manager/axis/CompositeAxisManager.java index 3e08b875465..96d79c25702 100644 --- a/extraplugins/table/org.eclipse.papyrus.infra.nattable/src/org/eclipse/papyrus/infra/nattable/manager/axis/CompositeAxisManager.java +++ b/extraplugins/table/org.eclipse.papyrus.infra.nattable/src/org/eclipse/papyrus/infra/nattable/manager/axis/CompositeAxisManager.java @@ -171,6 +171,7 @@ public class CompositeAxisManager extends AbstractAxisManager implements ICompos */
@Override
public void dispose() {
+ super.dispose();
for(final IAxisManager current : this.subManagers) {
current.dispose();
}
diff --git a/plugins/sysml/org.eclipse.papyrus.sysml.service.types/META-INF/MANIFEST.MF b/plugins/sysml/org.eclipse.papyrus.sysml.service.types/META-INF/MANIFEST.MF index 1df4759d80e..705540b338a 100644 --- a/plugins/sysml/org.eclipse.papyrus.sysml.service.types/META-INF/MANIFEST.MF +++ b/plugins/sysml/org.eclipse.papyrus.sysml.service.types/META-INF/MANIFEST.MF @@ -11,7 +11,8 @@ Require-Bundle: org.eclipse.ui, org.eclipse.uml2.uml.profile.l2;bundle-version="1.0.0",
org.eclipse.core.expressions,
org.eclipse.papyrus.infra.tools;bundle-version="0.10.2",
- org.eclipse.papyrus.uml.diagram.common;bundle-version="0.10.2"
+ org.eclipse.papyrus.uml.diagram.common;bundle-version="0.10.2",
+ org.eclipse.papyrus.uml.tools.utils;bundle-version="0.10.2"
Export-Package: org.eclipse.papyrus.sysml.service.types,
org.eclipse.papyrus.sysml.service.types.command,
org.eclipse.papyrus.sysml.service.types.element,
@@ -30,4 +31,3 @@ Bundle-Activator: org.eclipse.papyrus.sysml.service.types.Activator Bundle-SymbolicName: org.eclipse.papyrus.sysml.service.types;singleton
:=true
Bundle-RequiredExecutionEnvironment: J2SE-1.5
-
diff --git a/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/advice/AssociationNoneEditHelperAdvice.java b/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/advice/AssociationNoneEditHelperAdvice.java index 0f69b4d04e0..a8794ba91cd 100644 --- a/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/advice/AssociationNoneEditHelperAdvice.java +++ b/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/advice/AssociationNoneEditHelperAdvice.java @@ -1,233 +1,233 @@ -/*****************************************************************************
- * Copyright (c) 2011-2012 CEA LIST.
- *
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- *
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.sysml.service.types.helper.advice;
-
-import java.util.List;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand;
-import org.eclipse.gmf.runtime.emf.type.core.commands.ConfigureElementCommand;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
-import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
-import org.eclipse.papyrus.sysml.service.types.Activator;
-import org.eclipse.papyrus.uml.service.types.utils.ClassifierUtils;
-import org.eclipse.papyrus.uml.service.types.utils.NamedElementHelper;
-import org.eclipse.uml2.uml.Association;
-import org.eclipse.uml2.uml.Classifier;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Property;
-import org.eclipse.uml2.uml.Type;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Edit helper advice for {@link Association} with "aggregation = none" (used for creation purpose only).
- */
-public class AssociationNoneEditHelperAdvice extends AssociationEditHelperAdvice {
-
- /**
- * This method provides the source type provided as {@link ConfigureRequest} parameter.
- *
- * @return the target role
- */
- protected Classifier getSourceOwnerType(ConfigureRequest req) {
- Classifier result = null;
- Object paramObject = req.getParameter(CreateRelationshipRequest.SOURCE);
- if(paramObject instanceof Classifier) {
- result = (Classifier)paramObject;
- }
-
- return result;
- }
-
- /**
- * This method provides the target type provided as {@link ConfigureRequest} parameter.
- *
- * @return the target role
- */
- protected Classifier getTargetOwnerType(ConfigureRequest req) {
- Classifier result = null;
- Object paramObject = req.getParameter(CreateRelationshipRequest.TARGET);
- if(paramObject instanceof Classifier) {
- result = (Classifier)paramObject;
- }
-
- return result;
- }
-
- /**
- * Creates a new {@link Property} from the propertyType in the propertyContainer
- *
- * @param propertyContainer
- * the container of the {@link Property}
- * @param propertyType
- * the type of the {@link Property}
- * @return the new {@link Property}
- * @throws ExecutionException
- */
- protected Property createTargetProperty(Property targetProperty, Classifier propertyContainer, Type propertyType, Association association, TransactionalEditingDomain editingDomain, IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException {
- addSourceInModel(targetProperty, propertyContainer, propertyType, association);
- setPropertyType(targetProperty, propertyType, editingDomain, progressMonitor, info);
- setPropertyName(targetProperty);
- return targetProperty;
- }
-
- protected Property createSourceProperty(Property sourceProperty, Classifier propertyContainer, Type propertyType, Association association, TransactionalEditingDomain editingDomain, IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException {
- addTargetInModel(sourceProperty, propertyContainer, propertyType, association);
- setPropertyType(sourceProperty, propertyType, editingDomain, progressMonitor, info);
- setPropertyName(sourceProperty);
- return sourceProperty;
- }
-
- protected void setPropertyType(Property property, Type propertyType, TransactionalEditingDomain editingDomain, IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException {
- // Set type using all AdviceHelper (use ServiceEdit instead of manually set)
- SetRequest request = new SetRequest(property, UMLPackage.eINSTANCE.getTypedElement_Type(), propertyType);
- request.setEditingDomain(editingDomain);
- IElementEditService commandProvider = ElementEditServiceUtils.getCommandProvider(property);
- ICommand editCommand = commandProvider.getEditCommand(request);
- editCommand.execute(progressMonitor, info);
- }
-
- private void setPropertyName(Property property) {
- String baseName = property.getType().getName().toLowerCase();
- Element owner = property.getOwner();
- if (owner instanceof Classifier) {
- List<Property> ownedAttributes = ClassifierUtils.getOwnedAttributes((Classifier)owner);
- String defaultNameWithIncrementFromBase = NamedElementHelper.getDefaultNameWithIncrementFromBase(
- property.getType().getName().toLowerCase(), ownedAttributes, "_");
- property.setName(defaultNameWithIncrementFromBase);
- }
- else {
- // default
- property.setName(baseName);
- }
- }
-
- /**
- * This method has to be specialized by subclasses (AggregationKind)
- * @param sourceProperty
- * The property to configure
- */
- protected void configureSourceProperty(Property sourceProperty) {
- // do nothing
- }
-
- /**
- * This method has to be specialized by subclasses (AggregationKind)
- * @param sourceProperty
- * The property to configure
- */
- protected void configureTargetProperty(Property targetProperty) {
- // do nothing
- }
-
- /**
- * This method has to be specialized by subclasses (owner)
- *
- * @param sourceEnd
- * the semantic end
- * @param owner
- * the end container
- * @param targetType
- * the target type
- * @param association
- * the association
- * @throws UnsupportedOperationException
- */
- protected void addSourceInModel(final Property sourceEnd, Classifier owner, Type targetType, Association association) throws UnsupportedOperationException {
- // set the container in order to allow Stereotype appliance
- boolean added = ClassifierUtils.addOwnedAttribute(owner, sourceEnd);
- if(!added) {
- throw new UnsupportedOperationException("Cannot add a Property on Classifier " + owner.getQualifiedName());
- }
- }
-
- /**
- * This method has to be specialized by subclasses (owner)
- *
- * @param targetEnd
- * the semantic end
- * @param owner
- * the end container
- * @param sourceType
- * the source type
- * @param association
- * the association
- * @throws UnsupportedOperationException
- */
- protected void addTargetInModel(Property targetEnd, Classifier owner, Type sourceType, Association association) {
- // set the container in order to allow Stereotype appliance
- boolean added = ClassifierUtils.addOwnedAttribute(owner, targetEnd);
- if(!added) {
- throw new UnsupportedOperationException("Cannot add a Property on Classifier " + owner.getQualifiedName());
- }
- }
-
- /**
- * <pre>
- * {@inheritDoc}
- *
- * Complete the {@link Association} creation by setting its ends.
- *
- * </pre>
- */
- @Override
- protected ICommand getBeforeConfigureCommand(final ConfigureRequest request) {
-
- final Association association = (Association)request.getElementToConfigure();
- final Classifier sourceType = getSourceOwnerType(request);
- final Classifier targetType = getTargetOwnerType(request);
-
- if((sourceType == null) || (targetType == null)) {
- return UnexecutableCommand.INSTANCE;
- }
-
- return new ConfigureElementCommand(request) {
-
- protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException {
-
- try {
- Property targetProperty = UMLFactory.eINSTANCE.createProperty();
- Property sourceProperty = UMLFactory.eINSTANCE.createProperty();
-
- // TODO: problem with SysML. Link are inversed. A -> B => memberEnd={a, b} instead of {b, a}.
- // Problem seems to come from cached derivedFeature /endTypes
- // So we force to set memberEnd in this order before doing anything with the created properties
- association.getMemberEnds().add(targetProperty);
- association.getMemberEnds().add(sourceProperty);
-
- // Create source and target ends
- createTargetProperty(targetProperty, sourceType, targetType, association, request.getEditingDomain(), progressMonitor, info);
- configureSourceProperty(targetProperty);
- createSourceProperty(sourceProperty, targetType, sourceType, association, request.getEditingDomain(), progressMonitor, info);
- configureTargetProperty(sourceProperty);
-
- } catch (Exception e) {
- Activator.log.error(e);
- return CommandResult.newCancelledCommandResult();
- }
-
- return CommandResult.newOKCommandResult(association);
- }
- };
- }
-}
+/***************************************************************************** + * Copyright (c) 2011-2012 CEA LIST. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.sysml.service.types.helper.advice; + +import java.util.List; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand; +import org.eclipse.gmf.runtime.emf.type.core.commands.ConfigureElementCommand; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils; +import org.eclipse.papyrus.infra.services.edit.service.IElementEditService; +import org.eclipse.papyrus.sysml.service.types.Activator; +import org.eclipse.papyrus.uml.service.types.utils.ClassifierUtils; +import org.eclipse.papyrus.uml.service.types.utils.NamedElementHelper; +import org.eclipse.uml2.uml.Association; +import org.eclipse.uml2.uml.Classifier; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Property; +import org.eclipse.uml2.uml.Type; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Edit helper advice for {@link Association} with "aggregation = none" (used for creation purpose only). + */ +public class AssociationNoneEditHelperAdvice extends AssociationEditHelperAdvice { + + /** + * This method provides the source type provided as {@link ConfigureRequest} parameter. + * + * @return the target role + */ + protected Classifier getSourceOwnerType(ConfigureRequest req) { + Classifier result = null; + Object paramObject = req.getParameter(CreateRelationshipRequest.SOURCE); + if(paramObject instanceof Classifier) { + result = (Classifier)paramObject; + } + + return result; + } + + /** + * This method provides the target type provided as {@link ConfigureRequest} parameter. + * + * @return the target role + */ + protected Classifier getTargetOwnerType(ConfigureRequest req) { + Classifier result = null; + Object paramObject = req.getParameter(CreateRelationshipRequest.TARGET); + if(paramObject instanceof Classifier) { + result = (Classifier)paramObject; + } + + return result; + } + + /** + * Creates a new {@link Property} from the propertyType in the propertyContainer + * + * @param propertyContainer + * the container of the {@link Property} + * @param propertyType + * the type of the {@link Property} + * @return the new {@link Property} + * @throws ExecutionException + */ + protected Property createTargetProperty(Property targetProperty, Classifier propertyContainer, Type propertyType, Association association, TransactionalEditingDomain editingDomain, IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { + setPropertyType(targetProperty, propertyType, editingDomain, progressMonitor, info); + setPropertyName(targetProperty); + return targetProperty; + } + + protected Property createSourceProperty(Property sourceProperty, Classifier propertyContainer, Type propertyType, Association association, TransactionalEditingDomain editingDomain, IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { + setPropertyType(sourceProperty, propertyType, editingDomain, progressMonitor, info); + setPropertyName(sourceProperty); + return sourceProperty; + } + + protected void setPropertyType(Property property, Type propertyType, TransactionalEditingDomain editingDomain, IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { + // Set type using all AdviceHelper (use ServiceEdit instead of manually set) + SetRequest request = new SetRequest(property, UMLPackage.eINSTANCE.getTypedElement_Type(), propertyType); + request.setEditingDomain(editingDomain); + IElementEditService commandProvider = ElementEditServiceUtils.getCommandProvider(property); + ICommand editCommand = commandProvider.getEditCommand(request); + editCommand.execute(progressMonitor, info); + } + + private void setPropertyName(Property property) { + String baseName = property.getType().getName().toLowerCase(); + Element owner = property.getOwner(); + if (owner instanceof Classifier) { + List<Property> ownedAttributes = ClassifierUtils.getOwnedAttributes((Classifier)owner); + String defaultNameWithIncrementFromBase = NamedElementHelper.getDefaultNameWithIncrementFromBase( + property.getType().getName().toLowerCase(), ownedAttributes, "_"); + property.setName(defaultNameWithIncrementFromBase); + } + else { + // default + property.setName(baseName); + } + } + + /** + * This method has to be specialized by subclasses (AggregationKind) + * @param sourceProperty + * The property to configure + */ + protected void configureSourceProperty(Property sourceProperty) { + // do nothing + } + + /** + * This method has to be specialized by subclasses (AggregationKind) + * @param sourceProperty + * The property to configure + */ + protected void configureTargetProperty(Property targetProperty) { + // do nothing + } + + /** + * This method has to be specialized by subclasses (owner) + * + * @param sourceEnd + * the semantic end + * @param owner + * the end container + * @param targetType + * the target type + * @param association + * the association + * @throws UnsupportedOperationException + */ + protected void addSourceInModel(final Property sourceEnd, Classifier owner, Type targetType, Association association) throws UnsupportedOperationException { + // set the container in order to allow Stereotype appliance + boolean added = ClassifierUtils.addOwnedAttribute(owner, sourceEnd); + if(!added) { + throw new UnsupportedOperationException("Cannot add a Property on Classifier " + owner.getQualifiedName()); + } + } + + /** + * This method has to be specialized by subclasses (owner) + * + * @param targetEnd + * the semantic end + * @param owner + * the end container + * @param sourceType + * the source type + * @param association + * the association + * @throws UnsupportedOperationException + */ + protected void addTargetInModel(Property targetEnd, Classifier owner, Type sourceType, Association association) { + // set the container in order to allow Stereotype appliance + boolean added = ClassifierUtils.addOwnedAttribute(owner, targetEnd); + if(!added) { + throw new UnsupportedOperationException("Cannot add a Property on Classifier " + owner.getQualifiedName()); + } + } + + /** + * <pre> + * {@inheritDoc} + * + * Complete the {@link Association} creation by setting its ends. + * + * </pre> + */ + @Override + protected ICommand getBeforeConfigureCommand(final ConfigureRequest request) { + + final Association association = (Association)request.getElementToConfigure(); + final Classifier sourceType = getSourceOwnerType(request); + final Classifier targetType = getTargetOwnerType(request); + + if((sourceType == null) || (targetType == null)) { + return UnexecutableCommand.INSTANCE; + } + + return new ConfigureElementCommand(request) { + + protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { + + try { + Property targetProperty = UMLFactory.eINSTANCE.createProperty(); + Property sourceProperty = UMLFactory.eINSTANCE.createProperty(); + + // TODO: problem with SysML. Link are inversed. A -> B => memberEnd={a, b} instead of {b, a}. + // Problem seems to come from cached derivedFeature /endTypes + // So we force to set memberEnd in this order before doing anything with the created properties + association.getMemberEnds().add(targetProperty); + association.getMemberEnds().add(sourceProperty); + + // Create source and target ends + addSourceInModel(targetProperty, sourceType, targetType, association); + addTargetInModel(sourceProperty, targetType, sourceType, association); + createTargetProperty(targetProperty, sourceType, targetType, association, request.getEditingDomain(), progressMonitor, info); + configureSourceProperty(targetProperty); + createSourceProperty(sourceProperty, targetType, sourceType, association, request.getEditingDomain(), progressMonitor, info); + configureTargetProperty(sourceProperty); + + } catch (Exception e) { + Activator.log.error(e); + return CommandResult.newCancelledCommandResult(); + } + + return CommandResult.newOKCommandResult(association); + } + }; + } +} diff --git a/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/advice/PropertyEditHelperAdvice.java b/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/advice/PropertyEditHelperAdvice.java index 5c174e570ae..316f82fe411 100644 --- a/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/advice/PropertyEditHelperAdvice.java +++ b/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/helper/advice/PropertyEditHelperAdvice.java @@ -1,316 +1,360 @@ -/*****************************************************************************
- * Copyright (c) 2011-2012 CEA LIST.
- *
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- *
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.sysml.service.types.helper.advice;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.common.core.command.AbstractCommand;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.gmf.runtime.emf.core.util.EMFCoreUtil;
-import org.eclipse.gmf.runtime.emf.type.core.ISpecializationType;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientRelationshipRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.dialogs.MessageDialogWithToggle;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
-import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
-import org.eclipse.papyrus.infra.services.edit.utils.RequestParameterConstants;
-import org.eclipse.papyrus.sysml.constraints.ConstraintBlock;
-import org.eclipse.papyrus.sysml.constraints.ConstraintProperty;
-import org.eclipse.papyrus.sysml.constraints.ConstraintsPackage;
-import org.eclipse.papyrus.sysml.service.types.Activator;
-import org.eclipse.papyrus.sysml.service.types.element.SysMLElementTypes;
-import org.eclipse.papyrus.uml.diagram.common.util.CrossReferencerUtil;
-import org.eclipse.papyrus.uml.service.types.utils.ElementUtil;
-import org.eclipse.papyrus.uml.service.types.utils.NamedElementHelper;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.uml2.uml.Association;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Port;
-import org.eclipse.uml2.uml.Property;
-import org.eclipse.uml2.uml.Type;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-import org.eclipse.uml2.uml.util.UMLUtil;
-import org.eclipse.uml2.uml.util.UMLUtil.StereotypeApplicationHelper;
-
-/**
- * <pre>
- * This HelperAdvice completes {@link Property} edit commands with:
- * - possibly required (sysML) association re-factor command.
- * </pre>
- */
-public class PropertyEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * <pre>
- * {@inheritDoc}
- *
- * While setting {@link Property} (excluding {@link Port} and {@link ConstraintParameter} type:
- * - add possibly required (sysML) association re-factor command when needed.
- * - add/remove possibly required ConstraintProperty stereotype when needed.
- * </pre>
- */
- @SuppressWarnings("unchecked")
- @Override
- protected ICommand getBeforeSetCommand(SetRequest request) {
- ICommand gmfCommand = super.getBeforeSetCommand(request);
-
- EObject elementToEdit = request.getElementToEdit();
- if((elementToEdit instanceof Property) && !(elementToEdit instanceof Port) &&
- (request.getFeature() == UMLPackage.eINSTANCE.getTypedElement_Type()) && (request.getValue() instanceof Type)) {
-
- Property propertyToEdit = (Property)elementToEdit;
-
- // SysML specification : all property typed by a ConstraintBlock must have a ContraintProperty stereotype applied
- if (request.getValue() instanceof org.eclipse.uml2.uml.Class) {
- ICommand stereotypeApplicationCommand = getConstraintPropertyStereotypeApplicationCommand(propertyToEdit, (org.eclipse.uml2.uml.Class)request.getValue(), request);
- gmfCommand = CompositeCommand.compose(gmfCommand, stereotypeApplicationCommand);
- }
-
- // Exclude ConstraintParameter (simple property without ConstraintProperty stereotype owned by a ConstraintBlock)
- if (propertyToEdit.eContainer() instanceof org.eclipse.uml2.uml.Class && UMLUtil.getStereotypeApplication((Element)propertyToEdit.eContainer(), ConstraintBlock.class) != null) {
- if (UMLUtil.getStereotypeApplication(propertyToEdit, ConstraintProperty.class) == null) {
- return gmfCommand;
- }
- }
-
- Association relatedAssociation = propertyToEdit.getAssociation();
-
- // The edited property has to be related to a SysML association
- if((relatedAssociation == null) || !(ElementUtil.hasNature(relatedAssociation, SysMLElementTypes.SYSML_NATURE))) {
-
- // If no association exist and the new type is a Block
- // (not a ConstraintBlock => a property typed by a ConstraintBlock is a ConstraintProperty, not a Part neither a Reference),
- // add the association
- if ((relatedAssociation == null)
- && ((ISpecializationType) SysMLElementTypes.BLOCK).getMatcher().matches((Type) request.getValue())
- && !((ISpecializationType) SysMLElementTypes.CONSTRAINT_BLOCK).getMatcher().matches((Type) request.getValue())
- && ((ISpecializationType) SysMLElementTypes.BLOCK).getMatcher().matches(propertyToEdit.eContainer())) {
-
- ICommand addAssociationCommand = getCreatePartAssociationCommand((org.eclipse.uml2.uml.Class)propertyToEdit.eContainer(), propertyToEdit, (org.eclipse.uml2.uml.Class)request.getValue());
- gmfCommand = CompositeCommand.compose(gmfCommand, addAssociationCommand);
- }
-
- return gmfCommand;
- }
-
- // Setting new type can be related to an association re-orient (or trigger the association re-orient)
- // Retrieve elements already under re-factor.
- List<EObject> currentlyRefactoredElements = (request.getParameter(RequestParameterConstants.ASSOCIATION_REFACTORED_ELEMENTS) != null) ? (List<EObject>)request.getParameter(RequestParameterConstants.ASSOCIATION_REFACTORED_ELEMENTS) : new ArrayList<EObject>();
- if(!currentlyRefactoredElements.contains(propertyToEdit)) {
- currentlyRefactoredElements.add(propertyToEdit);
- request.getParameters().put(RequestParameterConstants.ASSOCIATION_REFACTORED_ELEMENTS, currentlyRefactoredElements);
-
- // Current association already under re-factor ?
- if(currentlyRefactoredElements.contains(relatedAssociation)) {
- return gmfCommand;
- }
- }
-
- // If the new type is not a block, destroy related association
- // This must be done only if the setting of the property type is not part of an association re-orient (hence after the previous code-block),
- // otherwise there is no legitimate reason to destroy the existing association while re-orienting it.
- if (!((ISpecializationType) SysMLElementTypes.BLOCK).getMatcher().matches((Type) request.getValue()) && propertyToEdit.getType() != null) {
- ICommand destroyCommand = getDestroyPartAssociationCommand(relatedAssociation, propertyToEdit);
- gmfCommand = CompositeCommand.compose(gmfCommand, destroyCommand);
-
- return gmfCommand;
- }
-
- ICommand refactorCommand = getAssociationRefactoringCommand(propertyToEdit, relatedAssociation, request);
- gmfCommand = CompositeCommand.compose(gmfCommand, refactorCommand);
- }
-
- if(gmfCommand != null) {
- gmfCommand = gmfCommand.reduce();
- }
-
- return gmfCommand;
- }
-
- /**
- * Create a re-factoring command related to a Property move.
- *
- * @param setProperty
- * the property which type is set
- * @param associationToRefactor
- * the association to re-factor (re-orient action)
- * @param request
- * the original set request
- * @return the re-factoring command
- */
- private ICommand getAssociationRefactoringCommand(Property setProperty, Association associationToRefactor, SetRequest request) {
-
- Association relatedAssociation = setProperty.getAssociation(); // Should not be null, test before calling method.
-
- if (associationToRefactor.getMemberEnds().size() >= 2) {
- // Re-orient the related association (do not use edit service to avoid infinite loop here)
- int direction = ReorientRelationshipRequest.REORIENT_TARGET;
- if(setProperty == associationToRefactor.getMemberEnds().get(1)) {
- direction = ReorientRelationshipRequest.REORIENT_SOURCE;
- }
-
- ReorientRelationshipRequest reorientRequest = new ReorientRelationshipRequest(relatedAssociation, (Type)request.getValue(), setProperty.eContainer(), direction);
- reorientRequest.addParameters(request.getParameters());
-
- IElementEditService provider = ElementEditServiceUtils.getCommandProvider(relatedAssociation);
- if(provider != null) {
- return provider.getEditCommand(reorientRequest);
- }
- }
-
- return null;
- }
-
- /**
- * Create a part association creation command.
- *
- * @return the part association creation command
- */
- private ICommand getCreatePartAssociationCommand(final org.eclipse.uml2.uml.Class sourceBlock, final Property sourceProperty, final org.eclipse.uml2.uml.Class targetBlock) {
-
- return new AbstractCommand("Create part association") {
-
- @Override
- protected CommandResult doUndoWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected CommandResult doRedoWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException {
- Association association = UMLFactory.eINSTANCE.createAssociation();
-
- // Add the association in the model
- org.eclipse.uml2.uml.Package container = (org.eclipse.uml2.uml.Package)EMFCoreUtil.getLeastCommonContainer(Arrays.asList(new EObject[]{sourceBlock, targetBlock}), UMLPackage.eINSTANCE.getPackage());
- container.getPackagedElements().add(association);
-
- // Use existing Property as source...
- association.getMemberEnds().add(sourceProperty);
- // ... and create the opposite (unnamed) Property
- Property targetProperty = UMLFactory.eINSTANCE.createProperty();
- association.getOwnedEnds().add(targetProperty);
-
- // Set Association name
- // Initialize the element name based on the created IElementType
- String initializedName = NamedElementHelper.getDefaultNameWithIncrementFromBase(UMLPackage.eINSTANCE.getAssociation().getName(), association.eContainer().eContents());
- association.setName(initializedName);
-
- // Add SysML Nature on the new Association
- ElementUtil.addNature(association, SysMLElementTypes.SYSML_NATURE);
-
- return CommandResult.newOKCommandResult(association) ;
- }
- };
-
- }
-
- /**
- * Apply/remove the ConstraintProperty stereotype application
- *
- * @return the ConstraintProperty stereotype application command
- */
- private ICommand getConstraintPropertyStereotypeApplicationCommand(final Property sourceProperty, final org.eclipse.uml2.uml.Class targetBlock, final SetRequest request) {
-
- return new AbstractTransactionalCommand(request.getEditingDomain(), "Apply/Remove ConstraintProperty Stereotype", null) {
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException {
- // SysML specification : all property typed by a ConstraintBlock must have a ContraintProperty stereotype applied
- ConstraintProperty constraintPropertyApplication = UMLUtil.getStereotypeApplication(sourceProperty, ConstraintProperty.class);
- if (UMLUtil.getStereotypeApplication(targetBlock, ConstraintBlock.class) != null) {
- if (constraintPropertyApplication == null) {
- StereotypeApplicationHelper.INSTANCE.applyStereotype(sourceProperty, ConstraintsPackage.eINSTANCE.getConstraintProperty());
- final String diagramType = null;
- // Remove representations
- Set<View> memberViewsToDestroy = CrossReferencerUtil.getCrossReferencingViews(sourceProperty, diagramType);
- if (memberViewsToDestroy.size() != 0) {
- final IPreferenceStore store = Activator.getDefault().getPreferenceStore();
- final String DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY = "displayMessageForTypingActionPreferenceKey";
- boolean contains = store.contains(DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY);
- if(!contains) {
- store.setValue(DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY, MessageDialogWithToggle.NEVER);
- store.setDefault(DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY, MessageDialogWithToggle.NEVER);
- }
- final String hideValue = store.getString(DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY);
- if(!hideValue.equals(MessageDialogWithToggle.ALWAYS)) {
- int size = memberViewsToDestroy.size();
- MessageDialogWithToggle.openInformation(Display.getDefault().getActiveShell(),
- "Change Type Action",
- "WARNING! Typing a Property by a ConstraintBlock make this property become a ConstraintProperty. ConstraintProperty have a specific representation. "
- + "\nSo all representations of this property will be removed from the model (" + size + " occurence" + ((size > 1) ? "s" : "") + ")."
- , "Don't show this dialog the next time",
- false, store, DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY);
- }
-
- }
- for (View view : memberViewsToDestroy) {
- final DestroyElementRequest destroyRequest = new DestroyElementRequest(request.getEditingDomain(), view, false);
- final IElementEditService commandProvider = ElementEditServiceUtils.getCommandProvider(view);
- ICommand editCommand = commandProvider.getEditCommand(destroyRequest);
- editCommand.execute(progressMonitor, info);
- }
- }
- }
- else {
- if (constraintPropertyApplication != null) {
- StereotypeApplicationHelper.INSTANCE.removeFromContainmentList(sourceProperty, constraintPropertyApplication);
- }
- }
- return CommandResult.newOKCommandResult(sourceProperty) ;
- }
- };
- }
-
- /**
- * Create a part association destroy command.
- *
- * @return the part association destroy command
- */
- @SuppressWarnings("unchecked")
- private ICommand getDestroyPartAssociationCommand(Association partAssociation, Property propertyToEdit) {
-
- DestroyElementRequest request = new DestroyElementRequest(partAssociation, false);
- List<EObject> dependentsToKeep = Arrays.asList(new EObject[] { propertyToEdit });
- request.getParameters().put(RequestParameterConstants.DEPENDENTS_TO_KEEP, dependentsToKeep);
-
- IElementEditService provider = ElementEditServiceUtils.getCommandProvider(partAssociation.eContainer());
- if(provider == null) {
- return null;
- }
- ICommand destroyCommand = provider.getEditCommand(request);
-
- return destroyCommand;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011-2012 CEA LIST. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.sysml.service.types.helper.advice; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.common.core.command.AbstractCommand; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.gmf.runtime.emf.core.util.EMFCoreUtil; +import org.eclipse.gmf.runtime.emf.type.core.ISpecializationType; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyDependentsRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientRelationshipRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.dialogs.MessageDialogWithToggle; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils; +import org.eclipse.papyrus.infra.services.edit.service.IElementEditService; +import org.eclipse.papyrus.infra.services.edit.utils.RequestParameterConstants; +import org.eclipse.papyrus.sysml.constraints.ConstraintBlock; +import org.eclipse.papyrus.sysml.constraints.ConstraintProperty; +import org.eclipse.papyrus.sysml.constraints.ConstraintsPackage; +import org.eclipse.papyrus.sysml.service.types.Activator; +import org.eclipse.papyrus.sysml.service.types.element.SysMLElementTypes; +import org.eclipse.papyrus.sysml.service.types.utils.ConnectorUtils; +import org.eclipse.papyrus.uml.diagram.common.util.CrossReferencerUtil; +import org.eclipse.papyrus.uml.service.types.utils.ElementUtil; +import org.eclipse.papyrus.uml.service.types.utils.NamedElementHelper; +import org.eclipse.swt.widgets.Display; +import org.eclipse.uml2.uml.Association; +import org.eclipse.uml2.uml.Connector; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Port; +import org.eclipse.uml2.uml.Property; +import org.eclipse.uml2.uml.Type; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; +import org.eclipse.uml2.uml.util.UMLUtil; +import org.eclipse.uml2.uml.util.UMLUtil.StereotypeApplicationHelper; + +/** + * <pre> + * This HelperAdvice completes {@link Property} edit commands with: + * - possibly required (sysML) association re-factor command. + * </pre> + */ +public class PropertyEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * <pre> + * {@inheritDoc} + * + * While setting {@link Property} (excluding {@link Port} and {@link ConstraintParameter} type: + * - add possibly required (sysML) association re-factor command when needed. + * - add/remove possibly required ConstraintProperty stereotype when needed. + * </pre> + */ + @SuppressWarnings("unchecked") + @Override + protected ICommand getBeforeSetCommand(SetRequest request) { + ICommand gmfCommand = super.getBeforeSetCommand(request); + + EObject elementToEdit = request.getElementToEdit(); + if((elementToEdit instanceof Property) && !(elementToEdit instanceof Port) && (request.getFeature() == UMLPackage.eINSTANCE.getTypedElement_Type()) && (request.getValue() instanceof Type)) { + + Property propertyToEdit = (Property)elementToEdit; + + // SysML specification : all property typed by a ConstraintBlock must have a ContraintProperty stereotype applied + if(request.getValue() instanceof org.eclipse.uml2.uml.Class) { + ICommand stereotypeApplicationCommand = getConstraintPropertyStereotypeApplicationCommand(propertyToEdit, (org.eclipse.uml2.uml.Class)request.getValue(), request); + gmfCommand = CompositeCommand.compose(gmfCommand, stereotypeApplicationCommand); + } + + // Exclude ConstraintParameter (simple property without ConstraintProperty stereotype owned by a ConstraintBlock) + if(propertyToEdit.eContainer() instanceof org.eclipse.uml2.uml.Class && UMLUtil.getStereotypeApplication((Element)propertyToEdit.eContainer(), ConstraintBlock.class) != null) { + if(UMLUtil.getStereotypeApplication(propertyToEdit, ConstraintProperty.class) == null) { + return gmfCommand; + } + } + + Association relatedAssociation = propertyToEdit.getAssociation(); + + // The edited property has to be related to a SysML association + if((relatedAssociation == null) || !(ElementUtil.hasNature(relatedAssociation, SysMLElementTypes.SYSML_NATURE))) { + // If no association exist and the new type is a Block + // (not a ConstraintBlock => a property typed by a ConstraintBlock is a ConstraintProperty, not a Part neither a Reference), + // add the association + if((relatedAssociation == null) && ((ISpecializationType)SysMLElementTypes.BLOCK).getMatcher().matches((Type)request.getValue()) && !((ISpecializationType)SysMLElementTypes.CONSTRAINT_BLOCK).getMatcher().matches((Type)request.getValue()) && ((ISpecializationType)SysMLElementTypes.BLOCK).getMatcher().matches(propertyToEdit.eContainer())) { + ICommand addAssociationCommand = getCreatePartAssociationCommand((org.eclipse.uml2.uml.Class)propertyToEdit.eContainer(), propertyToEdit, (org.eclipse.uml2.uml.Class)request.getValue()); + gmfCommand = CompositeCommand.compose(gmfCommand, addAssociationCommand); + } + return gmfCommand; + } + + // Setting new type can be related to an association re-orient (or trigger the association re-orient) + // Retrieve elements already under re-factor. + List<EObject> currentlyRefactoredElements = (request.getParameter(RequestParameterConstants.ASSOCIATION_REFACTORED_ELEMENTS) != null) ? (List<EObject>)request.getParameter(RequestParameterConstants.ASSOCIATION_REFACTORED_ELEMENTS) : new ArrayList<EObject>(); + if(!currentlyRefactoredElements.contains(propertyToEdit)) { + currentlyRefactoredElements.add(propertyToEdit); + request.getParameters().put(RequestParameterConstants.ASSOCIATION_REFACTORED_ELEMENTS, currentlyRefactoredElements); + + // Current association already under re-factor ? + if(currentlyRefactoredElements.contains(relatedAssociation)) { + return gmfCommand; + } + } + + // If the new type is not a block, destroy related association + // This must be done only if the setting of the property type is not part of an association re-orient (hence after the previous code-block), + // otherwise there is no legitimate reason to destroy the existing association while re-orienting it. + if(!((ISpecializationType)SysMLElementTypes.BLOCK).getMatcher().matches((Type)request.getValue()) && propertyToEdit.getType() != null) { + ICommand destroyCommand = getDestroyPartAssociationCommand(relatedAssociation, propertyToEdit); + gmfCommand = CompositeCommand.compose(gmfCommand, destroyCommand); + return gmfCommand; + } + + ICommand refactorCommand = getAssociationRefactoringCommand(propertyToEdit, relatedAssociation, request); + gmfCommand = CompositeCommand.compose(gmfCommand, refactorCommand); + } + + if(gmfCommand != null) { + gmfCommand = gmfCommand.reduce(); + } + + return gmfCommand; + } + + /** + * + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param setRequest + * @return + */ + @Override + protected ICommand getAfterSetCommand(SetRequest setRequest) { + ICommand afterSetCommand = super.getAfterSetCommand(setRequest); + EObject elementToEdit = setRequest.getElementToEdit(); + if((elementToEdit instanceof Property) && !(elementToEdit instanceof Port) && (setRequest.getFeature() == UMLPackage.eINSTANCE.getTypedElement_Type()) && (setRequest.getValue() instanceof Type)) { + afterSetCommand = getDestroyAssociatedNestedConnectorCommand((Property)elementToEdit, afterSetCommand); + } + return afterSetCommand; + } + + /** + * + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterDestroyDependentsCommand(org.eclipse.gmf.runtime.emf.type.core.requests.DestroyDependentsRequest) + * + * @param destroyDependentsRequest + * @return + */ + @Override + protected ICommand getAfterDestroyDependentsCommand(DestroyDependentsRequest destroyDependentsRequest) { + ICommand afterDestroyDependentsCommand = super.getAfterDestroyDependentsCommand(destroyDependentsRequest); + EObject elementToDestroy = destroyDependentsRequest.getElementToDestroy(); + if(elementToDestroy instanceof Property) { + afterDestroyDependentsCommand = getDestroyAssociatedNestedConnectorCommand((Property)elementToDestroy, afterDestroyDependentsCommand); + } + return afterDestroyDependentsCommand; + } + + /** + * Create a destroy command for all connectors that have this property in their <NestedConnectorEnd> property path. + * + * @param property + * the part to be destroyed + * @param command + * @return + */ + private ICommand getDestroyAssociatedNestedConnectorCommand(Property property, ICommand command) { + List<Connector> instancesFilteredByType = org.eclipse.papyrus.uml.tools.utils.ElementUtil.getInstancesFilteredByType(property.getModel(), Connector.class, null); + List<Connector> connectorToDestroy = ConnectorUtils.filterConnectorByPropertyInNestedConnectorEnd(instancesFilteredByType, (Property)property); + for(Connector connector : connectorToDestroy) { + ICommand destroyConnectorCommand = getDestroyConnectorCommand(connector); + command = CompositeCommand.compose(command, destroyConnectorCommand); + } + return command; + } + + /** + * Create a connector destroy command. + * + * @param connector + * @return the connector destroy command + */ + private ICommand getDestroyConnectorCommand(Connector connector) { + DestroyElementRequest request = new DestroyElementRequest(connector, false); + IElementEditService provider = ElementEditServiceUtils.getCommandProvider(connector.eContainer()); + if(provider == null) { + return null; + } + return provider.getEditCommand(request); + } + + /** + * Create a re-factoring command related to a Property move. + * + * @param setProperty + * the property which type is set + * @param associationToRefactor + * the association to re-factor (re-orient action) + * @param request + * the original set request + * @return the re-factoring command + */ + private ICommand getAssociationRefactoringCommand(Property setProperty, Association associationToRefactor, SetRequest request) { + + Association relatedAssociation = setProperty.getAssociation(); // Should not be null, test before calling method. + + if(associationToRefactor.getMemberEnds().size() >= 2) { + // Re-orient the related association (do not use edit service to avoid infinite loop here) + int direction = ReorientRelationshipRequest.REORIENT_TARGET; + if(setProperty == associationToRefactor.getMemberEnds().get(1)) { + direction = ReorientRelationshipRequest.REORIENT_SOURCE; + } + ReorientRelationshipRequest reorientRequest = new ReorientRelationshipRequest(relatedAssociation, (Type)request.getValue(), setProperty.eContainer(), direction); + reorientRequest.addParameters(request.getParameters()); + IElementEditService provider = ElementEditServiceUtils.getCommandProvider(relatedAssociation); + if(provider != null) { + return provider.getEditCommand(reorientRequest); + } + } + + return null; + } + + /** + * Create a part association creation command. + * + * @return the part association creation command + */ + private ICommand getCreatePartAssociationCommand(final org.eclipse.uml2.uml.Class sourceBlock, final Property sourceProperty, final org.eclipse.uml2.uml.Class targetBlock) { + return new AbstractCommand("Create part association") { + + @Override + protected CommandResult doUndoWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { + // TODO Auto-generated method stub + return null; + } + + @Override + protected CommandResult doRedoWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { + // TODO Auto-generated method stub + return null; + } + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { + Association association = UMLFactory.eINSTANCE.createAssociation(); + // Add the association in the model + org.eclipse.uml2.uml.Package container = (org.eclipse.uml2.uml.Package)EMFCoreUtil.getLeastCommonContainer(Arrays.asList(new EObject[]{ sourceBlock, targetBlock }), UMLPackage.eINSTANCE.getPackage()); + container.getPackagedElements().add(association); + // Use existing Property as source... + association.getMemberEnds().add(sourceProperty); + // ... and create the opposite (unnamed) Property + Property targetProperty = UMLFactory.eINSTANCE.createProperty(); + association.getOwnedEnds().add(targetProperty); + + // Set Association name + // Initialize the element name based on the created IElementType + String initializedName = NamedElementHelper.getDefaultNameWithIncrementFromBase(UMLPackage.eINSTANCE.getAssociation().getName(), association.eContainer().eContents()); + association.setName(initializedName); + // Add SysML Nature on the new Association + ElementUtil.addNature(association, SysMLElementTypes.SYSML_NATURE); + return CommandResult.newOKCommandResult(association); + } + }; + + } + + /** + * Apply/remove the ConstraintProperty stereotype application + * + * @return the ConstraintProperty stereotype application command + */ + private ICommand getConstraintPropertyStereotypeApplicationCommand(final Property sourceProperty, final org.eclipse.uml2.uml.Class targetBlock, final SetRequest request) { + return new AbstractTransactionalCommand(request.getEditingDomain(), "Apply/Remove ConstraintProperty Stereotype", null) { + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { + // SysML specification : all property typed by a ConstraintBlock must have a ContraintProperty stereotype applied + ConstraintProperty constraintPropertyApplication = UMLUtil.getStereotypeApplication(sourceProperty, ConstraintProperty.class); + if(UMLUtil.getStereotypeApplication(targetBlock, ConstraintBlock.class) != null) { + if(constraintPropertyApplication == null) { + StereotypeApplicationHelper.INSTANCE.applyStereotype(sourceProperty, ConstraintsPackage.eINSTANCE.getConstraintProperty()); + final String diagramType = null; + // Remove representations + Set<View> memberViewsToDestroy = CrossReferencerUtil.getCrossReferencingViews(sourceProperty, diagramType); + if(memberViewsToDestroy.size() != 0) { + final IPreferenceStore store = Activator.getDefault().getPreferenceStore(); + final String DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY = "displayMessageForTypingActionPreferenceKey"; + boolean contains = store.contains(DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY); + if(!contains) { + store.setValue(DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY, MessageDialogWithToggle.NEVER); + store.setDefault(DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY, MessageDialogWithToggle.NEVER); + } + final String hideValue = store.getString(DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY); + if(!hideValue.equals(MessageDialogWithToggle.ALWAYS)) { + int size = memberViewsToDestroy.size(); + MessageDialogWithToggle.openInformation(Display.getDefault().getActiveShell(), "Change Type Action", "WARNING! Typing a Property by a ConstraintBlock make this property become a ConstraintProperty. ConstraintProperty have a specific representation. " + "\nSo all representations of this property will be removed from the model (" + size + " occurence" + ((size > 1) ? "s" : "") + ").", "Don't show this dialog the next time", false, store, DISPLAY_MESSAGE_FOR_TYPING_ACTION_PREFERENCE_KEY); + } + } + for(View view : memberViewsToDestroy) { + final DestroyElementRequest destroyRequest = new DestroyElementRequest(request.getEditingDomain(), view, false); + final IElementEditService commandProvider = ElementEditServiceUtils.getCommandProvider(view); + ICommand editCommand = commandProvider.getEditCommand(destroyRequest); + editCommand.execute(progressMonitor, info); + } + } + } else { + if(constraintPropertyApplication != null) { + StereotypeApplicationHelper.INSTANCE.removeFromContainmentList(sourceProperty, constraintPropertyApplication); + } + } + return CommandResult.newOKCommandResult(sourceProperty); + } + }; + } + + /** + * Create a part association destroy command. + * + * @return the part association destroy command + */ + @SuppressWarnings("unchecked") + private ICommand getDestroyPartAssociationCommand(Association partAssociation, Property propertyToEdit) { + DestroyElementRequest request = new DestroyElementRequest(partAssociation, false); + List<EObject> dependentsToKeep = Arrays.asList(new EObject[]{ propertyToEdit }); + request.getParameters().put(RequestParameterConstants.DEPENDENTS_TO_KEEP, dependentsToKeep); + IElementEditService provider = ElementEditServiceUtils.getCommandProvider(partAssociation.eContainer()); + if(provider == null) { + return null; + } + ICommand destroyCommand = provider.getEditCommand(request); + return destroyCommand; + } +} diff --git a/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/utils/ConnectorUtils.java b/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/utils/ConnectorUtils.java index d9d723e6e10..4033a75abbd 100644 --- a/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/utils/ConnectorUtils.java +++ b/plugins/sysml/org.eclipse.papyrus.sysml.service.types/src/org/eclipse/papyrus/sysml/service/types/utils/ConnectorUtils.java @@ -19,6 +19,7 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.papyrus.sysml.blocks.Block; @@ -428,4 +429,33 @@ public class ConnectorUtils extends org.eclipse.papyrus.uml.service.types.utils. } return true; } + + + + /** + * Filter connectors that have this property in their <NestedConnectorEnd> property path. + * @param connectors + * @param part + * @return connectors that have this property in their <NestedConnectorEnd> property path. + */ + public static List<Connector> filterConnectorByPropertyInNestedConnectorEnd(List<Connector> connectors, Property part) { + List<Connector> res = new ArrayList<Connector>(); + for(Connector connector : connectors) { + EList<ConnectorEnd> ends = connector.getEnds(); + for(ConnectorEnd connectorEnd : ends) { + NestedConnectorEnd stereotypeApplication = UMLUtil.getStereotypeApplication(connectorEnd, NestedConnectorEnd.class); + if (stereotypeApplication != null){ + EList<Property> propertyPath = stereotypeApplication.getPropertyPath(); + for(Property property : propertyPath) { + if (property.equals(part)){ + res.add(connector); + } + } + } + } + } + return res; + } + + } diff --git a/plugins/sysml/org.eclipse.papyrus.sysml/src/org/eclipse/papyrus/sysml/util/SysmlResource.java b/plugins/sysml/org.eclipse.papyrus.sysml/src/org/eclipse/papyrus/sysml/util/SysmlResource.java index b432ffae4c9..b1d3bc81b46 100644 --- a/plugins/sysml/org.eclipse.papyrus.sysml/src/org/eclipse/papyrus/sysml/util/SysmlResource.java +++ b/plugins/sysml/org.eclipse.papyrus.sysml/src/org/eclipse/papyrus/sysml/util/SysmlResource.java @@ -1,213 +1,220 @@ -/*****************************************************************************
- * Copyright (c) 2009 CEA LIST.
- *
- *
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Yann Tanguy (CEA LIST) yann.tanguy@cea.fr - Initial API and implementation
- * Vincent Lorenzo (CEA LIST) vincent.lorenzo@cea.fr
- *****************************************************************************/
-package org.eclipse.papyrus.sysml.util;
-
-import org.eclipse.papyrus.sysml.SysmlPackage;
-
-public class SysmlResource {
-
- public static final String LIBRARIES_PATHMAP = "pathmap://SysML_LIBRARIES/"; //$NON-NLS-1$
-
- public static final String SYSML_PRIMITIVE_TYPES_LIBRARY_URI = LIBRARIES_PATHMAP + "SysMLPrimitiveTypes.uml"; //$NON-NLS-1$
-
- public static final String PROFILES_PATHMAP = "pathmap://SysML_PROFILES/"; //$NON-NLS-1$
-
- public static final String SYSML_PROFILE_NS_URI = SysmlPackage.eNS_URI;
-
- public static final String SYSML_PROFILE_URI = PROFILES_PATHMAP + "SysML.profile.uml"; //$NON-NLS-1$
-
- // Stereotypes ids
- @Deprecated
- public static String CONFORM_ID = "SysML::ModelElements::Conform";
-
- @Deprecated
- public static String VIEW_ID = "SysML::ModelElements::View";
-
- @Deprecated
- public static String VIEW_POINT_ID = "SysML::ModelElements::ViewPoint";
-
- /**
- * @deprecated use VIEW_POINT_ID instead
- */
- public static String VIEWPOINT_ID = VIEW_POINT_ID;
-
- @Deprecated
- public static String RATIONALE_ID = "SysML::ModelElements::Rationale";
-
- @Deprecated
- public static String PROBLEM_ID = "SysML::ModelElements::Problem";
-
- @Deprecated
- public static String BLOCK_ID = "SysML::Blocks::Block";
-
- @Deprecated
- public static String DISTRIBUTED_PROPERTY_ID = "SysML::Blocks::DistributedProperty";
-
- @Deprecated
- public static String DIMENSION_ID = "SysML::Blocks::Dimension";
-
- @Deprecated
- public static String UNIT_ID = "SysML::Blocks::Unit";
-
- @Deprecated
- public static String VALUE_TYPE_ID = "SysML::Blocks::ValueType";
-
- @Deprecated
- public static String NESTED_CONNECTOR_END_ID = "SysML::Blocks::NestedConnectorEnd";
-
- /** @deprecated use NESTED_CONNECTOR_END_ID instead */
- public static String NESTED_CONNECTOREND_ID = NESTED_CONNECTOR_END_ID;
-
- @Deprecated
- public static String PARTICIPANT_PROPERTY_ID = "SysML::Blocks::ParticipantProperty";
-
- @Deprecated
- public static String CONNECTOR_PROPERTY_ID = "SysML::Blocks::ConnectorProperty";
-
- @Deprecated
- public static String BINDING_CONNECTOR_ID = "SysML::Blocks::BindingConnector";
-
- @Deprecated
- public static String PROPERTY_SPECIFIC_TYPE_ID = "SysML::Blocks::PropertySpecificType";
-
- @Deprecated
- public static String FLOW_PORT_ID = "SysML::PortAndFlows::FlowPort";
-
- @Deprecated
- public static String FLOW_PROPERTY_ID = "SysML::PortAndFlows::FlowProperty";
-
- @Deprecated
- public static String FLOW_SPECIFICATION_ID = "SysML::PortAndFlows::FlowSpecification";
-
- @Deprecated
- public static String ITEM_FLOW_ID = "SysML::PortAndFlows::ItemFlow";
-
- @Deprecated
- public static String CONSTRAINT_BLOCK_ID = "SysML::Constraints::ConstraintBlock";
-
- @Deprecated
- public static String CONSTRAINT_PROPERTY_ID = "SysML::Constraints::ConstraintProperty";
-
- @Deprecated
- public static String OPTIONAL_ID = "SysML::Activities::Optional";
-
- @Deprecated
- public static String RATE_ID = "SysML::Activities::Rate";
-
- @Deprecated
- public static String PROBABILITY_ID = "SysML::Activities::Probability";
-
- @Deprecated
- public static String CONTINUOUS_ID = "SysML::Activities::Continuous";
-
- @Deprecated
- public static String DISCRETE_ID = "SysML::Activities::Discrete";
-
- @Deprecated
- public static String CONTROL_OPERATOR_ID = "SysML::Activities::ControlOperator";
-
- @Deprecated
- public static String NO_BUFFER_ID = "SysML::Activities::NoBuffer";
-
- @Deprecated
- public static String OVERWRITE_ID = "SysML::Activities::Overwrite";
-
- @Deprecated
- public static String ALLOCATE_ID = "SysML::Allocations::Allocate";
-
- @Deprecated
- public static String ALLOCATED_ID = "SysML::Allocations::Allocated";
-
- @Deprecated
- public static String ALLOCATE_ACTIVITY_PARTITION_ID = "SysML::Allocations::AllocateActivityPartition";
-
- @Deprecated
- public static String DERIVE_REQT_ID = "SysML::Requirements::DeriveReqt";
-
- @Deprecated
- public static String VERIFY_ID = "SysML::Requirements::Verify";
-
- @Deprecated
- public static String COPY_ID = "SysML::Requirements::Copy";
-
- @Deprecated
- public static String SATISFY_ID = "SysML::Requirements::Satisfy";
-
- @Deprecated
- public static String TEST_CASE_ID = "SysML::Requirements::TestCase";
-
- @Deprecated
- public static String REQUIREMENT_ID = "SysML::Requirements::Requirement";
-
- @Deprecated
- public static String REQUIREMENT_RELATED_ID = "SysML::Requirements::RequirementRelated";
-
- // SubProfiles ids
- @Deprecated
- public static String SYSML_ID = "SysML";
-
- @Deprecated
- public static String MODEL_ELEMENTS_ID = "SysML::ModelElements";
-
- @Deprecated
- public static String BLOCKS_ID = "SysML::Blocks";
-
- @Deprecated
- public static String PORT_AND_FLOWS_ID = "SysML::PortAndFlows";
-
- @Deprecated
- public static String CONSTRAINTS_ID = "SysML::Constraints";
-
- @Deprecated
- public static String ACTIVITIES_ID = "SysML::Activities";
-
- @Deprecated
- public static String ALLOCATIONS_ID = "SysML::Allocations";
-
- @Deprecated
- public static String REQUIREMENTS_ID = "SysML::Requirements";
-
- // stereotype properties ids
- // requirements properties
- @Deprecated
- public static String REQUIREMENT_BASE_CLASS_ID = "base_Class"; //$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_DERIVED_ID = "derived"; //$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_DERIVED_FROM_ID = "derivedFrom";//$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_ID_ID = "id";//$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_MASTER_ID = "master";//$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_REFINED_BY_ID = "refinedBy";//$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_SATISFIED_BY_ID = "satisfiedBy";//$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_TEXT_ID = "text";//$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_TRACED_TO_ID = "tracedTo";//$NON-NLS-1$
-
- @Deprecated
- public static String REQUIREMENT_VERIFIED_BY_ID = "verifiedBy";//$NON-NLS-1$
-
-}
+/***************************************************************************** + * Copyright (c) 2009 CEA LIST. + * + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Yann Tanguy (CEA LIST) yann.tanguy@cea.fr - Initial API and implementation + * Vincent Lorenzo (CEA LIST) vincent.lorenzo@cea.fr + *****************************************************************************/ +package org.eclipse.papyrus.sysml.util; + +import org.eclipse.papyrus.sysml.SysmlPackage; + +/** + * For all deprecated : use org.eclipse.uml2.uml.util.UMLUtil.getStereotypeApplication + * Ex : + * replace appliedStereotype = connectorEnd.getAppliedStereotype("SysML::Blocks::NestedConnectorEnd");connectorEnd.getStereotypeApplication(appliedStereotype); + * by org.eclipse.uml2.uml.util.UMLUtil.getStereotypeApplication(element, NestedConnectorEnd.class); + */ +public class SysmlResource { + + public static final String LIBRARIES_PATHMAP = "pathmap://SysML_LIBRARIES/"; //$NON-NLS-1$ + + public static final String SYSML_PRIMITIVE_TYPES_LIBRARY_URI = LIBRARIES_PATHMAP + "SysMLPrimitiveTypes.uml"; //$NON-NLS-1$ + + public static final String PROFILES_PATHMAP = "pathmap://SysML_PROFILES/"; //$NON-NLS-1$ + + public static final String SYSML_PROFILE_NS_URI = SysmlPackage.eNS_URI; + + public static final String SYSML_PROFILE_URI = PROFILES_PATHMAP + "SysML.profile.uml"; //$NON-NLS-1$ + + + // Stereotypes ids + @Deprecated + public static String CONFORM_ID = "SysML::ModelElements::Conform"; + + @Deprecated + public static String VIEW_ID = "SysML::ModelElements::View"; + + @Deprecated + public static String VIEW_POINT_ID = "SysML::ModelElements::ViewPoint"; + + /** + * @deprecated use VIEW_POINT_ID instead + */ + public static String VIEWPOINT_ID = VIEW_POINT_ID; + + @Deprecated + public static String RATIONALE_ID = "SysML::ModelElements::Rationale"; + + @Deprecated + public static String PROBLEM_ID = "SysML::ModelElements::Problem"; + + @Deprecated + public static String BLOCK_ID = "SysML::Blocks::Block"; + + @Deprecated + public static String DISTRIBUTED_PROPERTY_ID = "SysML::Blocks::DistributedProperty"; + + @Deprecated + public static String DIMENSION_ID = "SysML::Blocks::Dimension"; + + @Deprecated + public static String UNIT_ID = "SysML::Blocks::Unit"; + + @Deprecated + public static String VALUE_TYPE_ID = "SysML::Blocks::ValueType"; + + @Deprecated + public static String NESTED_CONNECTOR_END_ID = "SysML::Blocks::NestedConnectorEnd"; + + /** @deprecated use NESTED_CONNECTOR_END_ID instead */ + public static String NESTED_CONNECTOREND_ID = NESTED_CONNECTOR_END_ID; + + @Deprecated + public static String PARTICIPANT_PROPERTY_ID = "SysML::Blocks::ParticipantProperty"; + + @Deprecated + public static String CONNECTOR_PROPERTY_ID = "SysML::Blocks::ConnectorProperty"; + + @Deprecated + public static String BINDING_CONNECTOR_ID = "SysML::Blocks::BindingConnector"; + + @Deprecated + public static String PROPERTY_SPECIFIC_TYPE_ID = "SysML::Blocks::PropertySpecificType"; + + @Deprecated + public static String FLOW_PORT_ID = "SysML::PortAndFlows::FlowPort"; + + @Deprecated + public static String FLOW_PROPERTY_ID = "SysML::PortAndFlows::FlowProperty"; + + @Deprecated + public static String FLOW_SPECIFICATION_ID = "SysML::PortAndFlows::FlowSpecification"; + + @Deprecated + public static String ITEM_FLOW_ID = "SysML::PortAndFlows::ItemFlow"; + + @Deprecated + public static String CONSTRAINT_BLOCK_ID = "SysML::Constraints::ConstraintBlock"; + + @Deprecated + public static String CONSTRAINT_PROPERTY_ID = "SysML::Constraints::ConstraintProperty"; + + @Deprecated + public static String OPTIONAL_ID = "SysML::Activities::Optional"; + + @Deprecated + public static String RATE_ID = "SysML::Activities::Rate"; + + @Deprecated + public static String PROBABILITY_ID = "SysML::Activities::Probability"; + + @Deprecated + public static String CONTINUOUS_ID = "SysML::Activities::Continuous"; + + @Deprecated + public static String DISCRETE_ID = "SysML::Activities::Discrete"; + + @Deprecated + public static String CONTROL_OPERATOR_ID = "SysML::Activities::ControlOperator"; + + @Deprecated + public static String NO_BUFFER_ID = "SysML::Activities::NoBuffer"; + + @Deprecated + public static String OVERWRITE_ID = "SysML::Activities::Overwrite"; + + @Deprecated + public static String ALLOCATE_ID = "SysML::Allocations::Allocate"; + + @Deprecated + public static String ALLOCATED_ID = "SysML::Allocations::Allocated"; + + @Deprecated + public static String ALLOCATE_ACTIVITY_PARTITION_ID = "SysML::Allocations::AllocateActivityPartition"; + + @Deprecated + public static String DERIVE_REQT_ID = "SysML::Requirements::DeriveReqt"; + + @Deprecated + public static String VERIFY_ID = "SysML::Requirements::Verify"; + + @Deprecated + public static String COPY_ID = "SysML::Requirements::Copy"; + + @Deprecated + public static String SATISFY_ID = "SysML::Requirements::Satisfy"; + + @Deprecated + public static String TEST_CASE_ID = "SysML::Requirements::TestCase"; + + @Deprecated + public static String REQUIREMENT_ID = "SysML::Requirements::Requirement"; + + @Deprecated + public static String REQUIREMENT_RELATED_ID = "SysML::Requirements::RequirementRelated"; + + // SubProfiles ids + @Deprecated + public static String SYSML_ID = "SysML"; + + @Deprecated + public static String MODEL_ELEMENTS_ID = "SysML::ModelElements"; + + @Deprecated + public static String BLOCKS_ID = "SysML::Blocks"; + + @Deprecated + public static String PORT_AND_FLOWS_ID = "SysML::PortAndFlows"; + + @Deprecated + public static String CONSTRAINTS_ID = "SysML::Constraints"; + + @Deprecated + public static String ACTIVITIES_ID = "SysML::Activities"; + + @Deprecated + public static String ALLOCATIONS_ID = "SysML::Allocations"; + + @Deprecated + public static String REQUIREMENTS_ID = "SysML::Requirements"; + + // stereotype properties ids + // requirements properties + @Deprecated + public static String REQUIREMENT_BASE_CLASS_ID = "base_Class"; //$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_DERIVED_ID = "derived"; //$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_DERIVED_FROM_ID = "derivedFrom";//$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_ID_ID = "id";//$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_MASTER_ID = "master";//$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_REFINED_BY_ID = "refinedBy";//$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_SATISFIED_BY_ID = "satisfiedBy";//$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_TEXT_ID = "text";//$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_TRACED_TO_ID = "tracedTo";//$NON-NLS-1$ + + @Deprecated + public static String REQUIREMENT_VERIFIED_BY_ID = "verifiedBy";//$NON-NLS-1$ + +} diff --git a/plugins/uml/tools/org.eclipse.papyrus.uml.tools.utils/src/org/eclipse/papyrus/uml/tools/utils/ElementUtil.java b/plugins/uml/tools/org.eclipse.papyrus.uml.tools.utils/src/org/eclipse/papyrus/uml/tools/utils/ElementUtil.java index f2d17196218..80546c1f6c1 100644 --- a/plugins/uml/tools/org.eclipse.papyrus.uml.tools.utils/src/org/eclipse/papyrus/uml/tools/utils/ElementUtil.java +++ b/plugins/uml/tools/org.eclipse.papyrus.uml.tools.utils/src/org/eclipse/papyrus/uml/tools/utils/ElementUtil.java @@ -30,6 +30,7 @@ import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.uml2.uml.Element; import org.eclipse.uml2.uml.ElementImport; import org.eclipse.uml2.uml.Image; +import org.eclipse.uml2.uml.Model; import org.eclipse.uml2.uml.Package; import org.eclipse.uml2.uml.PackageImport; import org.eclipse.uml2.uml.Stereotype; @@ -302,28 +303,58 @@ public class ElementUtil { } /** - * Retrieve an list of all instances in the model that are instances of - * the java.lang.Class metaType or with a stereotype applied - * - * @param <T> + * Retrieve an list of all instances in the Package that are instances of + * the java.lang.Class metaType OR with a stereotype applied * + * @param topPackage + * * @param metaType - * selected classes - * @param model - * to check + * selected classes * @param appliedStereotype - * may be null, metatype is ignored if not null + * may be null, metatype is ignored if not null * @return a list containing the selected instances */ - //duplicated code from /org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/util/Util.java - //+add template to this method - @SuppressWarnings("unchecked") + public static final <T extends EObject> List<T> getInstancesFilteredByType(final Package topPackage, final java.lang.Class<T> metaType, final Stereotype appliedStereotype) { // retrieve parent element // Package topPackage = Util.topPackage(element); // Assert.isNotNull(topPackage, // "Top package should not be null for element " + element); - Iterator<EObject> iter = topPackage.eAllContents(); + return getInstancesFilteredByType(topPackage.eAllContents(), metaType, appliedStereotype ); + } + + /** + * Retrieve an list of all instances in the Model that are instances of + * the java.lang.Class metaType OR with a stereotype applied + * + * @param topPackage + * + * @param metaType + * selected classes + * @param appliedStereotype + * may be null, metatype is ignored if not null + * @return a list containing the selected instances + */ + public static final <T extends EObject> List<T> getInstancesFilteredByType(final Model model, final java.lang.Class<T> metaType, final Stereotype appliedStereotype) { + return getInstancesFilteredByType(model.eAllContents(), metaType, appliedStereotype ); + } + + /** + * Retrieve an list of all instances that are instances of + * the java.lang.Class metaType OR with a stereotype applied + * + * @param iter + * iterator on all the instances + * @param metaType + * selected classes + * @param appliedStereotype + * may be null, metatype is ignored if not null + * @return a list containing the selected instances + */ + //duplicated code from /org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/util/Util.java + //+add template to this method + @SuppressWarnings("unchecked") + private static <T extends EObject> List<T> getInstancesFilteredByType(Iterator<EObject> iter, final java.lang.Class<T> metaType, final Stereotype appliedStereotype ) { List<T> filteredElements = new ArrayList<T>(); while(iter.hasNext()) { @@ -406,6 +437,6 @@ public class ElementUtil { } return filteredElements; - } + } } diff --git a/tests/junit/plugins/sysml/diagram/org.eclipse.papyrus.sysml.diagram.internalblock.tests/src/org/eclipse/papyrus/sysml/diagram/internalblock/tests/utils/TestUtils.java b/tests/junit/plugins/sysml/diagram/org.eclipse.papyrus.sysml.diagram.internalblock.tests/src/org/eclipse/papyrus/sysml/diagram/internalblock/tests/utils/TestUtils.java index e8f8220e9dd..b306843dd3d 100644 --- a/tests/junit/plugins/sysml/diagram/org.eclipse.papyrus.sysml.diagram.internalblock.tests/src/org/eclipse/papyrus/sysml/diagram/internalblock/tests/utils/TestUtils.java +++ b/tests/junit/plugins/sysml/diagram/org.eclipse.papyrus.sysml.diagram.internalblock.tests/src/org/eclipse/papyrus/sysml/diagram/internalblock/tests/utils/TestUtils.java @@ -1,748 +1,748 @@ -/*****************************************************************************
- * Copyright (c) 2012 CEA LIST.
- *
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- *
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils;
-
-import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getDiagramEditor;
-import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getDiagramView;
-import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getEditPart;
-import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getPaletteTool;
-import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getTransactionalEditingDomain;
-import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.TestPrepareUtils.createElement;
-import static org.junit.Assert.fail;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.commands.ParameterizedCommand;
-import org.eclipse.core.commands.operations.IOperationHistory;
-import org.eclipse.core.commands.operations.IOperationHistoryListener;
-import org.eclipse.core.commands.operations.OperationHistoryEvent;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.ConnectionEditPart;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.RequestConstants;
-import org.eclipse.gef.Tool;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.commands.CompoundCommand;
-import org.eclipse.gef.requests.GroupRequest;
-import org.eclipse.gef.requests.ReconnectRequest;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.common.ui.action.global.GlobalAction;
-import org.eclipse.gmf.runtime.common.ui.action.internal.actions.global.GlobalCopyAction;
-import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.commands.PopupMenuCommand;
-import org.eclipse.gmf.runtime.diagram.ui.menus.PopupMenu;
-import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
-import org.eclipse.gmf.runtime.diagram.ui.requests.CreateConnectionViewAndElementRequest;
-import org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.requests.EditCommandRequestWrapper;
-import org.eclipse.gmf.runtime.emf.type.core.IElementType;
-import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientRelationshipRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.gmf.runtime.notation.Connector;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.commands.ActionHandler;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper;
-import org.eclipse.papyrus.infra.gmfdiag.common.commands.SelectAndExecuteCommand;
-import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
-import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
-import org.eclipse.papyrus.sysml.blocks.Block;
-import org.eclipse.papyrus.sysml.blocks.BlocksPackage;
-import org.eclipse.papyrus.sysml.blocks.NestedConnectorEnd;
-import org.eclipse.papyrus.sysml.diagram.internalblock.Activator;
-import org.eclipse.papyrus.uml.diagram.common.service.AspectUnspecifiedTypeConnectionTool;
-import org.eclipse.papyrus.uml.diagram.common.service.AspectUnspecifiedTypeConnectionTool.CreateAspectUnspecifiedTypeConnectionRequest;
-import org.eclipse.papyrus.uml.diagram.common.service.AspectUnspecifiedTypeCreationTool;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbenchCommandConstants;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.uml2.uml.ConnectableElement;
-import org.eclipse.uml2.uml.ConnectorEnd;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Property;
-import org.eclipse.uml2.uml.util.UMLUtil;
-import org.junit.Assert;
-
-public class TestUtils {
-
- public static void deleteView(IElementType elementType, View containerView, boolean isAllowed) throws Exception {
- View view = TestPrepareUtils.dropFromModelExplorer(elementType, getDiagramView());
- deleteView(view, isAllowed);
- }
-
- public static void deleteView(View view, boolean isAllowed) throws Exception {
- // Find container EditPart (for command creation)
- EditPart containerEditPart = getEditPart(view);
- // Get delete view command
- Command command = containerEditPart.getCommand(new GroupRequest(RequestConstants.REQ_DELETE));
- // if the view deletion is not allowed the command should not be executable
- if(!isAllowed) {
- if((command == null) || (!command.canExecute())) {
- // Ok the command cannot be executed.
- } else {
- fail("The command should not be executable.");
- }
- } else {
- if((command == null) || (!command.canExecute())) {
- fail("The command should be executable.");
- } else {
- // Ok the command can be executed.
- defaultExecutionTest(command);
- // Test the results then
- // fail("Result tests not implemented.");
- }
- }
- }
-
- public static void deleteElement(IElementType elementType, View containerView, boolean isAllowed) throws Exception {
- View view = TestPrepareUtils.dropFromModelExplorer(elementType, getDiagramView());
- deleteElement(view, isAllowed);
- }
-
- public static void deleteElement(View view, boolean isAllowed) throws Exception {
- // Find container EditPart (for command creation)
- EditPart containerEditPart = getEditPart(view);
- // Prepare request
- DestroyElementRequest destroyRequest = new DestroyElementRequest(getTransactionalEditingDomain(), false);
- // Get delete command
- Command command = containerEditPart.getCommand(new EditCommandRequestWrapper(destroyRequest));
- // if the deletion is not allowed the command should not be executable
- if(!isAllowed) {
- if((command == null) || (!command.canExecute())) {
- // Ok the command cannot be executed.
- } else {
- fail("The command should not be executable.");
- }
- } else {
- if((command == null) || (!command.canExecute())) {
- fail("The command should be executable.");
- } else {
- // Ok the command can be executed.
- defaultExecutionTest(command);
- // Test the results then
- // fail("Result tests not implemented.");
- }
- }
- }
-
- public static void dropFromModelExplorer(IElementType elementType, View containerView, boolean isAllowed) throws Exception {
- EObject newObject = createElement(elementType, containerView);
- dropFromModelExplorer(newObject, containerView, isAllowed);
- }
-
- public static void dropFromModelExplorer(EObject eObject, View containerView, boolean isAllowed) throws Exception {
- // Find container EditPart (for command creation)
- EditPart containerEditPart = getEditPart(containerView);
- // Prepare drop request
- DropObjectsRequest dropRequest = new DropObjectsRequest();
- ArrayList<EObject> list = new ArrayList<EObject>();
- list.add(eObject);
- dropRequest.setObjects(list);
- dropRequest.setLocation(new Point(200, 200));
- // Get drop command
- Command command = containerEditPart.getCommand(dropRequest);
- // if the drop is not allowed the command should not be executable
- if(!isAllowed) {
- if((command == null) || (!command.canExecute())) {
- // Ok the command cannot be executed.
- } else {
- fail("The command should not be executable.");
- }
- } else {
- if((command == null) || (!command.canExecute())) {
- fail("The command should be executable.");
- } else {
- // Ok the command can be executed.
- defaultExecutionTest(command);
- // Test the results then
- // fail("Result tests not implemented.");
- }
- }
- }
-
- public static void altDropFromModelExplorer(EObject eObject, View containerView, List<String> expectedCommandNames, boolean isAllowed) throws Exception {
- // Find container EditPart (for command creation)
- EditPart containerEditPart = getEditPart(containerView);
- // Prepare drop request
- DropObjectsRequest dropRequest = new DropObjectsRequest();
- ArrayList<EObject> list = new ArrayList<EObject>();
- list.add(eObject);
- dropRequest.setObjects(list);
- dropRequest.setLocation(new Point(200, 200));
- // Get drop command
- Command command = containerEditPart.getCommand(dropRequest);
- // if the drop is not allowed the command should not be executable
- if(!isAllowed) {
- if((command == null) || (!command.canExecute())) {
- // Ok the command cannot be executed.
- } else {
- fail("The command should not be executable.");
- }
- } else {
- if((command == null) || (!command.canExecute())) {
- fail("The command should be executable.");
- } else {
- // Simple command
- if(expectedCommandNames.size() == 1) {
- if(expectedCommandNames.get(0).equals(command.getLabel())) {
- // Ok the command can be executed.
- defaultExecutionTest(command);
- // Test the results then
- // fail("Result tests not implemented.");
- EditorUtils.getCommandStack().undo();
- } else {
- fail("The expected kind of command was {" + expectedCommandNames.get(0) + "}, but was {" + command.getLabel() + "}");
- }
- } else if(expectedCommandNames.size() > 1) {
- ICommand tmpCommand = (command instanceof ICommandProxy) ? ((ICommandProxy)command).getICommand() : null;
- if((tmpCommand == null) || !(tmpCommand instanceof SelectAndExecuteCommand)) {
- fail("The drop command is not a selact and execute command.");
- }
- // Field accessibility modification to review elementary drop command available as
- // SelectAndExecuteCommand choices.
- SelectAndExecuteCommand selectCommand = (SelectAndExecuteCommand)tmpCommand;
- Field popupField = PopupMenuCommand.class.getDeclaredField("popupMenu");
- popupField.setAccessible(true);
- PopupMenu menu = (PopupMenu)popupField.get(selectCommand);
- Field content = PopupMenu.class.getDeclaredField("content");
- content.setAccessible(true);
- List<CompoundCommand> commandList = (List<CompoundCommand>)content.get(menu);
- if(commandList.size() != expectedCommandNames.size()) {
- fail("Unexpected number of possible alternate drop command.");
- }
- for(int i = 0; i < commandList.size(); i++) {
- CompoundCommand subCommand = commandList.get(i);
- if(expectedCommandNames.get(i).equals(subCommand.getLabel())) {
- // Ok the command can be executed.
- defaultExecutionTest(subCommand);
- // Add one more undo to go back in initial state before testing next command
- EditorUtils.getCommandStack().undo();;
- // Test the results then
- // fail("Result tests not implemented.");
- } else {
- fail("The expected kind of command was {" + expectedCommandNames.get(i) + "}.");
- }
- }
- }
- }
- }
- }
-
- public static void createNodeFromPalette(String toolId, View containerView, boolean isAllowed) throws Exception {
- if(isAllowed) {
- createNodeFromPalette(toolId, containerView, isAllowed, true);
- } else {
- createNodeFromPalette(toolId, containerView, isAllowed, false);
- }
- }
-
- public static void createNodeFromPalette(String toolId, View containerView, boolean isAllowed, boolean execute) throws Exception {
- // Find container EditPart (for command creation)
- EditPart containerEditPart = getEditPart(containerView);
- // Find palette tool to simulate element creation
- Tool tool = getPaletteTool(toolId);
- Request createRequest = getCreateRequest(tool);
- // Get creation command for request
- Command command = containerEditPart.getCommand(createRequest);
- // if the creation is not allowed the command should not be executable
- if(!isAllowed) {
- if((command == null) || (!command.canExecute())) {
- // Ok the command cannot be executed.
- } else {
- fail("The command should not be executable.");
- }
- } else {
- if((command == null) || (!command.canExecute())) {
- fail("The command should be executable.");
- } else {
- // Ok the command can be executed.
- if(execute) {
- defaultExecutionTest(command);
- }
- // Test the results then
- // fail("Result tests not implemented.");
- }
- }
- }
-
- public static Request getCreateRequest(final Tool tool) throws Exception {
-
- // Don't forget to set the diagram viewer (required for preferenceHints to mimic manual creation)
- final IDiagramGraphicalViewer viewer = getDiagramEditor().getDiagramGraphicalViewer();
-
- Display.getDefault().syncExec(new Runnable() {
-
- public void run() {
- try {
- tool.setViewer(viewer);
- } catch (Exception ex) {
- ex.printStackTrace(System.out);
- }
- }
- });
-
- if(tool instanceof AspectUnspecifiedTypeCreationTool) {
- AspectUnspecifiedTypeCreationTool creationTool = (AspectUnspecifiedTypeCreationTool)tool;
- return creationTool.createCreateRequest();
- } else if(tool instanceof AspectUnspecifiedTypeConnectionTool) {
- AspectUnspecifiedTypeConnectionTool connectionTool = (AspectUnspecifiedTypeConnectionTool)tool;
- return connectionTool.new CreateAspectUnspecifiedTypeConnectionRequest(connectionTool.getElementTypes(), false, Activator.DIAGRAM_PREFERENCES_HINT);
- }
-
- throw new Exception("Unexpected kind of creation tool.");
- }
-
- public static void createEdgeFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed) throws Exception {
- // Execute command only when the command is expected to be executable
- createEdgeFromPalette(toolId, sourceView, targetView, isAllowed, isAllowed);
- }
-
- public static EObject createEdgeFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, boolean execute) throws Exception {
- // Find palette tool to simulate element creation and prepare request
- Tool tool = getPaletteTool(toolId);
- CreateAspectUnspecifiedTypeConnectionRequest createRequest = (CreateAspectUnspecifiedTypeConnectionRequest)getCreateRequest(tool);
- // Test source creation command
- createRequest.setSourceEditPart(getEditPart(sourceView));
- createRequest.setType(RequestConstants.REQ_CONNECTION_START);
- Command srcCommand = getEditPart(sourceView).getCommand(createRequest);
- // Test source command
- if((srcCommand == null) || !(srcCommand.canExecute())) { // Non-executable command
- if(targetView == null) { // Only test behavior on source
- if(!isAllowed) {
- // Current behavior matches the expected results
- return null;
- } else {
- fail("The command should be executable.");
- }
- } else { // Test complete creation, the command should necessary be executable
- fail("The command should be executable.");
- }
- } else { // Executable command
- if(targetView == null) { // Only test behavior on source
- if(!isAllowed) {
- fail("The command should not be executable.");
- } else {
- // Current behavior matches the expected results - no execution test.
- return null;
- }
- } else { // The command is executable and a target is provided - continue the test
- // Get target command (complete link creation)
- createRequest.setSourceEditPart(getEditPart(sourceView));
- createRequest.setTargetEditPart(getEditPart(targetView));
- createRequest.setType(RequestConstants.REQ_CONNECTION_END);
- Command tgtCommand = getEditPart(targetView).getCommand(createRequest);
- // Test the target command
- if((tgtCommand == null) || !(tgtCommand.canExecute())) { // Non-executable command
- if(!isAllowed) {
- // Current behavior matches the expected results
- return null;
- } else {
- fail("The command should be executable.");
- }
- } else { // Executable command
- if(!isAllowed) {
- fail("The command should not be executable.");
- } else {
- // Current behavior matches the expected results
- if(execute) { // Test command execution
- defaultExecutionTest(tgtCommand);
- // Retrieve created object via nested ElementAndViewCreationRequest.
- View newView = null;
- Iterator<?> it = createRequest.getAllRequests().iterator();
- while(it.hasNext() && newView == null) {
- CreateConnectionViewAndElementRequest subRequest = (CreateConnectionViewAndElementRequest)it.next();
- newView = (View)subRequest.getConnectionViewDescriptor().getAdapter(View.class);
- }
- if(newView != null) {
- return newView.getElement();
- } else {
- fail("No edge seem to have been created.");
- }
- }
- // Test the results then
- // fail("Result tests not implemented.");
- }
- }
- }
- }
- return null;
- }
-
- public static void createEdgeConnectorFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, List<Property> nestedSourcePath, List<Property> nestedTargetPath) throws Exception {
- createEdgeConnectorFromPalette(toolId, sourceView, targetView, isAllowed, isAllowed, nestedSourcePath, nestedTargetPath);
- }
-
- public static void createEdgeConnectorFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, boolean execute, List<Property> nestedSourcePath, List<Property> nestedTargetPath) throws Exception {
- EObject newLink = createEdgeFromPalette(toolId, sourceView, targetView, isAllowed, execute);
- // Abort if the command is not supposed to be executable
- if(!isAllowed) {
- return;
- }
- if((newLink == null) || (!(newLink instanceof org.eclipse.uml2.uml.Connector))) {
- fail("No edge or unexpected kind of edge created.");
- }
- // If previous test have not failed the execution / undo / re-do has been done
- org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)newLink;
- // Test source connector end
- NestedConnectorEnd sourceNestedConnectorEnd = UMLUtil.getStereotypeApplication(connector.getEnds().get(0), NestedConnectorEnd.class);
- if(nestedSourcePath.isEmpty()) {
- Assert.assertNull("No nested connector end stereotype should be applied on source.", sourceNestedConnectorEnd);
- } else {
- Assert.assertNotNull("Nested connector end stereotype should be applied on source.", sourceNestedConnectorEnd);
- Assert.assertEquals("Nested property path is incorrect for source", nestedSourcePath, sourceNestedConnectorEnd.getPropertyPath());
- // if(!sourceNestedConnectorEnd.getPropertyPath().equals(nestedSourcePath)) {
- // fail("The nested property path is incorrect for source.");
- // }
- }
- // Test target connector end
- NestedConnectorEnd targetNestedConnectorEnd = UMLUtil.getStereotypeApplication(connector.getEnds().get(1), NestedConnectorEnd.class);
- if(nestedTargetPath.isEmpty()) {
- Assert.assertNull("No nested connector end stereotype should be applied on target.", targetNestedConnectorEnd);
- } else {
- Assert.assertNotNull("Nested connector end stereotype should be applied on target.", targetNestedConnectorEnd);
- Assert.assertEquals("Nested property path is incorrect for target", nestedTargetPath, targetNestedConnectorEnd.getPropertyPath());
- // if(!targetNestedConnectorEnd.getPropertyPath().equals(nestedTargetPath)) {
- // fail("The nested property path is incorrect for target.");
- // }
- }
- }
-
- public static void createEdgeConnectorAndTestDelegateFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception {
- createEdgeConnectorAndTestDelegateFromPalette(toolId, sourceView, targetView, isAllowed, isAllowed, expectedSourcePartWithPort, expectedTargetPartWithPort);
- }
-
- public static void createEdgeConnectorAndTestDelegateFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, boolean execute, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception {
- EObject newLink = createEdgeFromPalette(toolId, sourceView, targetView, isAllowed, execute);
- // Abort if the command is not supposed to be executable
- if(!isAllowed) {
- return;
- }
- if((newLink == null) || (!(newLink instanceof org.eclipse.uml2.uml.Connector))) {
- fail("No edge or unexpected kind of edge created.");
- }
- // If previous test have not failed the execution / undo / re-do has been done
- org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)newLink;
- // Test source connector end
- ConnectorEnd sourceConnectorEnd = connector.getEnds().get(0);
- if(sourceConnectorEnd.getPartWithPort() != expectedSourcePartWithPort) {
- fail("The partWithPort is incorrect for source.");
- }
- // Test target connector end
- ConnectorEnd targetConnectorEnd = connector.getEnds().get(1);
- if(targetConnectorEnd.getPartWithPort() != expectedTargetPartWithPort) {
- fail("The partWithPort is incorrect for target.");
- }
- }
-
- public static void reorientRelationshipSource(View relationshipView, View newSourceView, boolean isAllowed) throws Exception {
- reorientRelationship((Connector)relationshipView, newSourceView, ReorientRelationshipRequest.REORIENT_SOURCE, isAllowed);
- }
-
- public static void reorientRelationshipTarget(View relationshipView, View newTargetView, boolean isAllowed) throws Exception {
- reorientRelationship((Connector)relationshipView, newTargetView, ReorientRelationshipRequest.REORIENT_TARGET, isAllowed);
- }
-
- public static void reorientRelationship(Connector relationshipView, View newEndView, int reorientDirection, boolean isAllowed) throws Exception {
- // Prepare request and add
- String reconnectDirection = (ReorientRelationshipRequest.REORIENT_SOURCE == reorientDirection) ? RequestConstants.REQ_RECONNECT_SOURCE : RequestConstants.REQ_RECONNECT_TARGET;
- ReconnectRequest reconnectRequest = new ReconnectRequest(relationshipView);
- reconnectRequest.setTargetEditPart(getEditPart(newEndView));
- reconnectRequest.setConnectionEditPart((ConnectionEditPart)getEditPart(relationshipView));
- reconnectRequest.setType(reconnectDirection);
- // Get command
- Command reorientCommand = getEditPart(newEndView).getCommand(reconnectRequest);
- // Test the target command
- if((reorientCommand == null) || !(reorientCommand.canExecute())) { // Non-executable command
- if(!isAllowed) {
- // Current behavior matches the expected results
- return;
- } else {
- fail("The command should be executable.");
- }
- } else { // Executable command
- if(!isAllowed) {
- fail("The command should not be executable.");
- } else {
- defaultExecutionTest(reorientCommand);
- // Test the results then
- // fail("Result tests not implemented.");
- }
- }
- }
-
- public static void reorientConnectorSource(View relationshipView, View newSourceView, boolean isAllowed) throws Exception {
- List<Property> nestedPath = Collections.emptyList();
- reorientConnectorSource(relationshipView, newSourceView, isAllowed, nestedPath);
- }
-
- public static void reorientConnectorTarget(View relationshipView, View newTargetView, boolean isAllowed) throws Exception {
- List<Property> nestedPath = Collections.emptyList();
- reorientConnectorTarget(relationshipView, newTargetView, isAllowed, nestedPath);
- }
-
- public static void reorientConnectorSource(View relationshipView, View newSourceView, boolean isAllowed, List<Property> nestedPath) throws Exception {
- reorientConnector((Connector)relationshipView, newSourceView, ReorientRelationshipRequest.REORIENT_SOURCE, isAllowed, nestedPath);
- }
-
- public static void reorientConnectorTarget(View relationshipView, View newTargetView, boolean isAllowed, List<Property> nestedPath) throws Exception {
- reorientConnector((Connector)relationshipView, newTargetView, ReorientRelationshipRequest.REORIENT_TARGET, isAllowed, nestedPath);
- }
-
- public static void reorientConnector(Connector relationshipView, View newEndView, int reorientDirection, boolean isAllowed, List<Property> nestedPath) throws Exception {
- reorientRelationship(relationshipView, newEndView, reorientDirection, isAllowed);
- // Abort if the command is not supposed to be executable
- if(!isAllowed) {
- return;
- }
- // If previous test have not failed the execution / undo / re-do has been done
- org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)relationshipView.getElement();
- ConnectorEnd modifiedConnectorEnd = (reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) ? connector.getEnds().get(0) : connector.getEnds().get(1);
- NestedConnectorEnd nestedConnectorEnd = UMLUtil.getStereotypeApplication(modifiedConnectorEnd, NestedConnectorEnd.class);
- if(nestedPath.isEmpty()) {
- Assert.assertNull("No nested connector end stereotype should be applied.", nestedConnectorEnd);
- } else {
- Assert.assertNotNull("Nested connector end stereotype should be applied.", nestedConnectorEnd);
- Assert.assertEquals("Invalid nested path", nestedPath, nestedConnectorEnd.getPropertyPath());
- }
- }
-
- public static void reorientConnectorSourceAndTestDelegate(View relationshipView, View newSourceView, boolean isAllowed, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception {
- reorientConnectorAndTestDelegate((Connector)relationshipView, newSourceView, ReorientRelationshipRequest.REORIENT_SOURCE, isAllowed, expectedSourcePartWithPort, expectedTargetPartWithPort);
- }
-
- public static void reorientConnectorTargetAndTestDelegate(View relationshipView, View newTargetView, boolean isAllowed, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception {
- reorientConnectorAndTestDelegate((Connector)relationshipView, newTargetView, ReorientRelationshipRequest.REORIENT_TARGET, isAllowed, expectedSourcePartWithPort, expectedTargetPartWithPort);
- }
-
- public static void reorientConnectorAndTestDelegate(Connector relationshipView, View newEndView, int reorientDirection, boolean isAllowed, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception {
- reorientRelationship(relationshipView, newEndView, reorientDirection, isAllowed);
- // Abort if the command is not supposed to be executable
- if(!isAllowed) {
- return;
- }
- // If previous test have not failed the execution / undo / re-do has been done
- org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)relationshipView.getElement();
- ConnectorEnd modifiedConnectorEnd = (reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) ? connector.getEnds().get(0) : connector.getEnds().get(1);
- ConnectorEnd oppositeConnectorEnd = (reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) ? connector.getEnds().get(1) : connector.getEnds().get(0);
- if(reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) { // re-orient source
- // Test source connector end
- Assert.assertEquals("The partWithPort is incorrect for source (re-oriented).", expectedSourcePartWithPort, modifiedConnectorEnd.getPartWithPort());
- // if(modifiedConnectorEnd.getPartWithPort() != expectedSourcePartWithPort) {
- // fail("The partWithPort is incorrect for source (re-oriented).");
- // }
- // Test target connector end
- Assert.assertEquals("The partWithPort is incorrect for target (opposite end).", expectedTargetPartWithPort, oppositeConnectorEnd.getPartWithPort());
- // if(oppositeConnectorEnd.getPartWithPort() != expectedTargetPartWithPort) {
- // fail("The partWithPort is incorrect for target (opposite end).");
- // }
- } else { // re-orient target
- // Test source connector end
- Assert.assertEquals("The partWithPort is incorrect for target (re-oriented).", expectedTargetPartWithPort, modifiedConnectorEnd.getPartWithPort());
- // if(modifiedConnectorEnd.getPartWithPort() != expectedTargetPartWithPort) {
- // fail("The partWithPort is incorrect for target .");
- // }
- // Test target connector end
- Assert.assertEquals("The partWithPort is incorrect for source (opposite end).", expectedSourcePartWithPort, oppositeConnectorEnd.getPartWithPort());
- // if(oppositeConnectorEnd.getPartWithPort() != expectedSourcePartWithPort) {
- // fail("The partWithPort is incorrect for source (opposite end).");
- // }
- }
- }
-
- public static void setEncapsulationDeleteConnectorTest(Element block, View sourceView, View targetView, boolean canCreateConnector, boolean isConnectorDestroyExpected) throws Exception {
- if(!canCreateConnector) {
- return; // abort
- }
- // Make sure the block is not encapsulated before Connector creation.
- TestPrepareUtils.setBlockIsEncapsulated(block, false);
- // Create connector
- org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)createEdgeFromPalette("internalblock.tool.connector", sourceView, targetView, true, true);
- // Prepare set encapsulated command and execute (with undo, re-do).
- Block blockApp = UMLUtil.getStereotypeApplication(block, Block.class);
- IElementEditService provider = ElementEditServiceUtils.getCommandProvider(blockApp);
- if(provider == null) {
- fail("Could not get IElementEditService for Block stereotype application.");
- }
- IEditCommandRequest setEncapsulationRequest = new SetRequest(getTransactionalEditingDomain(), blockApp, BlocksPackage.eINSTANCE.getBlock_IsEncapsulated(), true);
- ICommand setEncapsulationCommand = provider.getEditCommand(setEncapsulationRequest);
- defaultExecutionTest(new ICommandProxy(setEncapsulationCommand));
- // Test if the Connector have been destroyed
- if(isConnectorDestroyExpected) {
- if(connector.eResource() != null) { // connector destroyed has no container
- fail("Connector was expected to be destroyed.");
- }
- } else {
- if(connector.eResource() == null) { // connector destroyed has no container
- fail("Connector was not expected to be destroyed.");
- }
- }
- }
-
- /**
- * Copy the list of objects into the Clipboard
- *
- * @param objectsToCopy
- * the list of objects to copy. should not be <code>null</code>, at least an empty list
- * @throws Exception
- * exception thrown in case of problems
- */
- public static void copyEditParts(List<Object> objectsToCopy) throws Exception {
- // select elements to copy
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(EditorUtils.getEditor());
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().bringToTop(EditorUtils.getEditor());
- EditorUtils.getDiagramEditor().getEditorSite().getSelectionProvider().setSelection(new StructuredSelection(objectsToCopy));
- ISelection selection = EditorUtils.getEditor().getSite().getSelectionProvider().getSelection();
- Assert.assertEquals("Selection size should be " + objectsToCopy.size(), objectsToCopy.size(), ((IStructuredSelection)selection).size());
- // retrieve the command for copy
- ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class);
- commandService.refreshElements(IWorkbenchCommandConstants.EDIT_COPY, null);
- org.eclipse.core.commands.Command copyCommand = commandService.getCommand(IWorkbenchCommandConstants.EDIT_COPY);
- ((GlobalCopyAction)((ActionHandler)copyCommand.getHandler()).getAction()).setEnabled(true);
- Assert.assertNotNull("Impossible to find copy command", copyCommand);
- //EditorUtils.getDiagramEditor().getEditingDomain().setClipboard(objectsToCopy);
- // retrieve handler service for the copy command
- IHandlerService handlerService = (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class);
- Assert.assertNotNull("Impossible to find handler service", handlerService);
- final ParameterizedCommand parameterizedCommand = new ParameterizedCommand(copyCommand, null);
- // retrieve the command and set some parameters on it
- copyCommand.setEnabled(handlerService.getCurrentState());
- final boolean commandEnabled = copyCommand.isEnabled();
- Assert.assertTrue("Command should be enabled", commandEnabled);
- // execute the copy command
- handlerService.executeCommand(parameterizedCommand, null);
- }
-
- /**
- * paste the list of objects into the Clipboard into the current diagram
- *
- * @param target
- * object on which content of the clipboard should be added
- * @param executable
- * indicates if the paste command should be executable.
- *
- * @throws Exception
- * exception thrown in case of problems
- */
- public static void pasteEditParts(Object target, boolean executable) throws Exception {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(EditorUtils.getEditor());
- EditorUtils.getDiagramEditor().getEditorSite().getSelectionProvider().setSelection(new StructuredSelection(target));
- // retrieve the command for copy
- ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class);
- commandService.refreshElements(IWorkbenchCommandConstants.EDIT_PASTE, null);
- org.eclipse.core.commands.Command pasteCommand = commandService.getCommand(IWorkbenchCommandConstants.EDIT_PASTE);
- Assert.assertNotNull("Impossible to find paste command", pasteCommand);
- ((GlobalAction)((ActionHandler)pasteCommand.getHandler()).getAction()).refresh();
- IHandlerService handlerService = (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class);
- Assert.assertNotNull("Impossible to find handler service", handlerService);
- final ParameterizedCommand parameterizedCommand = new ParameterizedCommand(pasteCommand, null);
- Assert.assertEquals("Command is not executable as expected", pasteCommand.isEnabled(), executable);
- if(executable) {
- // execute the copy command
- handlerService.executeCommand(parameterizedCommand, null);
- }
- }
-
- /**
- * paste with model element the list of objects into the Clipboard into the current diagram
- *
- * @param target
- * object on which content of the clipboard should be added
- * @param executable
- * indicates if the paste command should be executable.
- *
- * @throws Exception
- * exception thrown in case of problems
- */
- public static void pasteWithModelEditParts(Object target, boolean executable) throws Exception {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(EditorUtils.getEditor());
- EditorUtils.getDiagramEditor().getEditorSite().getSelectionProvider().setSelection(new StructuredSelection(target));
- // retrieve the command for copy
- ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class);
- commandService.refreshElements(IWorkbenchCommandConstants.EDIT_PASTE, null);
- org.eclipse.core.commands.Command pasteWithModelCommand = commandService.getCommand("org.eclipse.papyrus.uml.diagram.common.commands.PasteWithModelCommand");
- Assert.assertNotNull("Impossible to find paste command", pasteWithModelCommand);
- // ((GlobalAction)((AbstractHandlerWithState)pasteWithModelCommand.getHandler()).getAction()).refresh();
- IHandlerService handlerService = (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class);
- Assert.assertNotNull("Impossible to find handler service", handlerService);
- final ParameterizedCommand parameterizedCommand = new ParameterizedCommand(pasteWithModelCommand, null);
- Assert.assertEquals("Command is not executable as expected", pasteWithModelCommand.isEnabled(), executable);
- if(executable) {
- // execute the copy command
- handlerService.executeCommand(parameterizedCommand, null);
- }
- }
-
- // History event type variable to store history error events.
- public static int historyEventType = OperationHistoryEvent.DONE;
-
- /**
- * Test execution, undo, redo of the given command.
- *
- * @param command
- * the command to test.
- * @throws Exception
- */
- public static void defaultExecutionTest(Command command) throws Exception {
- // Execution in the diagram command stack (like Papyrus usual execution for GEF commands). This is important especially for
- // composed command like Drop links which create intermediate view during execution. With EMF command stack, the whole command
- // tries to execute and the edit part of the intermediate created views are not created before the command ends.
- // The diagram command stack let edit part being created after each view creation.
- // The problem in using the DiagramCommandStack (vs EMF CommandStack) is that it hides any exception that can possibly occur during
- // command execution. This would let the test finish without error (the command result is not tested currently) while the execution failed.
- // For this matter the DiagramCommandStack history is observed to detect execution issues.
- // Add diagram command stack operation history listener
- IOperationHistory history = EditorUtils.getDiagramEditingDomain().getActionManager().getOperationHistory();
- IOperationHistoryListener historyChange = new IOperationHistoryListener() {
-
- public void historyNotification(OperationHistoryEvent event) {
- // Store history events
- historyEventType = event.getEventType();
- }
- };
- history.addOperationHistoryListener(historyChange);
- // Test execution
- historyEventType = OperationHistoryEvent.DONE;
- EditorUtils.getCommandStack().execute(new GEFtoEMFCommandWrapper(command));
- if(historyEventType == OperationHistoryEvent.OPERATION_NOT_OK) {
- fail("Command execution failed ()");
- }
- // Test undo
- historyEventType = OperationHistoryEvent.DONE;
- EditorUtils.getCommandStack().undo();
- if(historyEventType == OperationHistoryEvent.OPERATION_NOT_OK) {
- fail("Command undo failed ()");
- }
- // Test redo
- historyEventType = OperationHistoryEvent.DONE;
- EditorUtils.getCommandStack().redo();
- if(historyEventType == OperationHistoryEvent.OPERATION_NOT_OK) {
- fail("Command redo failed ()");
- }
- // Remove listener.
- history.removeOperationHistoryListener(historyChange);
- }
-}
+/***************************************************************************** + * Copyright (c) 2012 CEA LIST. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils; + +import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getDiagramEditor; +import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getDiagramView; +import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getEditPart; +import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getPaletteTool; +import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.EditorUtils.getTransactionalEditingDomain; +import static org.eclipse.papyrus.sysml.diagram.internalblock.tests.utils.TestPrepareUtils.createElement; +import static org.junit.Assert.fail; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.commands.ParameterizedCommand; +import org.eclipse.core.commands.operations.IOperationHistory; +import org.eclipse.core.commands.operations.IOperationHistoryListener; +import org.eclipse.core.commands.operations.OperationHistoryEvent; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.ConnectionEditPart; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.Request; +import org.eclipse.gef.RequestConstants; +import org.eclipse.gef.Tool; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.commands.CompoundCommand; +import org.eclipse.gef.requests.GroupRequest; +import org.eclipse.gef.requests.ReconnectRequest; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.common.ui.action.global.GlobalAction; +import org.eclipse.gmf.runtime.common.ui.action.internal.actions.global.GlobalCopyAction; +import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.commands.PopupMenuCommand; +import org.eclipse.gmf.runtime.diagram.ui.menus.PopupMenu; +import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer; +import org.eclipse.gmf.runtime.diagram.ui.requests.CreateConnectionViewAndElementRequest; +import org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest; +import org.eclipse.gmf.runtime.diagram.ui.requests.EditCommandRequestWrapper; +import org.eclipse.gmf.runtime.emf.type.core.IElementType; +import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientRelationshipRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.gmf.runtime.notation.Connector; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.commands.ActionHandler; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper; +import org.eclipse.papyrus.infra.gmfdiag.common.commands.SelectAndExecuteCommand; +import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils; +import org.eclipse.papyrus.infra.services.edit.service.IElementEditService; +import org.eclipse.papyrus.sysml.blocks.Block; +import org.eclipse.papyrus.sysml.blocks.BlocksPackage; +import org.eclipse.papyrus.sysml.blocks.NestedConnectorEnd; +import org.eclipse.papyrus.sysml.diagram.internalblock.Activator; +import org.eclipse.papyrus.uml.diagram.common.service.AspectUnspecifiedTypeConnectionTool; +import org.eclipse.papyrus.uml.diagram.common.service.AspectUnspecifiedTypeConnectionTool.CreateAspectUnspecifiedTypeConnectionRequest; +import org.eclipse.papyrus.uml.diagram.common.service.AspectUnspecifiedTypeCreationTool; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IWorkbenchCommandConstants; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.commands.ICommandService; +import org.eclipse.ui.handlers.IHandlerService; +import org.eclipse.uml2.uml.ConnectableElement; +import org.eclipse.uml2.uml.ConnectorEnd; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Property; +import org.eclipse.uml2.uml.util.UMLUtil; +import org.junit.Assert; + +public class TestUtils { + + public static void deleteView(IElementType elementType, View containerView, boolean isAllowed) throws Exception { + View view = TestPrepareUtils.dropFromModelExplorer(elementType, getDiagramView()); + deleteView(view, isAllowed); + } + + public static void deleteView(View view, boolean isAllowed) throws Exception { + // Find container EditPart (for command creation) + EditPart containerEditPart = getEditPart(view); + // Get delete view command + Command command = containerEditPart.getCommand(new GroupRequest(RequestConstants.REQ_DELETE)); + // if the view deletion is not allowed the command should not be executable + if(!isAllowed) { + if((command == null) || (!command.canExecute())) { + // Ok the command cannot be executed. + } else { + fail("The command should not be executable."); + } + } else { + if((command == null) || (!command.canExecute())) { + fail("The command should be executable."); + } else { + // Ok the command can be executed. + defaultExecutionTest(command); + // Test the results then + // fail("Result tests not implemented."); + } + } + } + + public static void deleteElement(IElementType elementType, View containerView, boolean isAllowed) throws Exception { + View view = TestPrepareUtils.dropFromModelExplorer(elementType, getDiagramView()); + deleteElement(view, isAllowed); + } + + public static void deleteElement(View view, boolean isAllowed) throws Exception { + // Find container EditPart (for command creation) + EditPart containerEditPart = getEditPart(view); + // Prepare request + DestroyElementRequest destroyRequest = new DestroyElementRequest(getTransactionalEditingDomain(), false); + // Get delete command + Command command = containerEditPart.getCommand(new EditCommandRequestWrapper(destroyRequest)); + // if the deletion is not allowed the command should not be executable + if(!isAllowed) { + if((command == null) || (!command.canExecute())) { + // Ok the command cannot be executed. + } else { + fail("The command should not be executable."); + } + } else { + if((command == null) || (!command.canExecute())) { + fail("The command should be executable."); + } else { + // Ok the command can be executed. + defaultExecutionTest(command); + // Test the results then + // fail("Result tests not implemented."); + } + } + } + + public static void dropFromModelExplorer(IElementType elementType, View containerView, boolean isAllowed) throws Exception { + EObject newObject = createElement(elementType, containerView); + dropFromModelExplorer(newObject, containerView, isAllowed); + } + + public static void dropFromModelExplorer(EObject eObject, View containerView, boolean isAllowed) throws Exception { + // Find container EditPart (for command creation) + EditPart containerEditPart = getEditPart(containerView); + // Prepare drop request + DropObjectsRequest dropRequest = new DropObjectsRequest(); + ArrayList<EObject> list = new ArrayList<EObject>(); + list.add(eObject); + dropRequest.setObjects(list); + dropRequest.setLocation(new Point(200, 200)); + // Get drop command + Command command = containerEditPart.getCommand(dropRequest); + // if the drop is not allowed the command should not be executable + if(!isAllowed) { + if((command == null) || (!command.canExecute())) { + // Ok the command cannot be executed. + } else { + fail("The command should not be executable."); + } + } else { + if((command == null) || (!command.canExecute())) { + fail("The command should be executable."); + } else { + // Ok the command can be executed. + defaultExecutionTest(command); + // Test the results then + // fail("Result tests not implemented."); + } + } + } + + public static void altDropFromModelExplorer(EObject eObject, View containerView, List<String> expectedCommandNames, boolean isAllowed) throws Exception { + // Find container EditPart (for command creation) + EditPart containerEditPart = getEditPart(containerView); + // Prepare drop request + DropObjectsRequest dropRequest = new DropObjectsRequest(); + ArrayList<EObject> list = new ArrayList<EObject>(); + list.add(eObject); + dropRequest.setObjects(list); + dropRequest.setLocation(new Point(200, 200)); + // Get drop command + Command command = containerEditPart.getCommand(dropRequest); + // if the drop is not allowed the command should not be executable + if(!isAllowed) { + if((command == null) || (!command.canExecute())) { + // Ok the command cannot be executed. + } else { + fail("The command should not be executable."); + } + } else { + if((command == null) || (!command.canExecute())) { + fail("The command should be executable."); + } else { + // Simple command + if(expectedCommandNames.size() == 1) { + if(expectedCommandNames.get(0).equals(command.getLabel())) { + // Ok the command can be executed. + defaultExecutionTest(command); + // Test the results then + // fail("Result tests not implemented."); + EditorUtils.getCommandStack().undo(); + } else { + fail("The expected kind of command was {" + expectedCommandNames.get(0) + "}, but was {" + command.getLabel() + "}"); + } + } else if(expectedCommandNames.size() > 1) { + ICommand tmpCommand = (command instanceof ICommandProxy) ? ((ICommandProxy)command).getICommand() : null; + if((tmpCommand == null) || !(tmpCommand instanceof SelectAndExecuteCommand)) { + fail("The drop command is not a selact and execute command."); + } + // Field accessibility modification to review elementary drop command available as + // SelectAndExecuteCommand choices. + SelectAndExecuteCommand selectCommand = (SelectAndExecuteCommand)tmpCommand; + Field popupField = PopupMenuCommand.class.getDeclaredField("popupMenu"); + popupField.setAccessible(true); + PopupMenu menu = (PopupMenu)popupField.get(selectCommand); + Field content = PopupMenu.class.getDeclaredField("content"); + content.setAccessible(true); + List<CompoundCommand> commandList = (List<CompoundCommand>)content.get(menu); + if(commandList.size() != expectedCommandNames.size()) { + fail("Unexpected number of possible alternate drop command."); + } + for(int i = 0; i < commandList.size(); i++) { + CompoundCommand subCommand = commandList.get(i); + if(expectedCommandNames.get(i).equals(subCommand.getLabel())) { + // Ok the command can be executed. + defaultExecutionTest(subCommand); + // Add one more undo to go back in initial state before testing next command + EditorUtils.getCommandStack().undo();; + // Test the results then + // fail("Result tests not implemented."); + } else { + fail("The expected kind of command was {" + expectedCommandNames.get(i) + "}."); + } + } + } + } + } + } + + public static void createNodeFromPalette(String toolId, View containerView, boolean isAllowed) throws Exception { + if(isAllowed) { + createNodeFromPalette(toolId, containerView, isAllowed, true); + } else { + createNodeFromPalette(toolId, containerView, isAllowed, false); + } + } + + public static void createNodeFromPalette(String toolId, View containerView, boolean isAllowed, boolean execute) throws Exception { + // Find container EditPart (for command creation) + EditPart containerEditPart = getEditPart(containerView); + // Find palette tool to simulate element creation + Tool tool = getPaletteTool(toolId); + Request createRequest = getCreateRequest(tool); + // Get creation command for request + Command command = containerEditPart.getCommand(createRequest); + // if the creation is not allowed the command should not be executable + if(!isAllowed) { + if((command == null) || (!command.canExecute())) { + // Ok the command cannot be executed. + } else { + fail("The command should not be executable."); + } + } else { + if((command == null) || (!command.canExecute())) { + fail("The command should be executable."); + } else { + // Ok the command can be executed. + if(execute) { + defaultExecutionTest(command); + } + // Test the results then + // fail("Result tests not implemented."); + } + } + } + + public static Request getCreateRequest(final Tool tool) throws Exception { + + // Don't forget to set the diagram viewer (required for preferenceHints to mimic manual creation) + final IDiagramGraphicalViewer viewer = getDiagramEditor().getDiagramGraphicalViewer(); + + Display.getDefault().syncExec(new Runnable() { + + public void run() { + try { + tool.setViewer(viewer); + } catch (Exception ex) { + ex.printStackTrace(System.out); + } + } + }); + + if(tool instanceof AspectUnspecifiedTypeCreationTool) { + AspectUnspecifiedTypeCreationTool creationTool = (AspectUnspecifiedTypeCreationTool)tool; + return creationTool.createCreateRequest(); + } else if(tool instanceof AspectUnspecifiedTypeConnectionTool) { + AspectUnspecifiedTypeConnectionTool connectionTool = (AspectUnspecifiedTypeConnectionTool)tool; + return connectionTool.new CreateAspectUnspecifiedTypeConnectionRequest(connectionTool.getElementTypes(), false, Activator.DIAGRAM_PREFERENCES_HINT); + } + + throw new Exception("Unexpected kind of creation tool."); + } + + public static void createEdgeFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed) throws Exception { + // Execute command only when the command is expected to be executable + createEdgeFromPalette(toolId, sourceView, targetView, isAllowed, isAllowed); + } + + public static EObject createEdgeFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, boolean execute) throws Exception { + // Find palette tool to simulate element creation and prepare request + Tool tool = getPaletteTool(toolId); + CreateAspectUnspecifiedTypeConnectionRequest createRequest = (CreateAspectUnspecifiedTypeConnectionRequest)getCreateRequest(tool); + // Test source creation command + createRequest.setSourceEditPart(getEditPart(sourceView)); + createRequest.setType(RequestConstants.REQ_CONNECTION_START); + Command srcCommand = getEditPart(sourceView).getCommand(createRequest); + // Test source command + if((srcCommand == null) || !(srcCommand.canExecute())) { // Non-executable command + if(targetView == null) { // Only test behavior on source + if(!isAllowed) { + // Current behavior matches the expected results + return null; + } else { + fail("The command should be executable."); + } + } else { // Test complete creation, the command should necessary be executable + fail("The command should be executable."); + } + } else { // Executable command + if(targetView == null) { // Only test behavior on source + if(!isAllowed) { + fail("The command should not be executable."); + } else { + // Current behavior matches the expected results - no execution test. + return null; + } + } else { // The command is executable and a target is provided - continue the test + // Get target command (complete link creation) + createRequest.setSourceEditPart(getEditPart(sourceView)); + createRequest.setTargetEditPart(getEditPart(targetView)); + createRequest.setType(RequestConstants.REQ_CONNECTION_END); + Command tgtCommand = getEditPart(targetView).getCommand(createRequest); + // Test the target command + if((tgtCommand == null) || !(tgtCommand.canExecute())) { // Non-executable command + if(!isAllowed) { + // Current behavior matches the expected results + return null; + } else { + fail("The command should be executable."); + } + } else { // Executable command + if(!isAllowed) { + fail("The command should not be executable."); + } else { + // Current behavior matches the expected results + if(execute) { // Test command execution + defaultExecutionTest(tgtCommand); + // Retrieve created object via nested ElementAndViewCreationRequest. + View newView = null; + Iterator<?> it = createRequest.getAllRequests().iterator(); + while(it.hasNext() && newView == null) { + CreateConnectionViewAndElementRequest subRequest = (CreateConnectionViewAndElementRequest)it.next(); + newView = (View)subRequest.getConnectionViewDescriptor().getAdapter(View.class); + } + if(newView != null) { + return newView.getElement(); + } else { + fail("No edge seem to have been created."); + } + } + // Test the results then + // fail("Result tests not implemented."); + } + } + } + } + return null; + } + + public static void createEdgeConnectorFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, List<Property> nestedSourcePath, List<Property> nestedTargetPath) throws Exception { + createEdgeConnectorFromPalette(toolId, sourceView, targetView, isAllowed, isAllowed, nestedSourcePath, nestedTargetPath); + } + + public static void createEdgeConnectorFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, boolean execute, List<Property> nestedSourcePath, List<Property> nestedTargetPath) throws Exception { + EObject newLink = createEdgeFromPalette(toolId, sourceView, targetView, isAllowed, execute); + // Abort if the command is not supposed to be executable + if(!isAllowed) { + return; + } + if((newLink == null) || (!(newLink instanceof org.eclipse.uml2.uml.Connector))) { + fail("No edge or unexpected kind of edge created."); + } + // If previous test have not failed the execution / undo / re-do has been done + org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)newLink; + // Test source connector end + NestedConnectorEnd sourceNestedConnectorEnd = UMLUtil.getStereotypeApplication(connector.getEnds().get(0), NestedConnectorEnd.class); + if(nestedSourcePath.isEmpty()) { + Assert.assertNull("No nested connector end stereotype should be applied on source.", sourceNestedConnectorEnd); + } else { + Assert.assertNotNull("Nested connector end stereotype should be applied on source.", sourceNestedConnectorEnd); + Assert.assertEquals("Nested property path is incorrect for source", nestedSourcePath, sourceNestedConnectorEnd.getPropertyPath()); + // if(!sourceNestedConnectorEnd.getPropertyPath().equals(nestedSourcePath)) { + // fail("The nested property path is incorrect for source."); + // } + } + // Test target connector end + NestedConnectorEnd targetNestedConnectorEnd = UMLUtil.getStereotypeApplication(connector.getEnds().get(1), NestedConnectorEnd.class); + if(nestedTargetPath.isEmpty()) { + Assert.assertNull("No nested connector end stereotype should be applied on target.", targetNestedConnectorEnd); + } else { + Assert.assertNotNull("Nested connector end stereotype should be applied on target.", targetNestedConnectorEnd); + Assert.assertEquals("Nested property path is incorrect for target", nestedTargetPath, targetNestedConnectorEnd.getPropertyPath()); + // if(!targetNestedConnectorEnd.getPropertyPath().equals(nestedTargetPath)) { + // fail("The nested property path is incorrect for target."); + // } + } + } + + public static void createEdgeConnectorAndTestDelegateFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception { + createEdgeConnectorAndTestDelegateFromPalette(toolId, sourceView, targetView, isAllowed, isAllowed, expectedSourcePartWithPort, expectedTargetPartWithPort); + } + + public static void createEdgeConnectorAndTestDelegateFromPalette(String toolId, View sourceView, View targetView, boolean isAllowed, boolean execute, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception { + EObject newLink = createEdgeFromPalette(toolId, sourceView, targetView, isAllowed, execute); + // Abort if the command is not supposed to be executable + if(!isAllowed) { + return; + } + if((newLink == null) || (!(newLink instanceof org.eclipse.uml2.uml.Connector))) { + fail("No edge or unexpected kind of edge created."); + } + // If previous test have not failed the execution / undo / re-do has been done + org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)newLink; + // Test source connector end + ConnectorEnd sourceConnectorEnd = connector.getEnds().get(0); + if(sourceConnectorEnd.getPartWithPort() != expectedSourcePartWithPort) { + fail("The partWithPort is incorrect for source."); + } + // Test target connector end + ConnectorEnd targetConnectorEnd = connector.getEnds().get(1); + if(targetConnectorEnd.getPartWithPort() != expectedTargetPartWithPort) { + fail("The partWithPort is incorrect for target."); + } + } + + public static void reorientRelationshipSource(View relationshipView, View newSourceView, boolean isAllowed) throws Exception { + reorientRelationship((Connector)relationshipView, newSourceView, ReorientRelationshipRequest.REORIENT_SOURCE, isAllowed); + } + + public static void reorientRelationshipTarget(View relationshipView, View newTargetView, boolean isAllowed) throws Exception { + reorientRelationship((Connector)relationshipView, newTargetView, ReorientRelationshipRequest.REORIENT_TARGET, isAllowed); + } + + public static void reorientRelationship(Connector relationshipView, View newEndView, int reorientDirection, boolean isAllowed) throws Exception { + // Prepare request and add + String reconnectDirection = (ReorientRelationshipRequest.REORIENT_SOURCE == reorientDirection) ? RequestConstants.REQ_RECONNECT_SOURCE : RequestConstants.REQ_RECONNECT_TARGET; + ReconnectRequest reconnectRequest = new ReconnectRequest(relationshipView); + reconnectRequest.setTargetEditPart(getEditPart(newEndView)); + reconnectRequest.setConnectionEditPart((ConnectionEditPart)getEditPart(relationshipView)); + reconnectRequest.setType(reconnectDirection); + // Get command + Command reorientCommand = getEditPart(newEndView).getCommand(reconnectRequest); + // Test the target command + if((reorientCommand == null) || !(reorientCommand.canExecute())) { // Non-executable command + if(!isAllowed) { + // Current behavior matches the expected results + return; + } else { + fail("The command should be executable."); + } + } else { // Executable command + if(!isAllowed) { + fail("The command should not be executable."); + } else { + defaultExecutionTest(reorientCommand); + // Test the results then + // fail("Result tests not implemented."); + } + } + } + + public static void reorientConnectorSource(View relationshipView, View newSourceView, boolean isAllowed) throws Exception { + List<Property> nestedPath = Collections.emptyList(); + reorientConnectorSource(relationshipView, newSourceView, isAllowed, nestedPath); + } + + public static void reorientConnectorTarget(View relationshipView, View newTargetView, boolean isAllowed) throws Exception { + List<Property> nestedPath = Collections.emptyList(); + reorientConnectorTarget(relationshipView, newTargetView, isAllowed, nestedPath); + } + + public static void reorientConnectorSource(View relationshipView, View newSourceView, boolean isAllowed, List<Property> nestedPath) throws Exception { + reorientConnector((Connector)relationshipView, newSourceView, ReorientRelationshipRequest.REORIENT_SOURCE, isAllowed, nestedPath); + } + + public static void reorientConnectorTarget(View relationshipView, View newTargetView, boolean isAllowed, List<Property> nestedPath) throws Exception { + reorientConnector((Connector)relationshipView, newTargetView, ReorientRelationshipRequest.REORIENT_TARGET, isAllowed, nestedPath); + } + + public static void reorientConnector(Connector relationshipView, View newEndView, int reorientDirection, boolean isAllowed, List<Property> nestedPath) throws Exception { + reorientRelationship(relationshipView, newEndView, reorientDirection, isAllowed); + // Abort if the command is not supposed to be executable + if(!isAllowed) { + return; + } + // If previous test have not failed the execution / undo / re-do has been done + org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)relationshipView.getElement(); + ConnectorEnd modifiedConnectorEnd = (reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) ? connector.getEnds().get(0) : connector.getEnds().get(1); + NestedConnectorEnd nestedConnectorEnd = UMLUtil.getStereotypeApplication(modifiedConnectorEnd, NestedConnectorEnd.class); + if(nestedPath.isEmpty()) { + Assert.assertNull("No nested connector end stereotype should be applied.", nestedConnectorEnd); + } else { + Assert.assertNotNull("Nested connector end stereotype should be applied.", nestedConnectorEnd); + Assert.assertEquals("Invalid nested path", nestedPath, nestedConnectorEnd.getPropertyPath()); + } + } + + public static void reorientConnectorSourceAndTestDelegate(View relationshipView, View newSourceView, boolean isAllowed, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception { + reorientConnectorAndTestDelegate((Connector)relationshipView, newSourceView, ReorientRelationshipRequest.REORIENT_SOURCE, isAllowed, expectedSourcePartWithPort, expectedTargetPartWithPort); + } + + public static void reorientConnectorTargetAndTestDelegate(View relationshipView, View newTargetView, boolean isAllowed, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception { + reorientConnectorAndTestDelegate((Connector)relationshipView, newTargetView, ReorientRelationshipRequest.REORIENT_TARGET, isAllowed, expectedSourcePartWithPort, expectedTargetPartWithPort); + } + + public static void reorientConnectorAndTestDelegate(Connector relationshipView, View newEndView, int reorientDirection, boolean isAllowed, ConnectableElement expectedSourcePartWithPort, ConnectableElement expectedTargetPartWithPort) throws Exception { + reorientRelationship(relationshipView, newEndView, reorientDirection, isAllowed); + // Abort if the command is not supposed to be executable + if(!isAllowed) { + return; + } + // If previous test have not failed the execution / undo / re-do has been done + org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)relationshipView.getElement(); + ConnectorEnd modifiedConnectorEnd = (reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) ? connector.getEnds().get(0) : connector.getEnds().get(1); + ConnectorEnd oppositeConnectorEnd = (reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) ? connector.getEnds().get(1) : connector.getEnds().get(0); + if(reorientDirection == ReorientRelationshipRequest.REORIENT_SOURCE) { // re-orient source + // Test source connector end + Assert.assertEquals("The partWithPort is incorrect for source (re-oriented).", expectedSourcePartWithPort, modifiedConnectorEnd.getPartWithPort()); + // if(modifiedConnectorEnd.getPartWithPort() != expectedSourcePartWithPort) { + // fail("The partWithPort is incorrect for source (re-oriented)."); + // } + // Test target connector end + Assert.assertEquals("The partWithPort is incorrect for target (opposite end).", expectedTargetPartWithPort, oppositeConnectorEnd.getPartWithPort()); + // if(oppositeConnectorEnd.getPartWithPort() != expectedTargetPartWithPort) { + // fail("The partWithPort is incorrect for target (opposite end)."); + // } + } else { // re-orient target + // Test source connector end + Assert.assertEquals("The partWithPort is incorrect for target (re-oriented).", expectedTargetPartWithPort, modifiedConnectorEnd.getPartWithPort()); + // if(modifiedConnectorEnd.getPartWithPort() != expectedTargetPartWithPort) { + // fail("The partWithPort is incorrect for target ."); + // } + // Test target connector end + Assert.assertEquals("The partWithPort is incorrect for source (opposite end).", expectedSourcePartWithPort, oppositeConnectorEnd.getPartWithPort()); + // if(oppositeConnectorEnd.getPartWithPort() != expectedSourcePartWithPort) { + // fail("The partWithPort is incorrect for source (opposite end)."); + // } + } + } + + public static void setEncapsulationDeleteConnectorTest(Element block, View sourceView, View targetView, boolean canCreateConnector, boolean isConnectorDestroyExpected) throws Exception { + if(!canCreateConnector) { + return; // abort + } + // Make sure the block is not encapsulated before Connector creation. + TestPrepareUtils.setBlockIsEncapsulated(block, false); + // Create connector + org.eclipse.uml2.uml.Connector connector = (org.eclipse.uml2.uml.Connector)createEdgeFromPalette("internalblock.tool.connector", sourceView, targetView, true, true); + // Prepare set encapsulated command and execute (with undo, re-do). + Block blockApp = UMLUtil.getStereotypeApplication(block, Block.class); + IElementEditService provider = ElementEditServiceUtils.getCommandProvider(blockApp); + if(provider == null) { + fail("Could not get IElementEditService for Block stereotype application."); + } + IEditCommandRequest setEncapsulationRequest = new SetRequest(getTransactionalEditingDomain(), blockApp, BlocksPackage.eINSTANCE.getBlock_IsEncapsulated(), true); + ICommand setEncapsulationCommand = provider.getEditCommand(setEncapsulationRequest); + defaultExecutionTest(new ICommandProxy(setEncapsulationCommand)); + // Test if the Connector have been destroyed + if(isConnectorDestroyExpected) { + if(connector.eResource() != null) { // connector destroyed has no container + fail("Connector was expected to be destroyed."); + } + } else { + if(connector.eResource() == null) { // connector destroyed has no container + fail("Connector was not expected to be destroyed."); + } + } + } + + /** + * Copy the list of objects into the Clipboard + * + * @param objectsToCopy + * the list of objects to copy. should not be <code>null</code>, at least an empty list + * @throws Exception + * exception thrown in case of problems + */ + public static void copyEditParts(List<Object> objectsToCopy) throws Exception { + // select elements to copy + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(EditorUtils.getEditor()); + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().bringToTop(EditorUtils.getEditor()); + EditorUtils.getDiagramEditor().getEditorSite().getSelectionProvider().setSelection(new StructuredSelection(objectsToCopy)); + ISelection selection = EditorUtils.getEditor().getSite().getSelectionProvider().getSelection(); + Assert.assertEquals("Selection size should be " + objectsToCopy.size(), objectsToCopy.size(), ((IStructuredSelection)selection).size()); + // retrieve the command for copy + ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class); + commandService.refreshElements(IWorkbenchCommandConstants.EDIT_COPY, null); + org.eclipse.core.commands.Command copyCommand = commandService.getCommand(IWorkbenchCommandConstants.EDIT_COPY); + ((GlobalCopyAction)((ActionHandler)copyCommand.getHandler()).getAction()).setEnabled(true); + Assert.assertNotNull("Impossible to find copy command", copyCommand); + //EditorUtils.getDiagramEditor().getEditingDomain().setClipboard(objectsToCopy); + // retrieve handler service for the copy command + IHandlerService handlerService = (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class); + Assert.assertNotNull("Impossible to find handler service", handlerService); + final ParameterizedCommand parameterizedCommand = new ParameterizedCommand(copyCommand, null); + // retrieve the command and set some parameters on it + copyCommand.setEnabled(handlerService.getCurrentState()); + final boolean commandEnabled = copyCommand.isEnabled(); + Assert.assertTrue("Command should be enabled", commandEnabled); + // execute the copy command + handlerService.executeCommand(parameterizedCommand, null); + } + + /** + * paste the list of objects into the Clipboard into the current diagram + * + * @param target + * object on which content of the clipboard should be added + * @param executable + * indicates if the paste command should be executable. + * + * @throws Exception + * exception thrown in case of problems + */ + public static void pasteEditParts(Object target, boolean executable) throws Exception { + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(EditorUtils.getEditor()); + EditorUtils.getDiagramEditor().getEditorSite().getSelectionProvider().setSelection(new StructuredSelection(target)); + // retrieve the command for copy + ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class); + commandService.refreshElements(IWorkbenchCommandConstants.EDIT_PASTE, null); + org.eclipse.core.commands.Command pasteCommand = commandService.getCommand(IWorkbenchCommandConstants.EDIT_PASTE); + Assert.assertNotNull("Impossible to find paste command", pasteCommand); + ((GlobalAction)((ActionHandler)pasteCommand.getHandler()).getAction()).refresh(); + IHandlerService handlerService = (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class); + Assert.assertNotNull("Impossible to find handler service", handlerService); + final ParameterizedCommand parameterizedCommand = new ParameterizedCommand(pasteCommand, null); + Assert.assertEquals("Command is not executable as expected", pasteCommand.isEnabled(), executable); + if(executable) { + // execute the copy command + handlerService.executeCommand(parameterizedCommand, null); + } + } + + /** + * paste with model element the list of objects into the Clipboard into the current diagram + * + * @param target + * object on which content of the clipboard should be added + * @param executable + * indicates if the paste command should be executable. + * + * @throws Exception + * exception thrown in case of problems + */ + public static void pasteWithModelEditParts(Object target, boolean executable) throws Exception { + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(EditorUtils.getEditor()); + EditorUtils.getDiagramEditor().getEditorSite().getSelectionProvider().setSelection(new StructuredSelection(target)); + // retrieve the command for copy + ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class); + commandService.refreshElements(IWorkbenchCommandConstants.EDIT_PASTE, null); + org.eclipse.core.commands.Command pasteWithModelCommand = commandService.getCommand("org.eclipse.papyrus.uml.diagram.common.commands.PasteWithModelCommand"); + Assert.assertNotNull("Impossible to find paste command", pasteWithModelCommand); + // ((GlobalAction)((AbstractHandlerWithState)pasteWithModelCommand.getHandler()).getAction()).refresh(); + IHandlerService handlerService = (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class); + Assert.assertNotNull("Impossible to find handler service", handlerService); + final ParameterizedCommand parameterizedCommand = new ParameterizedCommand(pasteWithModelCommand, null); + Assert.assertEquals("Command is not executable as expected", pasteWithModelCommand.isEnabled(), executable); + if(executable) { + // execute the copy command + handlerService.executeCommand(parameterizedCommand, null); + } + } + + // History event type variable to store history error events. + public static int historyEventType = OperationHistoryEvent.DONE; + + /** + * Test execution, undo, redo of the given command. + * + * @param command + * the command to test. + * @throws Exception + */ + public static void defaultExecutionTest(Command command) throws Exception { + // Execution in the diagram command stack (like Papyrus usual execution for GEF commands). This is important especially for + // composed command like Drop links which create intermediate view during execution. With EMF command stack, the whole command + // tries to execute and the edit part of the intermediate created views are not created before the command ends. + // The diagram command stack let edit part being created after each view creation. + // The problem in using the DiagramCommandStack (vs EMF CommandStack) is that it hides any exception that can possibly occur during + // command execution. This would let the test finish without error (the command result is not tested currently) while the execution failed. + // For this matter the DiagramCommandStack history is observed to detect execution issues. + // Add diagram command stack operation history listener + IOperationHistory history = EditorUtils.getDiagramEditingDomain().getActionManager().getOperationHistory(); + IOperationHistoryListener historyChange = new IOperationHistoryListener() { + + public void historyNotification(OperationHistoryEvent event) { + // Store history events + historyEventType = event.getEventType(); + } + }; + history.addOperationHistoryListener(historyChange); + // Test execution + historyEventType = OperationHistoryEvent.DONE; + EditorUtils.getDiagramCommandStack().execute(command); + if(historyEventType == OperationHistoryEvent.OPERATION_NOT_OK) { + fail("Command execution failed ()"); + } + // Test undo + historyEventType = OperationHistoryEvent.DONE; + EditorUtils.getDiagramCommandStack().undo(); + if(historyEventType == OperationHistoryEvent.OPERATION_NOT_OK) { + fail("Command undo failed ()"); + } + // Test redo + historyEventType = OperationHistoryEvent.DONE; + EditorUtils.getDiagramCommandStack().redo(); + if(historyEventType == OperationHistoryEvent.OPERATION_NOT_OK) { + fail("Command redo failed ()"); + } + // Remove listener. + history.removeOperationHistoryListener(historyChange); + } +} |