Generation chain extension that generate EcoreTools Sirius based diagrams first commit
diff --git a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/.settings/org.eclipse.jdt.core.prefs b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/.settings/org.eclipse.jdt.core.prefs index e131649..44217f8 100644 --- a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/.settings/org.eclipse.jdt.core.prefs +++ b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/.settings/org.eclipse.jdt.core.prefs
@@ -1,4 +1,3 @@ -#Mon May 02 13:42:05 CEST 2011 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
diff --git a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/META-INF/MANIFEST.MF b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/META-INF/MANIFEST.MF index ef36ca8..e885865 100644 --- a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/META-INF/MANIFEST.MF +++ b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/META-INF/MANIFEST.MF
@@ -4,10 +4,16 @@ Bundle-Vendor: %providerName Bundle-SymbolicName: org.eclipse.egf.portfolio.genchain.ecoretools;singleton:=true Bundle-Version: 1.1.0.qualifier -Require-Bundle: org.eclipse.emf.ecoretools.diagram, - org.eclipse.gmf.runtime.diagram.ui, +Require-Bundle: org.eclipse.gmf.runtime.diagram.ui, org.eclipse.egf.portfolio.genchain.tools, - org.eclipse.egf.portfolio.genchain.tools.ui + org.eclipse.egf.portfolio.genchain.tools.ui, + org.eclipse.sirius;bundle-version="1.0.0", + org.eclipse.sirius.common;bundle-version="1.0.0", + org.eclipse.sirius.ui, + org.eclipse.sirius.table, + org.eclipse.sirius.ecore.extender;bundle-version="1.0.0", + org.eclipse.sirius.diagram;bundle-version="1.0.0", + org.eclipse.sirius.common.ui;bundle-version="1.0.0" Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: J2SE-1.5 Export-Package: org.eclipse.egf.portfolio.genchain.ecoretools,
diff --git a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/generated/org/eclipse/egf/portfolio/genchain/ecoretools/pattern/ecoreTools.java b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/generated/org/eclipse/egf/portfolio/genchain/ecoretools/pattern/ecoreTools.java index b038d3d..6186d38 100644 --- a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/generated/org/eclipse/egf/portfolio/genchain/ecoretools/pattern/ecoreTools.java +++ b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/generated/org/eclipse/egf/portfolio/genchain/ecoretools/pattern/ecoreTools.java
@@ -1,110 +1,120 @@ -//Generated on Thu Jan 12 17:22:19 CET 2012 with EGF 0.6.1.qualifier -package org.eclipse.egf.portfolio.genchain.ecoretools.pattern; - -import java.util.*; -import org.eclipse.emf.ecore.*; -import org.eclipse.egf.model.pattern.*; -import org.eclipse.egf.pattern.execution.*; -import org.eclipse.egf.pattern.query.*; -import org.eclipse.egf.common.helper.*; -import org.eclipse.egf.portfolio.genchain.generationChain.GenerationElement; -import org.eclipse.egf.portfolio.genchain.tools.FcoreBuilderConstants; -import org.eclipse.egf.portfolio.genchain.tools.utils.ActivityInvocationHelper; -import org.eclipse.emf.ecore.resource.ResourceSet; -import org.eclipse.egf.model.fcore.Activity; -import org.eclipse.egf.model.fcore.FactoryComponent; -import org.eclipse.egf.model.fprod.ProductionPlan; -import org.eclipse.emf.common.util.URI; -import org.eclipse.egf.model.types.Type; -import org.eclipse.egf.model.types.TypeString; -import org.eclipse.egf.model.types.TypeURI; -import org.eclipse.egf.model.fcore.Contract; -import org.eclipse.egf.model.types.TypesFactory; - -public class ecoreTools { - - public ecoreTools() { - //Here is the constructor - // add initialisation of the pattern variables (declaration has been already done). - } - - public void generate(Object argument) throws Exception { - InternalPatternContext ctx = (InternalPatternContext) argument; - IQuery.ParameterDescription paramDesc = null; - Map<String, String> queryCtx = null; - Node.Container currentNode = ctx.getNode(); - List<Object> parameterList = null; - //this pattern can only be called by another (i.e. it's not an entry point in execution) - - for (Object parameterParameter : parameterList) { - - this.parameter = (org.eclipse.egf.portfolio.genchain.ecoretools.ecoreToolsExtension.EcoreToolsGeneration) parameterParameter; - - if (preCondition(ctx)) { - ctx.setNode(new Node.Container(currentNode, getClass())); - orchestration((PatternContext) argument); - - } - } - if (ctx.useReporter()) { - ctx.getReporter().executionFinished(OutputManager.computeExecutionOutput(ctx), ctx); - } - } - - public String orchestration(PatternContext ctx) throws Exception { - InternalPatternContext ictx = (InternalPatternContext) ctx; - Node.Container currentNode = ictx.getNode(); - method_body(new StringBuffer(), ictx); - ictx.setNode(currentNode); - if (ictx.useReporter()) { - Map<String, Object> parameterValues = new HashMap<String, Object>(); - parameterValues.put("parameter", this.parameter); - String outputWithCallBack = OutputManager.computeLoopOutput(ictx); - String loop = OutputManager.computeLoopOutputWithoutCallback(ictx); - ictx.getReporter().loopFinished(loop, outputWithCallBack, ictx, parameterValues); - } - return null; - } - - protected void method_body(final StringBuffer out, final PatternContext ctx) throws Exception { - Map<GenerationElement, FactoryComponent> fcs = (Map<GenerationElement, FactoryComponent>) ctx.getValue(FcoreBuilderConstants.CURRENT_FCORE); - FactoryComponent fc = fcs.get((GenerationElement) (parameter.eContainer())); - ResourceSet resourceSet = fc.eResource().getResourceSet(); - ProductionPlan pp = (ProductionPlan) fc.getOrchestration(); - URI uri = URI.createURI("platform:/plugin/org.eclipse.egf.portfolio.genchain.ecoretools/egf/ecoreToolsExtension.fcore#_wQgLIHS0EeC3aZAQAbtFJA", false); - Activity activity = (Activity) resourceSet.getEObject(uri, true); - - Map<String, Type> contract2type = new HashMap<String, Type>(); - - TypeURI typeURI = TypesFactory.eINSTANCE.createTypeURI(); - typeURI.setValue(URI.createPlatformResourceURI(parameter.getModelPath(), true)); - - TypeString typeString = TypesFactory.eINSTANCE.createTypeString(); - typeString.setValue(parameter.getFileName()); - - contract2type.put("model", typeURI); - contract2type.put("fileName", typeString); - - ActivityInvocationHelper.addInvocation(pp, activity, contract2type); - - InternalPatternContext ictx = (InternalPatternContext) ctx; - new Node.DataLeaf(ictx.getNode(), getClass(), "body", out.toString()); - } - - public boolean preCondition(PatternContext ctx) throws Exception { - return true; - } - - protected org.eclipse.egf.portfolio.genchain.ecoretools.ecoreToolsExtension.EcoreToolsGeneration parameter; - - public void set_parameter(org.eclipse.egf.portfolio.genchain.ecoretools.ecoreToolsExtension.EcoreToolsGeneration parameter) { - this.parameter = parameter; - } - - public Map<String, Object> getParameters() { - Map<String, Object> parameters = new HashMap<String, Object>(); - parameters.put("parameter", this.parameter); - return parameters; - } - -} +//Generated on Wed Apr 09 17:15:07 CEST 2014 with EGF 1.1.0.v20140331-0638 +package org.eclipse.egf.portfolio.genchain.ecoretools.pattern; + +import java.util.*; +import org.eclipse.emf.ecore.*; +import org.eclipse.egf.model.pattern.*; +import org.eclipse.egf.pattern.execution.*; +import org.eclipse.egf.pattern.query.*; +import org.eclipse.egf.common.helper.*; +import org.eclipse.egf.portfolio.genchain.generationChain.GenerationElement; +import org.eclipse.egf.portfolio.genchain.tools.FcoreBuilderConstants; +import org.eclipse.egf.portfolio.genchain.tools.utils.ActivityInvocationHelper; +import org.eclipse.emf.ecore.resource.ResourceSet; +import org.eclipse.egf.model.fcore.Activity; +import org.eclipse.egf.model.fcore.FactoryComponent; +import org.eclipse.egf.model.fprod.ProductionPlan; +import org.eclipse.emf.common.util.URI; +import org.eclipse.egf.model.types.Type; +import org.eclipse.egf.model.types.TypeString; +import org.eclipse.egf.model.types.TypeURI; +import org.eclipse.egf.model.fcore.Contract; +import org.eclipse.egf.model.types.TypesFactory; + +public class ecoreTools { + + public ecoreTools() { + //Here is the constructor + // add initialisation of the pattern variables (declaration has been already done). + } + + public void generate(Object argument) throws Exception { + InternalPatternContext ctx = (InternalPatternContext) argument; + IQuery.ParameterDescription paramDesc = null; + Map<String, String> queryCtx = null; + Node.Container currentNode = ctx.getNode(); + List<Object> parameterList = null; + //this pattern can only be called by another (i.e. it's not an entry point in execution) + + for (Object parameterParameter : parameterList) { + + this.parameter = (org.eclipse.egf.portfolio.genchain.ecoretools.ecoreToolsExtension.EcoreToolsGeneration) parameterParameter; + + if (preCondition(ctx)) { + ctx.setNode(new Node.Container(currentNode, getClass())); + orchestration((PatternContext) argument); + + } + } + if (ctx.useReporter()) { + ctx.getReporter().executionFinished( + OutputManager.computeExecutionOutput(ctx), ctx); + } + } + + public String orchestration(PatternContext ctx) throws Exception { + InternalPatternContext ictx = (InternalPatternContext) ctx; + Node.Container currentNode = ictx.getNode(); + method_body(new StringBuffer(), ictx); + ictx.setNode(currentNode); + if (ictx.useReporter()) { + Map<String, Object> parameterValues = new HashMap<String, Object>(); + parameterValues.put("parameter", this.parameter); + String outputWithCallBack = OutputManager.computeLoopOutput(ictx); + String loop = OutputManager.computeLoopOutputWithoutCallback(ictx); + ictx.getReporter().loopFinished(loop, outputWithCallBack, ictx, + parameterValues); + } + return null; + } + + protected void method_body(final StringBuffer out, final PatternContext ctx) + throws Exception { + Map<GenerationElement, FactoryComponent> fcs = (Map<GenerationElement, FactoryComponent>) ctx + .getValue(FcoreBuilderConstants.CURRENT_FCORE); + FactoryComponent fc = fcs.get((GenerationElement) (parameter + .eContainer())); + ResourceSet resourceSet = fc.eResource().getResourceSet(); + ProductionPlan pp = (ProductionPlan) fc.getOrchestration(); + URI uri = URI + .createURI( + "platform:/plugin/org.eclipse.egf.portfolio.genchain.ecoretools/egf/ecoreToolsExtension.fcore#_wQgLIHS0EeC3aZAQAbtFJA", + false); + Activity activity = (Activity) resourceSet.getEObject(uri, true); + + Map<String, Type> contract2type = new HashMap<String, Type>(); + + TypeURI typeURI = TypesFactory.eINSTANCE.createTypeURI(); + typeURI.setValue(URI.createPlatformResourceURI( + parameter.getModelPath(), true)); + + TypeString typeString = TypesFactory.eINSTANCE.createTypeString(); + typeString.setValue(parameter.getFileName()); + + contract2type.put("model", typeURI); + contract2type.put("fileName", typeString); + + ActivityInvocationHelper.addInvocation(pp, activity, contract2type); + + InternalPatternContext ictx = (InternalPatternContext) ctx; + new Node.DataLeaf(ictx.getNode(), getClass(), "body", out.toString()); + } + + public boolean preCondition(PatternContext ctx) throws Exception { + return true; + } + + protected org.eclipse.egf.portfolio.genchain.ecoretools.ecoreToolsExtension.EcoreToolsGeneration parameter; + + public void set_parameter( + org.eclipse.egf.portfolio.genchain.ecoretools.ecoreToolsExtension.EcoreToolsGeneration parameter) { + this.parameter = parameter; + } + + public Map<String, Object> getParameters() { + Map<String, Object> parameters = new HashMap<String, Object>(); + parameters.put("parameter", this.parameter); + return parameters; + } + +}
diff --git a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/EcoreToolsExtension.java b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/EcoreToolsExtension.java index c9c646e..88377e3 100644 --- a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/EcoreToolsExtension.java +++ b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/EcoreToolsExtension.java
@@ -30,6 +30,9 @@ import org.eclipse.emf.common.util.URI; public class EcoreToolsExtension extends ExtensionHelper { + /** Sirius representation files extension **/ + private final static String _AIRD_FILE_EXTENSION = "aird"; + private static final URI PATTERN = URI.createURI("platform:/plugin/org.eclipse.egf.portfolio.genchain.ecoretools/egf/ecoreToolsExtension.fcore#_Mf1nEHyqEeC0R_Dv0EljeA", false); @Override @@ -40,7 +43,7 @@ if (properties.get("fileName") != null && properties.get("fileName").length() > 0) { fileName = properties.get("fileName"); } else { - fileName = modelPath.concat("diag"); + fileName = modelPath.concat(_AIRD_FILE_EXTENSION); } ecoreToolsGeneration.setModelPath(modelPath); ecoreToolsGeneration.setFileName(fileName); @@ -68,7 +71,7 @@ protected void computeDefaultProperties(Map<String, String> context) { final String modelPath = context.get(CONTEXT_MODEL_NAME); final String projectName = context.get(CONTEXT_PROJECT_NAME); - properties.put(EcoreToolsExtensionPackage.eINSTANCE.getEcoreToolsGeneration_FileName(), projectName + "/model/" + modelPath.concat(".ecorediag")); + properties.put(EcoreToolsExtensionPackage.eINSTANCE.getEcoreToolsGeneration_FileName(), projectName + "/model/" + modelPath.concat("."+_AIRD_FILE_EXTENSION)); } }
diff --git a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/command/CreateEdgeCommand.java b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/command/CreateEdgeCommand.java new file mode 100644 index 0000000..832f231 --- /dev/null +++ b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/command/CreateEdgeCommand.java
@@ -0,0 +1,199 @@ +package org.eclipse.egf.portfolio.genchain.ecoretools.command; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.transaction.RecordingCommand; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.sirius.business.api.componentization.DiagramMappingsManager; +import org.eclipse.sirius.business.api.query.EdgeMappingQuery; +import org.eclipse.sirius.business.api.session.Session; +import org.eclipse.sirius.business.internal.componentization.mappings.DiagramMappingsManagerRegistryImpl; +import org.eclipse.sirius.business.internal.experimental.sync.DDiagramElementSynchronizer; +import org.eclipse.sirius.business.internal.experimental.sync.DDiagramSynchronizer; +import org.eclipse.sirius.business.internal.experimental.sync.DEdgeCandidate; +import org.eclipse.sirius.common.tools.api.interpreter.EvaluationException; +import org.eclipse.sirius.common.tools.api.interpreter.IInterpreter; +import org.eclipse.sirius.viewpoint.DDiagram; +import org.eclipse.sirius.viewpoint.DDiagramElementContainer; +import org.eclipse.sirius.viewpoint.DNode; +import org.eclipse.sirius.viewpoint.DSemanticDecorator; +import org.eclipse.sirius.viewpoint.DSemanticDiagram; +import org.eclipse.sirius.viewpoint.EdgeTarget; +import org.eclipse.sirius.viewpoint.description.ContainerMapping; +import org.eclipse.sirius.viewpoint.description.DiagramElementMapping; +import org.eclipse.sirius.viewpoint.description.EdgeMapping; +import org.eclipse.sirius.viewpoint.description.MappingBasedDecoration; +import org.eclipse.sirius.viewpoint.description.NodeMapping; +import org.eclipse.sirius.viewpoint.description.SemanticBasedDecoration; + +/** + * Command that create an Edge in a diagram + * + * @author Boubekeur Zendagui + */ +@SuppressWarnings("restriction") +public class CreateEdgeCommand extends RecordingCommand { + + /** Command properties **/ + private DDiagram _diagram; + private Session _session; + private EdgeMapping _mapping; + private EObject _target; + private boolean _isElementBasedEdge; + + /** + * Default constructor + * @param session the {@link Session} used to create the Edge + * @param diagramthe {@link DDiagram} wherein the Edge will be created + * @param mapping the {@link EdgeMapping} describing the edge + * @param target {@link EObject} used as target semantic element of the edge + * @param isElementBasedEdge if <code> true </code> the edge is an element based edge + */ + public CreateEdgeCommand(Session session, DDiagram diagram, EdgeMapping mapping, EObject target, boolean isElementBasedEdge){ + this(session.getTransactionalEditingDomain()); + this._diagram = diagram; + this._session = session; + this._mapping = mapping; + this._target = target; + this._isElementBasedEdge = isElementBasedEdge; + } + + /** + * Hidden constructor + * @param domain a {@link TransactionalEditingDomain} + */ + private CreateEdgeCommand(TransactionalEditingDomain domain) { + super(domain); + } + + @Override + protected void doExecute() { + final DDiagramSynchronizer diagramSynchronizer = new DDiagramSynchronizer(_session.getInterpreter(), _diagram.getDescription(), _session.getModelAccessor()); + diagramSynchronizer.setDiagram((DSemanticDiagram)_diagram); + + /* maps for decorations */ + Map<EdgeMapping, Collection<MappingBasedDecoration>> edgeToMappingBasedDecoration = new HashMap<EdgeMapping, Collection<MappingBasedDecoration>>(); + Map<String, Collection<SemanticBasedDecoration>> edgeToSemanticBasedDecoration = new HashMap<String, Collection<SemanticBasedDecoration>>(); + + /* create the mapping to edge targets map */ + DDiagramElementSynchronizer elementSynchronizer = diagramSynchronizer.getElementSynchronizer(); + Map<DiagramElementMapping, Collection<EdgeTarget>> mappingsToEdgeTargets = elementSynchronizer.computeMappingsToEdgeTargets(_session.getSelectedViewpoints(false)); + diagramSynchronizer.computeDecorations(mappingsToEdgeTargets, edgeToSemanticBasedDecoration, edgeToMappingBasedDecoration); + + final DiagramMappingsManager diagramMappingsManager = DiagramMappingsManagerRegistryImpl.INSTANCE.getDiagramMappingsManager(_session, _diagram); + + /* create Edge Candidate object*/ + try { + /* Get all possible source nodes from the diagram */ + List<EdgeTarget> sourceNodes = getSourceNodes(); + /* Get all possible target nodes from the diagram */ + List<EdgeTarget> targetNodes = getTargetNodes(); + /* Try to create edges between sources and targets */ + for (EdgeTarget sourceEdgeTarget : sourceNodes) + { + for (EdgeTarget targetEdgeTarget : targetNodes) + { + // + EdgeMappingQuery edgeMappingQuery = new EdgeMappingQuery(_mapping); + boolean precondition = edgeMappingQuery.evaluatePrecondition((DSemanticDiagram)_diagram, _diagram, _session.getInterpreter(), _target, (DSemanticDecorator)sourceEdgeTarget, (DSemanticDecorator)targetEdgeTarget); + if (precondition) + { + DEdgeCandidate candidate = new DEdgeCandidate(_mapping,_target, sourceEdgeTarget, targetEdgeTarget); + elementSynchronizer.createNewEdge(diagramMappingsManager, candidate, mappingsToEdgeTargets, edgeToMappingBasedDecoration, edgeToSemanticBasedDecoration); + } + } + } + } catch (EvaluationException e) { + e.printStackTrace(); + } + } + + /** + * Get all source + * @return a list of {@link EdgeTarget} element candidate to be source node + * @throws EvaluationException + */ + public List<EdgeTarget> getSourceNodes() throws EvaluationException{ + List<EdgeTarget> result = new ArrayList<EdgeTarget>(); + Collection<EObject> sematicSources = new ArrayList<EObject>(); + + IInterpreter interpreter = _session.getInterpreter(); + if (_isElementBasedEdge) + sematicSources = interpreter.evaluateCollection(_target, _mapping.getSourceFinderExpression()); + else + sematicSources.add(_target); + + EList<DiagramElementMapping> sourceMapping = _mapping.getSourceMapping(); + for (EObject eObject : sematicSources) + { + List<EdgeTarget> sources = getNodesFromDiagram(sourceMapping, eObject); + if (! sources.isEmpty()) + result.addAll(sources); + } + + return result; + } + + public List<EdgeTarget> getTargetNodes() throws EvaluationException{ + List<EdgeTarget> result = new ArrayList<EdgeTarget>(); + IInterpreter interpreter = _session.getInterpreter(); + Collection<EObject> sematicTarget = new ArrayList<EObject>(); + try { + sematicTarget = interpreter.evaluateCollection(_target, _mapping.getTargetFinderExpression()); + } catch (EvaluationException e) { + // TODO: handle exception + } + + EList<DiagramElementMapping> targetMapping = _mapping.getTargetMapping(); + for (EObject eObject : sematicTarget) + { + List<EdgeTarget> targets = getNodesFromDiagram(targetMapping, eObject); + if (! targets.isEmpty()) + result.addAll(targets); + } + + return result; + } + + /** + * Get node from diagram + * @param mapping a list of {@link DiagramElementMapping} + * @param semantic the semantic element + * @return + */ + private List<EdgeTarget> getNodesFromDiagram(EList<DiagramElementMapping> mapping, EObject semantic) { + List<EdgeTarget> result = new ArrayList<EdgeTarget>(); + // Get the diagram node for which semantic element is target + for (DiagramElementMapping diagramElementMapping : mapping) + { + if (diagramElementMapping instanceof ContainerMapping) + { + EList<DDiagramElementContainer> containers = _diagram.getContainersFromMapping((ContainerMapping) diagramElementMapping); + for (DDiagramElementContainer dDiagramElementContainer : containers) + { + if (dDiagramElementContainer.getTarget().equals(semantic)) + result.add(dDiagramElementContainer); + } + + } + + if (diagramElementMapping instanceof NodeMapping) + { + EList<DNode> nodes = _diagram.getNodesFromMapping((NodeMapping) diagramElementMapping); + for (DNode dNode : nodes) + { + if (dNode.getTarget().equals(semantic)) + result.add(dNode); + } + } + } + return result; + } + +}
diff --git a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/command/CreateNodeCommand.java b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/command/CreateNodeCommand.java new file mode 100644 index 0000000..df1d553 --- /dev/null +++ b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/command/CreateNodeCommand.java
@@ -0,0 +1,136 @@ +package org.eclipse.egf.portfolio.genchain.ecoretools.command; + +import java.util.ArrayList; +import java.util.Collection; + +import org.eclipse.emf.common.util.BasicEList; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.transaction.RecordingCommand; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.sirius.business.api.componentization.DiagramMappingsManager; +import org.eclipse.sirius.business.api.query.AbstractNodeMappingQuery; +import org.eclipse.sirius.business.api.session.Session; +import org.eclipse.sirius.business.internal.componentization.mappings.DiagramMappingsManagerRegistryImpl; +import org.eclipse.sirius.business.internal.experimental.sync.AbstractDNodeCandidate; +import org.eclipse.sirius.business.internal.experimental.sync.DDiagramSynchronizer; +import org.eclipse.sirius.common.tools.api.interpreter.EvaluationException; +import org.eclipse.sirius.common.tools.api.interpreter.IInterpreter; +import org.eclipse.sirius.ecore.extender.business.api.accessor.ModelAccessor; +import org.eclipse.sirius.viewpoint.AbstractDNode; +import org.eclipse.sirius.viewpoint.DDiagram; +import org.eclipse.sirius.viewpoint.DSemanticDiagram; +import org.eclipse.sirius.viewpoint.DragAndDropTarget; +import org.eclipse.sirius.viewpoint.description.AbstractNodeMapping; +import org.eclipse.sirius.viewpoint.description.ContainerMapping; +import org.eclipse.sirius.viewpoint.description.DiagramElementMapping; +import org.eclipse.sirius.viewpoint.description.NodeMapping; + +/** + * Recording command allowing to create a node in a diagram + * @author Boubekeur Zendagui + */ + +@SuppressWarnings("restriction") +public class CreateNodeCommand extends RecordingCommand { + + /** Command properties **/ + private DDiagram _diagram; + private Session _session; + private AbstractNodeMapping _mapping; + private EObject _target; + + /** Internal properties **/ + private DDiagramSynchronizer diagramSynchronizer; + private DiagramMappingsManager diagramMappingsManager; + private IInterpreter interpreter; + private ModelAccessor modelAccessor; + + /** + * Default constructor + * @param session used {@link Session} to create representations + * @param diagram {@link DDiagram} wherein the node will be created + * @param mapping an {@link AbstractNodeMapping} used to create the node + * @param target semantic element + */ + public CreateNodeCommand(Session session, DDiagram diagram, AbstractNodeMapping mapping, EObject target ) { + this(session.getTransactionalEditingDomain()); + this._diagram = diagram; + this._session = session; + this._mapping = mapping; + this._target = target; + /* This properties are set as class properties because they are used in a recursive method #createOneNode(). + * This allows to control created instance number. */ + this.interpreter = _session.getInterpreter(); + this.diagramSynchronizer = new DDiagramSynchronizer(this.interpreter, _diagram.getDescription(), _session.getModelAccessor()); + this.diagramSynchronizer.setDiagram((DSemanticDiagram)_diagram); + this.diagramMappingsManager = DiagramMappingsManagerRegistryImpl.INSTANCE.getDiagramMappingsManager(_session, _diagram); + this.modelAccessor = _session.getModelAccessor(); + } + + /** + * Hidden constructor + * @param domain {@link TransactionalEditingDomain} + */ + private CreateNodeCommand(TransactionalEditingDomain domain) { + super(domain); + } + + @Override + protected void doExecute() { + AbstractNodeMappingQuery abstractNodeMappingQuery = new AbstractNodeMappingQuery(_mapping); + boolean preCondition = abstractNodeMappingQuery.evaluatePrecondition((DSemanticDiagram)_diagram, _diagram, interpreter, _target); + if (preCondition) + { + createNodeAndItChildrenNodes(_target, _mapping, _diagram); + } + } + + + /** + * Create node and its sub nodes if there is sub mappings defined in it description + * @param nodeMapping current {@link AbstractNodeMapping} which can be a {@link NodeMapping} or a {@link ContainerMapping} + * @param semantic current root semantic element + * @param parent a {@link DragAndDropTarget} element wherein the node will be created + */ + private void createNodeAndItChildrenNodes(EObject semantic, AbstractNodeMapping nodeMapping, DragAndDropTarget parent){ + // create concerned node + AbstractDNode parentNode = createOneNode(semantic, nodeMapping, parent); + + // create it sub nodes + EList<AbstractNodeMapping> childrenNodeMapping = new BasicEList<AbstractNodeMapping>(); + for (DiagramElementMapping iDiagramElementMapping : nodeMapping.getAllMappings()) + { + if (iDiagramElementMapping instanceof AbstractNodeMapping) + childrenNodeMapping.add((AbstractNodeMapping) iDiagramElementMapping); + } + + for (AbstractNodeMapping childNodeMapping : childrenNodeMapping) + { + Collection<EObject> candidatesSemanticChildren = new ArrayList<EObject>(); + try { + candidatesSemanticChildren = interpreter.evaluateCollection(semantic, childNodeMapping.getSemanticCandidatesExpression()); + } catch (EvaluationException e) { + e.printStackTrace(); + } + + for (EObject childSemantic : candidatesSemanticChildren) + { + if (modelAccessor.eInstanceOf(childSemantic, childNodeMapping.getDomainClass())) + createNodeAndItChildrenNodes(childSemantic, childNodeMapping, (DragAndDropTarget) parentNode); + } + } + } + + /** + * Create one node in the current {@link DDiagram} + * @param mapping {@link AbstractNodeMapping} describing the node to create + * @param target {@link EObject} used to create the node + * @param parent a {@link DragAndDropTarget} element wherein the node will be created + */ + private AbstractDNode createOneNode(EObject target, AbstractNodeMapping mapping, DragAndDropTarget parent){ + final AbstractDNodeCandidate abstractDNodeCandidate = new AbstractDNodeCandidate(mapping, target, parent); + return diagramSynchronizer.getElementSynchronizer().createNewNode(diagramMappingsManager, abstractDNodeCandidate, false); + } + +}
diff --git a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/operation/CreateEcoreTools2RepresentationOperation.java b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/operation/CreateEcoreTools2RepresentationOperation.java new file mode 100644 index 0000000..a6fbe3b --- /dev/null +++ b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/operation/CreateEcoreTools2RepresentationOperation.java
@@ -0,0 +1,716 @@ +package org.eclipse.egf.portfolio.genchain.ecoretools.operation; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.SubProgressMonitor; +import org.eclipse.egf.portfolio.genchain.ecoretools.command.CreateEdgeCommand; +import org.eclipse.egf.portfolio.genchain.ecoretools.command.CreateNodeCommand; +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.common.command.CompoundCommand; +import org.eclipse.emf.common.util.BasicEList; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.plugin.EcorePlugin; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.transaction.RecordingCommand; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gmf.runtime.notation.Diagram; +import org.eclipse.sirius.business.api.componentization.ViewpointRegistry; +import org.eclipse.sirius.business.api.dialect.DialectManager; +import org.eclipse.sirius.business.api.dialect.command.CreateRepresentationCommand; +import org.eclipse.sirius.business.api.modelingproject.ModelingProject; +import org.eclipse.sirius.business.api.query.EdgeMappingQuery; +import org.eclipse.sirius.business.api.session.CustomDataConstants; +import org.eclipse.sirius.business.api.session.DefaultLocalSessionCreationOperation; +import org.eclipse.sirius.business.api.session.Session; +import org.eclipse.sirius.business.api.session.SessionCreationOperation; +import org.eclipse.sirius.common.tools.api.util.Option; +import org.eclipse.sirius.diagram.business.api.view.refresh.CanonicalSynchronizer; +import org.eclipse.sirius.diagram.business.api.view.refresh.CanonicalSynchronizerFactory; +import org.eclipse.sirius.diagram.ui.tools.api.layout.LayoutUtils; +import org.eclipse.sirius.ecore.extender.business.api.accessor.ModelAccessor; +import org.eclipse.sirius.table.metamodel.table.DTable; +import org.eclipse.sirius.tools.api.command.semantic.AddSemanticResourceCommand; +import org.eclipse.sirius.ui.business.api.viewpoint.ViewpointSelectionCallback; + +import org.eclipse.sirius.diagram.internal.refresh.SynchronizeGMFModelCommand; +import org.eclipse.sirius.diagram.tools.internal.graphical.edit.DiagramCreationUtil; +import org.eclipse.sirius.ui.business.internal.commands.ChangeViewpointSelectionCommand; + +import org.eclipse.sirius.viewpoint.DDiagram; +import org.eclipse.sirius.viewpoint.DRepresentation; +import org.eclipse.sirius.viewpoint.DSemanticDiagram; +import org.eclipse.sirius.viewpoint.DragAndDropTarget; +import org.eclipse.sirius.viewpoint.description.AbstractNodeMapping; +import org.eclipse.sirius.viewpoint.description.ContainerMapping; +import org.eclipse.sirius.viewpoint.description.DiagramDescription; +import org.eclipse.sirius.viewpoint.description.EdgeMapping; +import org.eclipse.sirius.viewpoint.description.NodeMapping; +import org.eclipse.sirius.viewpoint.description.RepresentationDescription; +import org.eclipse.sirius.viewpoint.description.Viewpoint; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.actions.WorkspaceModifyOperation; + +/** + * This operation allows to : + * - create a Sirius representation file (aird) + * - associate an ecore model to the representation as a semantic resource + * - select a set of viewpoint + * - create diagrams on ecore {@link EPackage} elements + * + * @author Boubekeur Zendagui + */ +@SuppressWarnings("restriction") +public class CreateEcoreTools2RepresentationOperation extends WorkspaceModifyOperation{ + + /** Sirius representation files extension **/ + private final static String _AIRD_FILE_EXTENSION = "aird"; + + /** Viewpoint and diagrams names **/ + protected final static String VIEWPOINT_ECORE_DESIGN = "Design"; + protected final static String REPRESENTATION__ENTITIES_DIAGRAM = "Entities"; + protected final static String REPRESENTATION__DOCUMENTATION_TABLE = "Classes"; + + /** List of all representation names to create**/ + protected Set<Viewpoint> viewpoints = new HashSet<Viewpoint>(); + protected List<RepresentationDescription> representations = new ArrayList<RepresentationDescription>(); + + /** Representation file information **/ + private String representationFileName; + private URI representationFileURI; + private IProject representationProject; + + /** {@link URI} of the ecore model **/ + private URI ecoreModelURI; + + /** + * Default constructor + * @param ecoreURI ecore model URI + * @param fileName name of the representation file. If its value is <code> null <code/>, + * the representation file will have the same name of the ecore model + */ + public CreateEcoreTools2RepresentationOperation(URI ecoreURI, String fileName) { + super(); + // ecoreModelURI value set must be the first operation + this.ecoreModelURI = ecoreURI; + // compute representation informations + initRepresentationFileInformations(fileName); + // Initialize Ecore Tools supported Viewpoint and available representations + initViewpointsList(); + } + + private void initRepresentationFileInformations(String fileName){ + this.representationFileName = getRepresentationFileName(fileName); + this.representationFileURI = getRepresentationUri(fileName); + this.representationProject = getRepresentationProject(fileName); + } + + private boolean isFqnFileName(String fileName){ + if (fileName != null && !fileName.isEmpty() && fileName.contains("/")) + return true; + else + return false; + } + + @Override + protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { + /** Step 1: create representation file and get the session **/ + Session session = createRepresentationFile(monitor); + + /** Step 2: Create diagrams on EPackages**/ + if (session != null) + {// Create diagrams if session was well created in the previous step + DDiagram diagram = createDiagrams(session, monitor); + // Create diagram content + if (diagram != null) + populateEntitiesDiagram(session, diagram); + + // Layout diagram content + arrangeAll(session, diagram); + + // Save session + session.save(Collections.EMPTY_MAP, monitor); + } + } + + /** + * Create all diagrams for ecore {@link EPackage}. + * @param session The {@link Session} opened on the created representation file + * @param monitor {@link IProgressMonitor} + */ + private DDiagram createDiagrams(final Session session, IProgressMonitor monitor){ + DDiagram entitiesDiagram = null; + List<EPackage> ecoreEPackages = getEcoreEPackagesFromSession(session); + for (EPackage iEPackage : ecoreEPackages) + { + Collection<DRepresentation> representations = DialectManager.INSTANCE.getRepresentations(iEPackage, session); + if (representations.isEmpty()) + {// Create all representation + entitiesDiagram = createEntitiesDiagram(iEPackage, session, monitor); + createClassesTable(iEPackage, session, monitor); + } + else + { + // Check no existence of "Entities" and "Classes" representations + List<String> representationDescriptionNames = new ArrayList<String>(); + for (DRepresentation representation : representations) + { + if (representation instanceof DDiagram) + { + final DDiagram dDiagram = (DDiagram) representation; + final RepresentationDescription description = dDiagram.getDescription(); + representationDescriptionNames.add(description.getName()); + if (dDiagram.getOwnedDiagramElements().isEmpty()) + entitiesDiagram = dDiagram; + } + else + { + if (representation instanceof DTable) + { + final RepresentationDescription description = ((DTable) representation).getDescription(); + representationDescriptionNames.add(description.getName()); + } + } + } + + if (! representationDescriptionNames.contains(REPRESENTATION__ENTITIES_DIAGRAM)) + entitiesDiagram = createEntitiesDiagram(iEPackage, session, monitor); + + if (! representationDescriptionNames.contains(REPRESENTATION__DOCUMENTATION_TABLE)) + createClassesTable(iEPackage, session, monitor); + } + } + return entitiesDiagram; + } + + /** + * Allows to arrange all on a given diagram + * @param session uses {@link Session} to edit diagrams + * @param diagram {@link DDiagram} to arrange + */ + private void arrangeAll(final Session session, final DDiagram diagram){ + final DiagramCreationUtil util = new DiagramCreationUtil(diagram); + Diagram associatedGMFDiagram = null; + if (!util.findAssociatedGMFDiagram()) + {// If GMF diagram is not initialized, create it + util.createNewGMFDiagram(); + associatedGMFDiagram = util.getAssociatedGMFDiagram(); + if (associatedGMFDiagram != null) + session.getServices().putCustomData(CustomDataConstants.GMF_DIAGRAMS, diagram, associatedGMFDiagram); + } + else + {// Get the GMF diagram + associatedGMFDiagram = util.getAssociatedGMFDiagram(); + } + + // Synchronize Sirius diagram with GMF diagram + final TransactionalEditingDomain domain = session.getTransactionalEditingDomain(); + if (associatedGMFDiagram != null) + { + final CanonicalSynchronizer canonicalSynchronizer = CanonicalSynchronizerFactory.INSTANCE.createCanonicalSynchronizer(associatedGMFDiagram); + Command gmfNotationModelSynchronizationCmd = new SynchronizeGMFModelCommand(domain, canonicalSynchronizer); + domain.getCommandStack().execute(gmfNotationModelSynchronizationCmd); + } + + final Diagram associatedGMFDiagram_f = associatedGMFDiagram; +// Display.getDefault().syncExec(new Runnable() { +// public void run() { +// Shell shell = new Shell(Display.getDefault()); +// try { +// +// DiagramEditPart diagramEP = OffscreenEditPartFactory.getInstance().createDiagramEditPart(associatedGMFDiagram_f, shell, null); +// +// List<Object> hints = new ArrayList<Object>(2); +// hints.add(LayoutType.DEFAULT); +// hints.add(diagramEP); +// IAdaptable layoutHint = new ObjectAdapter(hints); +// +// @SuppressWarnings("rawtypes") +// List layoutNodes = LayoutService.getInstance().getLayoutNodes(diagramEP, associatedGMFDiagram_f.getChildren()); +// Runnable layoutRun = LayoutService.getInstance().layoutLayoutNodes(layoutNodes, true, layoutHint); +// layoutRun.run(); +// +//// diagramEP.deactivate(); +//// domain.getCommandStack().flush(); +// } +// finally { +//// shell.dispose(); +// } +// } +// }); + + if (associatedGMFDiagram_f != null) + { + final RecordingCommand command = new RecordingCommand(session.getTransactionalEditingDomain()) { + @Override + protected void doExecute() { + LayoutUtils.initializeDiagramLayout(associatedGMFDiagram_f, diagram); + } + }; + + Display.getDefault().syncExec(new Runnable() { + public void run() { + session.getTransactionalEditingDomain().getCommandStack().execute(command); + } + }); + } + } + + /** + * Create diagram content + * @param session used {@link Session} to edit diagrams + * @param diagram {@link DDiagram} to populate with containers, nodes and edges + */ + private void populateEntitiesDiagram(final Session session, final DDiagram diagram){ + List<EPackage> ecoreEPackagesFromSession = getEcoreEPackagesFromSession(session); + for (EPackage ePackage : ecoreEPackagesFromSession) + { + populateNodesAndContainers(session, diagram, ePackage); + populateEdges(session, diagram, ePackage); + } + } + + private void populateEdges(final Session session, final DDiagram diagram, EPackage ePackage){ + /** List of diagram description edges mapping**/ + final DiagramDescription description = diagram.getDescription(); + EList<EdgeMapping> allEdgeMappings = description.getDefaultLayer().getEdgeMappings(); + // Create and execute edge creation commands + TransactionalEditingDomain transactionalEditingDomain = session.getTransactionalEditingDomain(); + for (EdgeMapping edgeMapping : allEdgeMappings) + { + boolean useDomainElement = edgeMapping.isUseDomainElement(); + if (useDomainElement) + { + EdgeMappingQuery edgeMappingQuery = new EdgeMappingQuery(edgeMapping); + Collection<EObject> candidates = edgeMappingQuery.evaluateCandidateExpression((DSemanticDiagram)diagram, session.getInterpreter(), (DragAndDropTarget)diagram); + for (EObject eObject : candidates) + { + CreateEdgeCommand command = new CreateEdgeCommand(session, diagram, edgeMapping, eObject, useDomainElement); + transactionalEditingDomain.getCommandStack().execute(command); + } + } + else + { + for (EObject semantic : ePackage.eContents()) + { + CreateEdgeCommand command = new CreateEdgeCommand(session, diagram, edgeMapping, semantic, useDomainElement); + transactionalEditingDomain.getCommandStack().execute(command); + } + } + } + transactionalEditingDomain.getCommandStack().flush(); + } + + /** + * Create nodes and containers diagram children + * @param session used {@link Session} to edit diagrams + * @param diagram {@link DDiagram} to populate with nodes and containers + * @param ePackage {@link EPackage} + */ + private void populateNodesAndContainers(final Session session, final DDiagram diagram, EPackage ePackage) { + /** List of diagram description node and container mapping**/ + EList<AbstractNodeMapping> abstractNodeMappings = new BasicEList<AbstractNodeMapping>(); + final DiagramDescription description = diagram.getDescription(); + /** Handle description NodeMppings **/ + EList<NodeMapping> nodeMappings = description.getAllNodeMappings(); + if (! nodeMappings.isEmpty()) + abstractNodeMappings.addAll(nodeMappings); + + /** Handle description ContainerMppings **/ + EList<ContainerMapping> containerMappings = description.getAllContainerMappings(); + if (! containerMappings.isEmpty()) + abstractNodeMappings.addAll(containerMappings); + + final ModelAccessor modelAccessor = session.getModelAccessor(); + for (final AbstractNodeMapping abstractNodeMapping : abstractNodeMappings) + { + final String domainClass = abstractNodeMapping.getDomainClass(); + // Handling EPackage content + for (final EObject element : ePackage.eContents()) + { + if (modelAccessor.eInstanceOf(element, domainClass)) + { + CreateNodeCommand command = new CreateNodeCommand(session, diagram, abstractNodeMapping, element); + session.getTransactionalEditingDomain().getCommandStack().execute(command); + } + } + } + } + + /** + * Create a diagram Representation + * @param semantic model element root of the representation to create + * @param session {@link Session} used to create the representation + * @param monitor {@link IProgressMonitor} to trace representation creation + * @return True if the representation is well created, false otherwise + */ + private DDiagram createEntitiesDiagram(final EPackage semantic, Session session, IProgressMonitor monitor){ + final RepresentationDescription entitiesDiagram = getRepresentationDescription(REPRESENTATION__ENTITIES_DIAGRAM); + final String diagramName = semantic.getName() + " entities diagram"; + DRepresentation createRepresentation = createRepresentation(semantic, session, entitiesDiagram, diagramName, monitor); + return (DDiagram) createRepresentation; + } + + /** + * Create a Table representation + * @param semantic model element root of the representation to create + * @param session {@link Session} used to create the representation + * @param monitor {@link IProgressMonitor} to trace representation creation + * @return True if the representation is well created, false otherwise + */ + private DTable createClassesTable(final EPackage semantic, final Session session, IProgressMonitor monitor){ + final RepresentationDescription classesTable = getRepresentationDescription(REPRESENTATION__DOCUMENTATION_TABLE); + final String tableName = semantic.getName() + " documentation"; + DRepresentation createRepresentation = createRepresentation(semantic, session, classesTable, tableName, monitor); + return (DTable) createRepresentation; + } + + /** + * Create one representation for a given semantic element in a given session + * @param semantic model element root of the representation to create + * @param session {@link Session} used to create the representation + * @param description {@link RepresentationDescription} used to create the representation + * @param name representation name + * @param monitor {@link IProgressMonitor} to trace representation creation + * @return the created {@link DRepresentation} + */ + private DRepresentation createRepresentation(final EObject semantic, final Session session, final RepresentationDescription description, + final String name, IProgressMonitor monitor) { + CreateRepresentationCommand createRepresentationCommand = new CreateRepresentationCommand(session, description, semantic, name, monitor); + session.getTransactionalEditingDomain().getCommandStack().execute(createRepresentationCommand); + DRepresentation createdRepresentation = createRepresentationCommand.getCreatedRepresentation(); + return createdRepresentation; + } + + /** + * + * @param representationName the name of sought representation + * @return a {@link RepresentationDescription} or null + */ + private RepresentationDescription getRepresentationDescription(String representationName){ + for (RepresentationDescription representation : representations) + { + if (representation.getName().equals(representationName)) + return representation; + } + return null; + } + + /** + * @return {@link EPackage} available in the ecore resource + */ + + private List<EPackage> getEcoreEPackagesFromSession(Session session){ + final List<EPackage> result = new ArrayList<EPackage>(); + for (Resource resource : session.getSemanticResources()) + { + if (resource.getURI().toString().equals(ecoreModelURI.toString())) + { + EList<EObject> contents = resource.getContents(); + if (contents != null && ! contents.isEmpty()) + { + EObject eObject = contents.get(0); + if (eObject instanceof EPackage) + { + EPackage ePackage = (EPackage) eObject; + result.add(ePackage); + List<EPackage> subPackages = getSubPackages(ePackage); + if (! subPackages.isEmpty()) + { + result.addAll(subPackages); + } + } + } + } + } + + return result; + } + + + /** + * @param parent the parent {@link EPackage} + * @return a {@link List} of sub packages + */ + private List<EPackage> getSubPackages(EPackage parent){ + final List<EPackage> result = new ArrayList<EPackage>(); + + EList<EPackage> eSubpackages = parent.getESubpackages(); + if (eSubpackages != null && ! eSubpackages.isEmpty()) + { + result.addAll(eSubpackages); + for (EPackage ePackage : eSubpackages) + { + List<EPackage> children = getSubPackages(ePackage); + if (! children.isEmpty()) + { + result.addAll(children); + } + } + } + + return result; + } + + /** + * Create the representation file for the ecore + * @param monitor {@link IProgressMonitor} to trace operation + */ + private Session createRepresentationFile(IProgressMonitor monitor){ + monitor.subTask("create the representation model..."); //$NON-NLS-1$ + /** Get the project containing the ecore model**/ + IProject project = this.representationProject; /*getRepresentationProject();*/ + + /** Create the aird file and create a Session **/ + final Session session = createAird(project, representationFileURI, monitor); + + if (session == null) + {// Session is not created + throw new RuntimeException("Can't create a session for " + representationFileURI.toString()); + } + else + {// Session created with success + /** prepare session ressource set for ecore models **/ + session.getTransactionalEditingDomain().getResourceSet() + .getURIConverter().getURIMap() + .putAll(EcorePlugin.computePlatformURIMap()); + } + + // Command to link ecore model to the session + AddSemanticResourceCommand addSemanticResourceCommand = new AddSemanticResourceCommand(session, ecoreModelURI, new SubProgressMonitor(monitor, 1)); + // Command to select Viewpoint in the current session + ChangeViewpointSelectionCommand changeViewpointSelectionCommand = new ChangeViewpointSelectionCommand(session, new ViewpointSelectionCallback(), viewpoints, + Collections.<Viewpoint> emptySet(), new SubProgressMonitor(monitor, 1)); + + // Execute the 2 created commands bellow + CompoundCommand compoundCommand = new CompoundCommand("Link resources to representation"); //$NON-NLS-1$ + compoundCommand.append(addSemanticResourceCommand); + compoundCommand.append(changeViewpointSelectionCommand); + session.getTransactionalEditingDomain().getCommandStack().execute(compoundCommand); + + return session; + } + + /** + * Reworked code from org.eclipse.emf.ecoretools.design.wizard.EcoreModelingProjectCreationOperation.createAird(IProject, URI, IProgressMonitor) + */ + public static Session createAird(IProject project, URI representationsURI, IProgressMonitor monitor) { + Session session = null; + // Get the corresponding modeling project + Option<ModelingProject> modelingProject = ModelingProject.asModelingProject(project); + if (modelingProject.some()) + { // If project is a modeling project, then get it session + session = modelingProject.get().getSession(); + } + else + {// Else, create a new session + SessionCreationOperation sessionCreationOperation = new DefaultLocalSessionCreationOperation(representationsURI, monitor); + try { + sessionCreationOperation.execute(); + session = sessionCreationOperation.getCreatedSession(); + } catch (CoreException e) { + throw new RuntimeException("Can't create session for " + representationsURI, e); + } + } + return session; + } + + /** + * Compute the representation file {@link URI}. This file will be created near of ecore model + * @return the representation file {@link URI} + */ + private URI getRepresentationUri(String fileName){ + String stringRepresentationURI = ""; + + if (isFqnFileName(fileName)) + { + stringRepresentationURI = fileName; + } + else + { + URI ecoreUriWithoutFileExtension = this.ecoreModelURI.trimFileExtension(); + if (ecoreUriWithoutFileExtension != null && ecoreUriWithoutFileExtension.segmentCount() > 1) + { + for (int i = 1; i < ecoreUriWithoutFileExtension.segments().length - 1; i++) + { + stringRepresentationURI += "/" + ecoreUriWithoutFileExtension.segments()[i]; + } + stringRepresentationURI += "/" + this.representationFileName; + } + else + { + throw new RuntimeException("Ecore URI is not valid"); + } + } + + if (stringRepresentationURI.length() > 0) + return URI.createPlatformResourceURI(stringRepresentationURI, true); + else + throw new RuntimeException("Error on creating representation URI"); + + } + + /** + * Check if fileName value is valid. If it is not the case, this method return ecore model file name + ".aird" + * @param fileName representation file name. This parameter accept <code> null <code/> value + * @param ecoreURI {@link URI} of the ecore model + * @return a valid representation file name + */ + private String getRepresentationFileName(String fileName){ + // TODO: implement it + if (fileName == null || (fileName != null && fileName.trim().length() <1 )) + { + URI ecoreUriWithoutFileExtension = this.ecoreModelURI.trimFileExtension(); + if (ecoreUriWithoutFileExtension != null && ecoreUriWithoutFileExtension.segmentCount() > 1) + { + String ecoreModelName = ecoreUriWithoutFileExtension.lastSegment(); + ecoreModelName += "." +_AIRD_FILE_EXTENSION; + return ecoreModelName; + } + else + { + throw new RuntimeException("Ecore file URI is not valid"); + } + } + else + { + boolean fqnFileName = isFqnFileName(fileName); + if (fqnFileName) + { + String[] segments = fileName.split("/"); + String lastSegment = segments[segments.length - 1]; + if (lastSegment.contains(_AIRD_FILE_EXTENSION)) + return lastSegment; + else + return lastSegment + "." +_AIRD_FILE_EXTENSION; + + } + } + return fileName; + } + + + /** + * @return the {@link IProject} containing the ecore model + */ + private IProject getRepresentationProject(String fileName){ + String projectName = null; + List<String> foldersToCreate = new ArrayList<String>(); + + if (isFqnFileName(fileName)) + {/* The file name provided by user is like: /PluginID/folders/filename.aird + * In this case, the project and folder will be created if they are not available */ + String[] segments = fileName.split("/"); + projectName = segments[0]; + // create the list of folders to create + for (int i = 1; i < segments.length - 1; i++) + { + foldersToCreate.add(segments[i]); + } + } + else + {// The file name provided by user is like: filename.aird + // FIXME: Check id we use the well segment + if (ecoreModelURI.isPlatform()) + {// Case of platform URI (Plug-in or Resource URI) + projectName = ecoreModelURI.segment(1); + } + else + {// Case of hierarchical URI. Only URI FQN like are handled. + projectName = ecoreModelURI.segment(0); + } + } + + // Get/create the project from/into the workspace + IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); + NullProgressMonitor NPM = new NullProgressMonitor(); + + try { + if (! project.exists()) + { + project.create(NPM); + } + project.open(NPM); + } catch (CoreException e) { + throw new RuntimeException("Project with name : " + projectName + " can't be localized", e); + } + + // Create folders if needed + if (! foldersToCreate.isEmpty()) + { + IFolder currentFolder = null; + for (String folderName : foldersToCreate) + { + if (currentFolder == null) + {// Case of the first iteration, get the folder from the project + currentFolder = project.getFolder(folderName); + } + else + {// Case of the other iterations, get the folder from it parent folder + currentFolder = currentFolder.getFolder(folderName); + } + + if (! currentFolder.exists()) + { // Create the folder if it is was not created yet. + try { + currentFolder.create(true, true, NPM); + } catch (CoreException e) { + throw new RuntimeException("Can't create folder : " + currentFolder , e); + } + } + } + } + + return project; + } + + /** + * Initialize Viewpoints list + */ + private void initViewpointsList(){ + // Step 1: initialize Viewpoint list + for (Viewpoint viewpoint : ViewpointRegistry.getInstance().getViewpoints()) + { + if (viewpoint.getName().equals(VIEWPOINT_ECORE_DESIGN)) + { + viewpoints.add(viewpoint); + // At this state of work, we handle only Design viewpoint for ecore model + break; + } + } + + // Step 2: initialize Representation list + if (! viewpoints.isEmpty()) + { + for (Viewpoint viewpoint : viewpoints) + { + EList<RepresentationDescription> ownedRepresentations = viewpoint.getOwnedRepresentations(); + if (ownedRepresentations != null && ! ownedRepresentations.isEmpty()) + { + for (RepresentationDescription representationDescription : ownedRepresentations) + { + if (representationDescription.getName().equals(REPRESENTATION__ENTITIES_DIAGRAM) + || representationDescription.getName().equals(REPRESENTATION__DOCUMENTATION_TABLE)) + { + representations.add(representationDescription); + } + } + } + } + } + } +}
diff --git a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/task/EcoreToolsTaskProduction.java b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/task/EcoreToolsTaskProduction.java index 1d44464..7f5f10f 100644 --- a/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/task/EcoreToolsTaskProduction.java +++ b/portfolio/org.eclipse.egf.portfolio.genchain.ecoretools/src/org/eclipse/egf/portfolio/genchain/ecoretools/task/EcoreToolsTaskProduction.java
@@ -14,71 +14,22 @@ */ package org.eclipse.egf.portfolio.genchain.ecoretools.task; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.lang.reflect.InvocationTargetException; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.core.commands.operations.OperationHistoryFactory; -import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.egf.core.producer.InvocationException; import org.eclipse.egf.ftask.producer.context.ITaskProductionContext; import org.eclipse.egf.ftask.producer.invocation.ITaskProduction; +import org.eclipse.egf.portfolio.genchain.ecoretools.operation.CreateEcoreTools2RepresentationOperation; import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.resource.ResourceSet; -import org.eclipse.emf.ecoretools.diagram.edit.parts.EPackageEditPart; -import org.eclipse.emf.ecoretools.diagram.part.EcoreDiagramContentInitializer; -import org.eclipse.emf.ecoretools.diagram.part.EcoreDiagramEditorPlugin; -import org.eclipse.emf.ecoretools.diagram.part.EcoreDiagramEditorUtil; -import org.eclipse.emf.transaction.TransactionalEditingDomain; -import org.eclipse.gmf.runtime.common.core.command.CommandResult; -import org.eclipse.gmf.runtime.diagram.core.services.ViewService; -import org.eclipse.gmf.runtime.diagram.ui.services.layout.LayoutService; -import org.eclipse.gmf.runtime.diagram.ui.services.layout.LayoutType; -import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; -import org.eclipse.gmf.runtime.emf.core.GMFEditingDomainFactory; -import org.eclipse.gmf.runtime.notation.Diagram; -import org.eclipse.gmf.runtime.notation.Node; -import org.eclipse.ui.PlatformUI; +/** + * + * @author Boubekeur Zendagui + */ public class EcoreToolsTaskProduction implements ITaskProduction { - private final class InitializeDiagramCommand extends - AbstractTransactionalCommand { - private final Diagram diagram; - - private InitializeDiagramCommand(TransactionalEditingDomain domain, - String label, List affectedFiles, Diagram diagram) { - super(domain, label, affectedFiles); - this.diagram = diagram; - } - - @Override - protected CommandResult doExecuteWithResult(IProgressMonitor monitor, - IAdaptable info) throws ExecutionException { - EcoreDiagramContentInitializer initializer = new EcoreDiagramContentInitializer(); - - initializer.setInitEPackageContent(false); - initializer.initDiagramContent(diagram); - - if (!diagram.getChildren().isEmpty()) { - List<Node> nodes = new ArrayList<Node>(); - for (Object view : diagram.getChildren()) { - if (view instanceof Node) { - nodes.add((Node) view); - } - } - LayoutService.getInstance().layoutNodes(nodes, true, LayoutType.DEFAULT); - } - return CommandResult.newOKCommandResult(); - } - } - + public void doExecute(ITaskProductionContext productionContext, IProgressMonitor monitor) throws InvocationException { @@ -86,64 +37,15 @@ public void postExecute(ITaskProductionContext productionContext, IProgressMonitor monitor) throws InvocationException { - URI modelUri = productionContext.getInputValue("model", URI.class); - String fileName = productionContext.getInputValue("fileName", - String.class); + URI ecoreUri = productionContext.getInputValue("model", URI.class); + String fileName = productionContext.getInputValue("fileName", String.class); - final TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE - .createEditingDomain(); - ResourceSet resourceSet = editingDomain.getResourceSet(); - - URI diagramModelURI = URI.createPlatformResourceURI(fileName, true); - final Resource diagramResource = resourceSet - .createResource(diagramModelURI); - Resource resource = resourceSet.getResource(modelUri, true); - final EObject modelRoot = (EObject) resource.getContents().get(0); - AbstractTransactionalCommand command = new AbstractTransactionalCommand( - editingDomain, "", Collections.emptyList()) { - - protected CommandResult doExecuteWithResult( - IProgressMonitor monitor, IAdaptable info) - throws ExecutionException { - - Diagram diagram = ViewService.createDiagram(modelRoot, - EPackageEditPart.MODEL_ID, - EcoreDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); - diagramResource.getContents().add(diagram); - return CommandResult.newOKCommandResult(); - } - }; + CreateEcoreTools2RepresentationOperation operation = new CreateEcoreTools2RepresentationOperation(ecoreUri, fileName); try { - OperationHistoryFactory.getOperationHistory().execute(command, - new NullProgressMonitor(), null); - diagramResource.save(EcoreDiagramEditorUtil.getSaveOptions()); - - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { - - public void run() { - EObject diagram = diagramResource.getContents().get(0); - if (diagram instanceof Diagram) { - AbstractTransactionalCommand command = new InitializeDiagramCommand( - editingDomain, "", null, (Diagram) diagram); - - try { - OperationHistoryFactory.getOperationHistory() - .execute(command, - new NullProgressMonitor(), null); - - } catch (ExecutionException e) { - e.printStackTrace(); - } - } - - } - - }); - - diagramResource.save(EcoreDiagramEditorUtil.getSaveOptions()); - } catch (IOException e) { + operation.run(monitor); + } catch (InvocationTargetException e) { e.printStackTrace(); - } catch (ExecutionException e) { + } catch (InterruptedException e) { e.printStackTrace(); }