[DiagramTemplate] Refactor existing custom code

- Add new utils classes (to be redistributed in Papyrus)
- Split DiagramTemplateLauncher into several classes
- Create new creation commands
- Add a List to filter out problematic diagrams

Change-Id: I08735da242eff9ff5c60f7500b0b13cfba160f40
Signed-off-by: Quentin Le Menez <quentin.lemenez@cea.fr>
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/.classpath b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/.classpath
index 240e23b..26e67d6 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/.classpath
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/.classpath
@@ -1,8 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
-	<classpathentry kind="src" path="src-gen"/>
-	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
 	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
-	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+	<classpathentry kind="src" path="src-gen"/>
 	<classpathentry kind="output" path="bin"/>
 </classpath>
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/.settings/org.eclipse.jdt.core.prefs b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/.settings/org.eclipse.jdt.core.prefs
index c585cc4..b3aa6d6 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/.settings/org.eclipse.jdt.core.prefs
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/.settings/org.eclipse.jdt.core.prefs
@@ -1,10 +1,10 @@
 eclipse.preferences.version=1
 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
-org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.compliance=1.8
 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
 org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.5
+org.eclipse.jdt.core.compiler.source=1.8
 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/META-INF/MANIFEST.MF b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/META-INF/MANIFEST.MF
index 15057c5..cc5a39d 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/META-INF/MANIFEST.MF
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/META-INF/MANIFEST.MF
@@ -12,4 +12,4 @@
 Bundle-Activator: org.eclipse.papyrus.diagramtemplate.provider.DiagramTemplateEditPlugin$Implementation
 Bundle-ManifestVersion: 2
 Bundle-SymbolicName: org.eclipse.papyrus.diagramtemplate.edit;singleton:=true
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
+Bundle-RequiredExecutionEnvironment: JavaSE-1.8
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/build.properties b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/build.properties
index 19ebe58..f6298ab 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/build.properties
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.edit/build.properties
@@ -11,6 +11,6 @@
                about.html,\
                build.properties
 jars.compile.order = .
-source.. = src/
+source.. = src-gen/
 output.. = bin/
 src.includes = about.html
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/.classpath b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/.classpath
index 240e23b..50aae14 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/.classpath
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/.classpath
@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
+	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
 	<classpathentry kind="src" path="src-gen"/>
 	<classpathentry kind="src" path="src"/>
-	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
-	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
 	<classpathentry kind="output" path="bin"/>
 </classpath>
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/.settings/org.eclipse.jdt.core.prefs b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/.settings/org.eclipse.jdt.core.prefs
index c585cc4..b3aa6d6 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/.settings/org.eclipse.jdt.core.prefs
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/.settings/org.eclipse.jdt.core.prefs
@@ -1,10 +1,10 @@
 eclipse.preferences.version=1
 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
-org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.compliance=1.8
 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
 org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.5
+org.eclipse.jdt.core.compiler.source=1.8
 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/META-INF/MANIFEST.MF b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/META-INF/MANIFEST.MF
index ce1a061..ebd45bb 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/META-INF/MANIFEST.MF
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/META-INF/MANIFEST.MF
@@ -17,7 +17,14 @@
  org.eclipse.papyrus.infra.gmfdiag.commands;bundle-version="1.2.0",
  org.eclipse.papyrus.infra.gmfdiag.common;bundle-version="[3.0.0,4.0.0)",
  org.eclipse.papyrus.infra.ui;bundle-version="1.2.0",
- org.eclipse.papyrus.infra.core.sashwindows.di;bundle-version="1.2.0"
+ org.eclipse.papyrus.infra.core.sashwindows.di;bundle-version="1.2.0",
+ org.eclipse.papyrus.uml.tools;bundle-version="4.0.0",
+ org.eclipse.papyrus.uml.diagram.menu,
+ org.eclipse.papyrus.uml.diagram.clazz,
+ org.eclipse.papyrus.infra.architecture,
+ org.eclipse.papyrus.infra.viewpoints.policy,
+ org.eclipse.papyrus.infra.architecture.representation,
+ org.eclipse.emf.common
 Export-Package: org.eclipse.papyrus.diagramtemplate.presentation,
  org.eclipse.papyrus.diagramtemplate.launcher,
  org.eclipse.papyrus.diagramtemplate.presentation
@@ -30,4 +37,4 @@
 Bundle-Activator: org.eclipse.papyrus.diagramtemplate.presentation.DiagramTemplateEditorPlugin$Implementation
 Bundle-ManifestVersion: 2
 Bundle-SymbolicName: org.eclipse.papyrus.diagramtemplate.editor;singleton:=true
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
+Bundle-RequiredExecutionEnvironment: JavaSE-1.8
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/build.properties b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/build.properties
index b6cd799..9ae50d1 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/build.properties
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/build.properties
@@ -11,6 +11,7 @@
                plugin.properties,\
                about.html
 jars.compile.order = .
-source.. = src/
+source.. = src/,\
+           src-gen/
 output.. = bin/
 src.includes = about.html
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src-gen/org/eclipse/papyrus/diagramtemplate/presentation/DiagramTemplateEditor.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src-gen/org/eclipse/papyrus/diagramtemplate/presentation/DiagramTemplateEditor.java
index 84171d2..fe85fe7 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src-gen/org/eclipse/papyrus/diagramtemplate/presentation/DiagramTemplateEditor.java
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src-gen/org/eclipse/papyrus/diagramtemplate/presentation/DiagramTemplateEditor.java
@@ -28,6 +28,7 @@
 import org.eclipse.core.resources.IFile;
 import org.eclipse.core.resources.ResourcesPlugin;
 import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
 import org.eclipse.emf.common.command.BasicCommandStack;
 import org.eclipse.emf.common.command.CommandStackListener;
 import org.eclipse.emf.common.util.BasicDiagnostic;
@@ -83,6 +84,7 @@
 import org.eclipse.papyrus.diagramtemplate.SelectionKind;
 import org.eclipse.papyrus.diagramtemplate.SelectionRef;
 import org.eclipse.papyrus.diagramtemplate.Template;
+import org.eclipse.papyrus.diagramtemplate.editor.messages.Messages;
 import org.eclipse.papyrus.diagramtemplate.editor.provider.DiagramDefinitionContentProvider;
 import org.eclipse.papyrus.diagramtemplate.editor.provider.DiagramDefinitionLabelProvider;
 import org.eclipse.papyrus.diagramtemplate.editor.provider.DiagramKindContentProvider;
@@ -94,12 +96,12 @@
 import org.eclipse.papyrus.diagramtemplate.editor.provider.WhatContentProvider;
 import org.eclipse.papyrus.diagramtemplate.launcher.DiagramTemplateLauncher;
 import org.eclipse.papyrus.diagramtemplate.provider.DiagramTemplateItemProviderAdapterFactory;
-import org.eclipse.papyrus.diagramtemplate.utils.Messages;
 import org.eclipse.papyrus.infra.architecture.ArchitectureDomainManager;
 import org.eclipse.papyrus.infra.architecture.representation.PapyrusRepresentationKind;
 import org.eclipse.papyrus.infra.core.architecture.RepresentationKind;
 import org.eclipse.papyrus.infra.core.architecture.merged.MergedArchitectureContext;
 import org.eclipse.papyrus.infra.core.architecture.merged.MergedArchitectureViewpoint;
+import org.eclipse.papyrus.infra.gmfdiag.common.helper.DiagramPrototype;
 import org.eclipse.papyrus.infra.viewpoints.policy.ViewPrototype;
 import org.eclipse.papyrus.uml.diagram.wizards.kind.DiagramKindLabelProvider;
 import org.eclipse.swt.SWT;
@@ -249,7 +251,7 @@
 	/**
 	 * List of diagram categories to consider
 	 */
-	Collection<ViewPrototype> representationsKinds = new ArrayList<ViewPrototype>();
+	Collection<ViewPrototype> representationsKinds = new ArrayList<>();
 
 	/**
 	 * The IFile object corresponding to the model to process
@@ -283,7 +285,7 @@
 	 *
 	 * @generated
 	 */
-	protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>();
+	protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<>();
 
 	/**
 	 * The diagram definition under edition
@@ -405,6 +407,8 @@
 	 */
 	protected void updateUI() {
 		diagramDefinitionTableViewer.refresh();
+		// String diagramKind = ((DiagramDefinition) currentDiagramDefinition.getSelection().get(0).eContainer()).getDiagramKind();
+		// ViewPrototype diagramKind = ViewPrototype.get()
 		forTreeViewer.setInput(currentDiagramDefinition.getSelection());
 		forTreeViewer.refresh();
 		whatTableViewer.refresh();
@@ -423,6 +427,7 @@
 	/**
 	 * Helper method to initialize the diagram categories (kinds)
 	 */
+	// FIXME This should be handled better so as to restrict the creation to available diagrams in the current context
 	protected void initializeDiagramCategories() {
 		ArchitectureDomainManager manager = ArchitectureDomainManager.getInstance();
 		Collection<MergedArchitectureContext> contexts = manager.getVisibleArchitectureContexts();
@@ -463,7 +468,7 @@
 	}
 
 	/**
-	 * Helper method to clear the template of specific information
+	 * Helper method to clear the template of model specific information
 	 */
 	protected void clearTemplate() {
 		TreeIterator<EObject> it = template.eAllContents();
@@ -471,7 +476,9 @@
 			EObject eObject = it.next();
 			if (eObject instanceof DiagramDefinition) {
 				((DiagramDefinition) eObject).setFromRoot(null);
-			} else if (eObject instanceof Selection) {
+			}
+			// This will remove all the model-specific references in the template (i.e. specific rules on an elment)
+			else if (eObject instanceof Selection) {
 				if (((AbstractSelection) eObject).getKind() != SelectionKind.FOR_ALL) {
 					RemoveCommand command = new RemoveCommand(editingDomain, ((Selection) eObject).eContainer(), ((Selection) eObject).eContainer().eClass().getEStructuralFeature("selection"), eObject); //$NON-NLS-1$
 					editingDomain.getCommandStack().execute(command);
@@ -568,6 +575,7 @@
 			/**
 			 * {@inheritDoc}
 			 */
+			@Override
 			public void commandStackChanged(EventObject event) {
 				updateUI();
 				firePropertyChange(IEditorPart.PROP_DIRTY);
@@ -602,7 +610,7 @@
 	public void doSave(IProgressMonitor monitor) {
 		// Save only resources that have actually changed.
 		//
-		final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
+		final Map<Object, Object> saveOptions = new HashMap<>();
 		saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
 
 		// Do the work within an operation because this is a long running activity that modifies the workbench.
@@ -902,6 +910,7 @@
 			/**
 			 * {@inheritDoc}
 			 */
+			@Override
 			public void selectionChanged(SelectionChangedEvent event) {
 				if (event.getSelection() instanceof IStructuredSelection && !event.getSelection().isEmpty()) {
 
@@ -1021,6 +1030,7 @@
 		diagramTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1));
 		diagramCheckboxTableViewer.addCheckStateListener(new ICheckStateListener() {
 
+			@Override
 			public void checkStateChanged(CheckStateChangedEvent event) {
 				Object element = event.getElement();
 				if (element instanceof CreationCommandDescriptor) {
@@ -1030,6 +1040,16 @@
 
 				diagramCheckboxTableViewer.setCheckedElements(new Object[0]);
 				diagramCheckboxTableViewer.setChecked(element, true);
+
+				// FIXME test to see if providing the diagram type manually fixes the creation problem.
+				// There is a problem during definition creation that erases all set kinds on existing definitions
+				if (!(element instanceof DiagramPrototype)) {
+					return;
+				}
+				currentDiagramDefinition.setDiagramKind(((DiagramPrototype) element).getRepresentationKind().getCreationCommandClass());
+				// this hack is used to fix the type of diagram created
+				doSave(new NullProgressMonitor());
+
 			}
 		});
 		diagramCheckboxTableViewer.setContentProvider(new DiagramKindContentProvider());
@@ -1038,10 +1058,12 @@
 
 		diagramCheckboxTableViewer.setCheckStateProvider(new ICheckStateProvider() {
 
+			@Override
 			public boolean isGrayed(Object element) {
 				return false;
 			}
 
+			@Override
 			public boolean isChecked(Object element) {
 				if (currentDiagramDefinition != null) {
 					if (element instanceof CreationCommandDescriptor && currentDiagramDefinition.getDiagramKind() != null) {
@@ -1079,7 +1101,7 @@
 			@Override
 			public void mouseUp(MouseEvent e) {
 
-				List<EObject> listOfTypes = new ArrayList<EObject>();
+				List<EObject> listOfTypes = new ArrayList<>();
 				UMLPackage umlPackage = UMLPackage.eINSTANCE;
 				TreeIterator<EObject> it = umlPackage.eAllContents();
 				while (it.hasNext()) {
@@ -1388,6 +1410,7 @@
 		forTreeViewer.setLabelProvider(new ForLabelProvider());
 		forTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
 
+			@Override
 			public void selectionChanged(SelectionChangedEvent event) {
 				ISelection selection = event.getSelection();
 				if (selection != null && !selection.isEmpty()) {
@@ -1505,7 +1528,7 @@
 
 									Object value = selectionItem.getElement().eGet(eReference);
 
-									List<EObject> valueToShow = new ArrayList<EObject>();
+									List<EObject> valueToShow = new ArrayList<>();
 									if (value instanceof List) {
 										valueToShow.addAll((Collection<? extends EObject>) value);
 									} else if (value instanceof EObject) {
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/Activator.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/Activator.java
new file mode 100755
index 0000000..ec236d4
--- /dev/null
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/Activator.java
@@ -0,0 +1,70 @@
+/*****************************************************************************
+ * Copyright (c) 2018 CEA LIST and others.
+ * 
+ * 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.diagramtemplate.editor;
+
+import org.eclipse.papyrus.infra.core.log.LogHelper;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * @author Quentin Le Menez
+ *
+ */
+public class Activator extends AbstractUIPlugin {
+
+	/**
+	 * The plug-in ID
+	 */
+	public static final String PLUGIN_ID = "org.eclipse.papyrus.diagramtemplate.editor"; //$NON-NLS-1$
+
+	// The shared instance
+	private static Activator plugin;
+
+	/**
+	 * The plug-in's logger
+	 */
+	public static LogHelper log;
+
+	/**
+	 * The constructor
+	 */
+	public Activator() {
+	}
+
+	@Override
+	public void start(BundleContext context) throws Exception {
+		super.start(context);
+		plugin = this;
+		log = new LogHelper(this);
+
+	}
+
+
+	@Override
+	public void stop(BundleContext context) throws Exception {
+		plugin = null;
+		log = null;
+		super.stop(context);
+	}
+
+	/**
+	 * Returns the shared instance
+	 *
+	 * @return the shared instance
+	 */
+	public static Activator getDefault() {
+		return plugin;
+	}
+
+}
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/commands/OpenDiagramsCommand.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/commands/OpenDiagramsCommand.java
new file mode 100755
index 0000000..1d3f587
--- /dev/null
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/commands/OpenDiagramsCommand.java
@@ -0,0 +1,67 @@
+/*****************************************************************************
+ * Copyright (c) 2018 CEA LIST and others.
+ * 
+ * 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.diagramtemplate.editor.commands;
+
+import java.util.Set;
+
+import org.eclipse.core.commands.ExecutionException;
+import org.eclipse.emf.common.command.AbstractCommand;
+import org.eclipse.emf.transaction.RecordingCommand;
+import org.eclipse.emf.transaction.TransactionalEditingDomain;
+import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
+import org.eclipse.gmf.runtime.notation.Diagram;
+import org.eclipse.papyrus.commands.OpenDiagramCommand;
+import org.eclipse.papyrus.infra.emf.gmf.command.GMFtoEMFCommandWrapper;
+
+/**
+ * @author Quentin Le Menez
+ *
+ */
+public class OpenDiagramsCommand extends RecordingCommand {
+
+	// Set<Diagram> diagramsToOpen;
+	Diagram diagramToOpen;
+
+	TransactionalEditingDomain editingDomain;
+
+	/**
+	 * Constructor.
+	 *
+	 * @param domain
+	 * @param label
+	 */
+	// public OpenDiagramsCommand(TransactionalEditingDomain domain, String label, Set<Diagram> diagramsToOpen) {
+	public OpenDiagramsCommand(TransactionalEditingDomain domain, String label, Diagram diagramToOpen) {
+		super(domain, label);
+		// this.diagramsToOpen = diagramsToOpen;
+		this.diagramToOpen = diagramToOpen;
+		this.editingDomain = domain;
+	}
+
+	/**
+	 * @see org.eclipse.emf.transaction.RecordingCommand#doExecute()
+	 *
+	 */
+	@Override
+	protected void doExecute() {
+		// for (Diagram diagram : diagramsToOpen) {
+		// editingDomain.getCommandStack().execute(new GMFtoEMFCommandWrapper(new OpenDiagramCommand(editingDomain, diagram)));
+		AbstractCommand command = new GMFtoEMFCommandWrapper(new OpenDiagramCommand(editingDomain, diagramToOpen));
+		if (command.canExecute()) {
+			command.execute();
+		}
+		// }
+	}
+
+}
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/commands/PopulateDiagramCommand.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/commands/PopulateDiagramCommand.java
new file mode 100755
index 0000000..a3d8543
--- /dev/null
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/commands/PopulateDiagramCommand.java
@@ -0,0 +1,378 @@
+/*****************************************************************************
+ * Copyright (c) 2018 CEA LIST and others.
+ * 
+ * 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.diagramtemplate.editor.commands;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.draw2d.geometry.Point;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.transaction.RecordingCommand;
+import org.eclipse.emf.transaction.TransactionalEditingDomain;
+import org.eclipse.gef.EditPart;
+import org.eclipse.gef.EditPartViewer;
+import org.eclipse.gef.commands.Command;
+import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
+import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
+import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
+import org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest;
+import org.eclipse.gmf.runtime.notation.Diagram;
+import org.eclipse.gmf.runtime.notation.View;
+import org.eclipse.papyrus.diagramtemplate.AbstractSelection;
+import org.eclipse.papyrus.diagramtemplate.SelectionKind;
+import org.eclipse.papyrus.diagramtemplate.SelectionRef;
+import org.eclipse.papyrus.diagramtemplate.utils.CreationReport;
+import org.eclipse.papyrus.diagramtemplate.utils.CreationReport.CreationReportKind;
+import org.eclipse.papyrus.diagramtemplate.utils.ModelUtils;
+import org.eclipse.uml2.uml.Element;
+import org.eclipse.uml2.uml.Relationship;
+
+/**
+ * @author Quentin Le Menez
+ *
+ */
+public class PopulateDiagramCommand extends RecordingCommand {
+
+	/**
+	 * The diagram edit part
+	 */
+	DiagramEditPart diagramEditPart;
+
+	/**
+	 * The selection used for this diagram
+	 */
+	AbstractSelection selection;
+
+	DiagramEditor diagramEditor;
+
+	Diagram pageDiagram;
+
+	/**
+	 * The view of the elements added
+	 */
+	protected List<View> elementProcessed = new ArrayList<>();
+
+	/**
+	 * Constructor.
+	 *
+	 * @param domain
+	 * @param label
+	 */
+	public PopulateDiagramCommand(TransactionalEditingDomain domain, String label, AbstractSelection selection, DiagramEditor diagramEditor) {
+		super(domain, label);
+		this.selection = selection;
+		this.diagramEditor = diagramEditor;
+		this.diagramEditPart = diagramEditor.getDiagramEditPart();
+		this.pageDiagram = diagramEditor.getDiagram();
+	}
+
+	/**
+	 * @see org.eclipse.emf.transaction.RecordingCommand#doExecute()
+	 *
+	 */
+	@Override
+	protected void doExecute() {
+		addElementsFor(selection.getSelectionRef(), pageDiagram.getElement(), diagramEditor, diagramEditPart);
+	}
+
+
+	/**
+	 * Find the element to show depending on a list and try to add them to a specific editPart
+	 *
+	 * @param selectionList
+	 *            The selection list of elements to add to the editPart
+	 * @param root
+	 *            The root to search the elements from
+	 * @param activeEditor
+	 *            the editor corresponding to the editPart
+	 * @param editPartToShowIn
+	 *            the editPart to show elements in
+	 */
+	protected void addElementsFor(List<?> selectionList, EObject root, DiagramEditor activeEditor, EditPart editPartToShowIn) {
+		// Go through the SelectionRef
+		for (Object object : selectionList) {
+			if (!(object instanceof SelectionRef)) {
+				continue;
+			}
+
+			SelectionRef selectionRef = (SelectionRef) object;
+
+			// Retrieve the values
+			Object result = root.eGet((EStructuralFeature) selectionRef.getEReference());
+			List<EObject> resultsToProcess = new ArrayList<>();
+
+			if (result instanceof List) {
+				resultsToProcess.addAll((Collection<? extends EObject>) result);
+			} else {
+				resultsToProcess.add((EObject) result);
+			}
+
+			System.err.println(diagramEditor.getDiagram().getName() + ": " + diagramEditPart);
+
+			if (selectionRef.getKind() == SelectionKind.FOR_ALL) {
+
+				List<EObject> resultsToShow = new ArrayList<>();
+				// Try to match constraints
+				for (EObject elementToMatch : resultsToProcess) {
+					// if (!(ModelUtils.getInstance().matchStereotypedBy(elementToMatch, selectionRef.getStereotypedBy()))) {
+					if (!(ModelUtils.matchStereotypedBy(elementToMatch, selectionRef.getStereotypedBy()))) {
+						continue;
+					}
+
+					if (selectionRef.isSubTypes()) {
+						// Consider all subtypes
+						if (elementToMatch.eClass().getEAllSuperTypes().contains(selectionRef.getElement()) || elementToMatch.eClass() == selectionRef.getElement()) {
+							// It matches
+							resultsToShow.add(elementToMatch);
+						}
+					} else {
+						if (elementToMatch.eClass() == selectionRef.getElement()) {
+							// It matches
+							resultsToShow.add(elementToMatch);
+						}
+					}
+				}
+
+				// Process them all
+				int i = 0;
+				for (EObject elementToShow : resultsToShow) {
+
+					// if (elementToShow instanceof org.eclipse.uml2.uml.Property) {
+					// continue;
+					// }
+					EditPart actualEditPart = showElementIn(elementToShow, activeEditor, editPartToShowIn, i);
+					if (null != actualEditPart) {
+						// actualEditPart.refresh();
+						processRecursively(actualEditPart, elementToShow, selectionRef, activeEditor);
+					}
+					i++;
+				}
+
+			} else {
+				// FIXME Kind of very dirty
+				for (EObject eObject : resultsToProcess) {
+					String eObjectID = eObject.eResource().getURIFragment(eObject);
+					String elementID = selectionRef.getElement().eResource().getURIFragment(selectionRef.getElement());
+					if (eObjectID.equals(elementID)) {
+						EditPart actualEditPart = showElementIn(eObject, activeEditor, editPartToShowIn, 0);
+						// actualEditPart.refresh();
+						processRecursively(actualEditPart, eObject, selectionRef, activeEditor);
+					}
+				}
+			}
+		}
+	}
+
+
+	/**
+	 * Used to recursively process the template definition. It identifies the newly created editpart and recurses on it
+	 *
+	 * @param actualEditPart
+	 *            the editpart elements was added to. It is used to find the newly created editpart
+	 * @param elementToShow
+	 *            the semantic element added
+	 * @param selectionRef
+	 *            the corresponding selectionRed
+	 * @param activeEditor
+	 *            the editor used
+	 */
+	protected void processRecursively(EditPart actualEditPart, EObject elementToShow,
+			SelectionRef selectionRef, DiagramEditor activeEditor) {
+
+		// Refresh the editPart of the newly added element
+		actualEditPart.refresh();
+
+		// Guess which of the View is the new one
+		EditPartViewer viewer = actualEditPart.getViewer();
+		Map<?, ?> map = viewer.getEditPartRegistry();
+
+		// We must have a copy since map may change during the loop
+		Map<?, ?> mapCopy = new HashMap<>(map);
+		Iterator<?> it = mapCopy.keySet().iterator();
+		boolean found = false;
+		while (it.hasNext() && !found) {
+			Object view = it.next();
+
+			Object value = mapCopy.get(view);
+			if (!(value instanceof GraphicalEditPart)) {
+				continue;
+			}
+			GraphicalEditPart editPart = (GraphicalEditPart) value;
+
+			// The element of the editPart and the element we just added must match
+			String editPartSemanticElementID = editPart.resolveSemanticElement().eResource().getURIFragment(editPart.resolveSemanticElement());
+			String elementToShowID = elementToShow.eResource().getURIFragment(elementToShow);
+			if (!(editPartSemanticElementID.equals(elementToShowID))) {
+				continue;
+			}
+
+			// The view should be the editpart whose parent's element is not the elementToShow
+			boolean foundParentWithElementToShowAsElement = false;
+
+			EditPart elementToProcess = editPart.getParent();
+			while (elementToProcess != null && !foundParentWithElementToShowAsElement) {
+				if (elementToProcess instanceof GraphicalEditPart) {
+					String elementToProcessSemanticElementID = ((GraphicalEditPart) elementToProcess).resolveSemanticElement().eResource().getURIFragment(((GraphicalEditPart) elementToProcess).resolveSemanticElement());
+					if (elementToProcessSemanticElementID.equals(elementToShowID)) {
+						foundParentWithElementToShowAsElement = true;
+						continue;
+					}
+				}
+
+				elementToProcess = elementToProcess.getParent();
+			}
+
+			if (!foundParentWithElementToShowAsElement) {
+				// Last we must be sure that it is really new one
+				if (!elementProcessed.contains(view)) {
+					// We can process it
+					addElementsFor(selectionRef.getSelectionRef(), elementToShow, activeEditor, editPart);
+
+					// FIXME we may need to add all new elements as processed
+					// Record that it is processed
+					elementProcessed.add((View) view);
+
+					found = true;
+				}
+			}
+		}
+	}
+
+	/**
+	 * Try to show an element in an editPart (or its children)
+	 *
+	 * @param elementToShow
+	 *            the element to show
+	 * @param activeEditor
+	 *            the editor corresponding to the editPart
+	 * @param editPart
+	 *            the editPart to show the element in
+	 * @param position
+	 *            position is used to try to distribute the drop
+	 * @return
+	 * 		the editPart in which the element has been actually added
+	 */
+	protected EditPart showElementIn(EObject elementToShow, DiagramEditor activeEditor, EditPart editPart, int position) {
+
+
+		EditPart returnEditPart = null;
+
+		if (elementToShow instanceof Element) {
+
+			System.out.println(elementToShow);
+			// We can't drop associations without the existing ends
+			// FIXME This may be fixable if the existing drop strategies implemented in Papyrus are used
+			if (elementToShow instanceof Relationship) {
+				boolean hasEnds = true;
+				List<EObject> test = new ArrayList<>();
+				for (Object view : activeEditor.getDiagram().getChildren()) {
+					EObject element = ((View) view).getElement();
+					test.add(element);
+				}
+				for (Iterator<?> requiredEnds = ((Relationship) elementToShow).getRelatedElements().iterator(); requiredEnds.hasNext();) {
+					Element end = (Element) requiredEnds.next();
+					if (!(test.contains(end))) {
+						hasEnds = false;
+					}
+					;
+				}
+
+				if (!hasEnds) {
+					// we lack the ends to drop the relationship
+					return returnEditPart;
+				}
+
+				// The editParts need to be refreshed in order to be able to drop connections
+				// org.eclipse.papyrus.infra.gmfdiag.common.commands.CommonDeferredCreateConnectionViewCommand.doExecuteWithResult
+				// editPart.refresh(); // May not be necessary anymore as we refresh the created elements one by one when we look for recursive creation
+			}
+
+			DropObjectsRequest dropObjectsRequest = new DropObjectsRequest();
+			ArrayList<Element> list = new ArrayList<>();
+			list.add((Element) elementToShow);
+			dropObjectsRequest.setObjects(list);
+			dropObjectsRequest.setLocation(new Point(20, 100 * position));
+			Command commandDrop = editPart.getCommand(dropObjectsRequest);
+
+			boolean processChildren = false;
+			if (commandDrop == null) {
+				processChildren = true;
+			} else {
+				if (commandDrop.canExecute()) {
+					activeEditor.getDiagramEditDomain().getDiagramCommandStack().execute(commandDrop);
+					returnEditPart = editPart;
+					CreationReport.getInstance().addToReport(elementToShow, CreationReportKind.SUCCESS);
+				} else {
+					processChildren = true;
+				}
+			}
+
+			if (processChildren) {
+				// If the element is intended to be dropped inside a specific compartment/container
+				// try to add to one of its children
+				boolean found = false;
+
+				ArrayList<EditPart> childrenList = new ArrayList<>();
+				findAllChildren(childrenList, editPart);
+				for (Object child : childrenList) {
+					if (child instanceof EditPart) {
+						Command commandDropChild = ((EditPart) child).getCommand(dropObjectsRequest);
+						if (commandDropChild != null) {
+							if (commandDropChild.canExecute()) {
+								activeEditor.getDiagramEditDomain().getDiagramCommandStack().execute(commandDropChild);
+								found = true;
+								returnEditPart = (EditPart) child;
+								CreationReport.getInstance().addToReport(elementToShow, CreationReportKind.SUCCESS);
+								break;
+							}
+						}
+					}
+				}
+				if (!found) {
+					CreationReport.getInstance().addToReport(elementToShow, CreationReportKind.FAIL);
+					returnEditPart = editPart;
+				}
+			}
+		}
+
+		return returnEditPart;
+	}
+
+
+
+
+	/**
+	 * Util method used to find all the children of a certain editpart
+	 *
+	 * @param list
+	 *            the children found recursively
+	 * @param root
+	 *            the root editpart to start the search from
+	 */
+	public static void findAllChildren(List<EditPart> list, EditPart root) {
+		list.addAll(root.getChildren());
+		for (Object editPart : root.getChildren()) {
+			if (editPart instanceof EditPart) {
+				findAllChildren(list, (EditPart) editPart);
+			}
+		}
+	}
+
+
+}
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/Messages.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/messages/Messages.java
similarity index 96%
rename from diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/Messages.java
rename to diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/messages/Messages.java
index a2e47d5..90f3993 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/Messages.java
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/messages/Messages.java
@@ -10,13 +10,13 @@
  *   Florian Noyrit florian.noyrit@cea.fr - Initial API and implementation
  *
  *****************************************************************************/
-package org.eclipse.papyrus.diagramtemplate.utils;
+package org.eclipse.papyrus.diagramtemplate.editor.messages;
 
 import org.eclipse.osgi.util.NLS;
 
 public class Messages extends NLS {
 
-	private static final String BUNDLE_NAME = "org.eclipse.papyrus.diagramtemplate.utils.messages"; //$NON-NLS-1$
+	private static final String BUNDLE_NAME = "org.eclipse.papyrus.diagramtemplate.editor.messages.messages"; //$NON-NLS-1$
 
 	public static String DiagramTemplateEditor_0;
 
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/messages.properties b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/messages/messages.properties
similarity index 100%
rename from diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/messages.properties
rename to diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/messages/messages.properties
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/provider/DiagramKindContentProvider.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/provider/DiagramKindContentProvider.java
index 000b46f..4ec866a 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/provider/DiagramKindContentProvider.java
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/editor/provider/DiagramKindContentProvider.java
@@ -13,6 +13,7 @@
 package org.eclipse.papyrus.diagramtemplate.editor.provider;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 
 import org.eclipse.jface.viewers.IStructuredContentProvider;
@@ -29,10 +30,14 @@
  */
 public class DiagramKindContentProvider implements IStructuredContentProvider {
 
+	private static List<String> allowedDiagrams = Arrays.asList("org.eclipse.papyrus.uml.diagram.clazz.CreateClassDiagramCommand");
+
+
 	/**
 	 * @see org.eclipse.jface.viewers.IContentProvider#dispose()
 	 *
 	 */
+	@Override
 	public void dispose() {
 	}
 
@@ -43,6 +48,7 @@
 	 * @param oldInput
 	 * @param newInput
 	 */
+	@Override
 	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
 	}
 
@@ -51,12 +57,19 @@
 	 *
 	 * @param inputElement
 	 */
+	@Override
 	public Object[] getElements(Object inputElement) {
 		if (inputElement instanceof List) {
 			List<ViewPrototype> categories = (List<ViewPrototype>) inputElement;
 
-			List<ViewPrototype> result = new ArrayList<ViewPrototype>();
+			List<ViewPrototype> result = new ArrayList<>();
 			for (CreationCommandDescriptor desc : getCreationCommandRegistry().getCommandDescriptors()) {
+				// FIXME This is used to filter out problematic diagrams
+				// This will of course need to be remedied when all the available diagrams are working again
+				if (!allowedDiagrams.contains(desc.getCommandId())) {
+					continue;
+				}
+
 				for (ViewPrototype category : categories) {
 					if (category.getLabel().equalsIgnoreCase(desc.getLabel())) {
 						result.add(category);
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/launcher/DiagramTemplateLauncher.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/launcher/DiagramTemplateLauncher.java
index 5cf8ed9..bcf201f 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/launcher/DiagramTemplateLauncher.java
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/launcher/DiagramTemplateLauncher.java
@@ -12,37 +12,20 @@
  *****************************************************************************/
 package org.eclipse.papyrus.diagramtemplate.launcher;
 
-import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
-import java.util.Map;
 
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.draw2d.geometry.Point;
 import org.eclipse.emf.common.util.TreeIterator;
 import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature;
+import org.eclipse.emf.ecore.resource.Resource;
 import org.eclipse.emf.transaction.RecordingCommand;
 import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.EditPartViewer;
 import org.eclipse.gef.GraphicalViewer;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
 import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
-import org.eclipse.gmf.runtime.diagram.ui.requests.ArrangeRequest;
-import org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants;
 import org.eclipse.gmf.runtime.notation.Diagram;
-import org.eclipse.gmf.runtime.notation.View;
 import org.eclipse.jface.dialogs.MessageDialog;
 import org.eclipse.papyrus.commands.CreationCommandDescriptor;
 import org.eclipse.papyrus.commands.CreationCommandRegistry;
@@ -51,32 +34,27 @@
 import org.eclipse.papyrus.diagramtemplate.DiagramDefinition;
 import org.eclipse.papyrus.diagramtemplate.Selection;
 import org.eclipse.papyrus.diagramtemplate.SelectionKind;
-import org.eclipse.papyrus.diagramtemplate.SelectionRef;
 import org.eclipse.papyrus.diagramtemplate.Template;
-import org.eclipse.papyrus.diagramtemplate.utils.Messages;
-import org.eclipse.papyrus.editor.PapyrusMultiDiagramEditor;
-import org.eclipse.papyrus.infra.architecture.ArchitectureDomainManager;
-import org.eclipse.papyrus.infra.architecture.representation.PapyrusRepresentationKind;
-import org.eclipse.papyrus.infra.core.architecture.RepresentationKind;
-import org.eclipse.papyrus.infra.core.architecture.merged.MergedArchitectureContext;
-import org.eclipse.papyrus.infra.core.architecture.merged.MergedArchitectureViewpoint;
+import org.eclipse.papyrus.diagramtemplate.editor.Activator;
+import org.eclipse.papyrus.diagramtemplate.editor.commands.OpenDiagramsCommand;
+import org.eclipse.papyrus.diagramtemplate.editor.commands.PopulateDiagramCommand;
+import org.eclipse.papyrus.diagramtemplate.editor.messages.Messages;
+import org.eclipse.papyrus.diagramtemplate.utils.CreationReport;
+import org.eclipse.papyrus.diagramtemplate.utils.CreationReport.CreationReportKind;
+import org.eclipse.papyrus.diagramtemplate.utils.DiagramUtils;
+import org.eclipse.papyrus.diagramtemplate.utils.FindSelectionInModel;
+import org.eclipse.papyrus.diagramtemplate.utils.ModelSetUtils;
+import org.eclipse.papyrus.diagramtemplate.utils.ModelUtils;
 import org.eclipse.papyrus.infra.core.editor.BackboneException;
-import org.eclipse.papyrus.infra.core.resource.ModelMultiException;
 import org.eclipse.papyrus.infra.core.resource.ModelSet;
 import org.eclipse.papyrus.infra.core.sashwindows.di.service.IPageManager;
-import org.eclipse.papyrus.infra.core.services.ExtensionServicesRegistry;
 import org.eclipse.papyrus.infra.core.services.ServiceException;
 import org.eclipse.papyrus.infra.core.services.ServicesRegistry;
-import org.eclipse.papyrus.infra.core.utils.DiResourceSet;
 import org.eclipse.papyrus.infra.gmfdiag.common.model.NotationUtils;
 import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
 import org.eclipse.papyrus.infra.viewpoints.policy.ViewPrototype;
 import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
 import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.uml2.uml.Element;
 import org.eclipse.uml2.uml.NamedElement;
 
 
@@ -93,32 +71,24 @@
 	private static DiagramTemplateLauncher instance = null;
 
 	/**
-	 * Enum used to report on diagram creation
-	 *
-	 */
-	public enum CreationReportKind {
-		SUCCESS, FAIL
-	}
-
-	/**
 	 * The creation report information
 	 */
-	protected HashMap<EObject, CreationReportKind> creationReport;
+	// protected HashMap<EObject, CreationReportKind> creationReport;
 
 	/**
 	 * The diagram added in the first part of the execution
 	 */
-	protected HashMap<String, AbstractSelection> diagramsCreated;
+	protected HashMap<Diagram, AbstractSelection> createdDiagrams;
 
 	/**
-	 * The view of the elements added
+	 * The Handled ModelSet
 	 */
-	protected List<View> elementProcessed = new ArrayList<View>();
+	protected ModelSet modelSet;
 
 	/**
 	 * Used to store the list of diagrams already present in the resource
 	 */
-	protected List<String> diagramsInResource;
+	protected List<Diagram> existingDiagrams;
 
 	/**
 	 * Constructor.
@@ -140,30 +110,6 @@
 		return instance;
 	}
 
-	/**
-	 * List of diagram categories to consider
-	 */
-	protected List<ViewPrototype> representationsKinds;
-
-	protected void initializeDiagramCategories(ModelSet modelSet) {
-		representationsKinds = new ArrayList<ViewPrototype>();
-
-		ArchitectureDomainManager manager = ArchitectureDomainManager.getInstance();
-		Collection<MergedArchitectureContext> contexts = manager.getVisibleArchitectureContexts();
-
-		for (MergedArchitectureContext mergedArchitectureContext : contexts) {
-			Collection<MergedArchitectureViewpoint> viewpoints = mergedArchitectureContext.getViewpoints();
-
-			for (MergedArchitectureViewpoint mergedArchitectureViewpoint : viewpoints) {
-				Collection<RepresentationKind> representations = mergedArchitectureViewpoint.getRepresentationKinds();
-				for (RepresentationKind representationKind : representations) {
-					if (representationKind instanceof PapyrusRepresentationKind) {
-						representationsKinds.add(ViewPrototype.get((PapyrusRepresentationKind) representationKind));
-					}
-				}
-			}
-		}
-	}
 
 	/**
 	 * Gets the creation command registry.
@@ -178,7 +124,7 @@
 		if (inputElement instanceof List) {
 			List<ViewPrototype> categories = (List<ViewPrototype>) inputElement;
 
-			List<CreationCommandDescriptor> result = new ArrayList<CreationCommandDescriptor>();
+			List<CreationCommandDescriptor> result = new ArrayList<>();
 			for (CreationCommandDescriptor desc : getCreationCommandRegistry().getCommandDescriptors()) {
 				for (ViewPrototype category : categories) {
 					if (category.getLabel().equalsIgnoreCase(desc.getLabel())) {
@@ -202,7 +148,8 @@
 	 * 		the corresponding CreationCommandDescriptor
 	 */
 	protected CreationCommandDescriptor getCreation(String commandID) {
-		List<Object> diagramsKindlist = Arrays.asList(getCommands(representationsKinds));
+		// List<Object> diagramsKindlist = Arrays.asList(getCommands(ModelSetUtils.getInstance().getRepresentationKinds()));
+		List<Object> diagramsKindlist = Arrays.asList(getCommands(ModelSetUtils.getRepresentationKinds()));
 
 		for (Object object : diagramsKindlist) {
 			CreationCommandDescriptor command = (CreationCommandDescriptor) object;
@@ -215,273 +162,8 @@
 		return null;
 	}
 
-	/**
-	 * Used to recursively process the template definition. It identifies the newly create editpart and recurses on it
-	 *
-	 * @param actualEditPart
-	 *            the editpart elements was added to. It is used to find the newly create editpart
-	 * @param elementToShow
-	 *            the semantic element added
-	 * @param selectionRef
-	 *            the corresponding selectionRed
-	 * @param activeEditor
-	 *            the editor used
-	 */
-	protected void processRecursively(EditPart actualEditPart, EObject elementToShow, SelectionRef selectionRef, DiagramEditor activeEditor) {
-
-		// Guess which of the View is the new one
-		EditPartViewer viewer = actualEditPart.getViewer();
-		Map<?, ?> map = viewer.getEditPartRegistry();
-
-		// We must have a copy since map may change during the loop
-		Map<?, ?> mapCopy = new HashMap<Object, Object>(map);
-		Iterator<?> it = mapCopy.keySet().iterator();
-		boolean found = false;
-		while (it.hasNext() && !found) {
-			Object view = it.next();
-
-			Object value = mapCopy.get(view);
-			if (value instanceof GraphicalEditPart) {
 
 
-				GraphicalEditPart editPart = (GraphicalEditPart) value;
-
-
-				// The element of the editPart and the element we just added must match
-				String editPartSemanticElementID = editPart.resolveSemanticElement().eResource().getURIFragment(editPart.resolveSemanticElement());
-				String elementToShowID = elementToShow.eResource().getURIFragment(elementToShow);
-				if (editPartSemanticElementID.equals(elementToShowID)) {
-
-					// The view should be the editpart whose parent's element is not the elementToShow
-					boolean foundParentWithElementToShowAsElement = false;
-
-					EditPart elementToProcess = editPart.getParent();
-					while (elementToProcess != null && !foundParentWithElementToShowAsElement) {
-
-						if (elementToProcess instanceof GraphicalEditPart) {
-							String elementToProcessSemanticElementID = ((GraphicalEditPart) elementToProcess).resolveSemanticElement().eResource().getURIFragment(((GraphicalEditPart) elementToProcess).resolveSemanticElement());
-							if (elementToProcessSemanticElementID.equals(elementToShowID)) {
-								foundParentWithElementToShowAsElement = true;
-							}
-						}
-
-						elementToProcess = elementToProcess.getParent();
-					}
-
-					if (!foundParentWithElementToShowAsElement) {
-						// Last we must be sure that it is really new one
-						if (!elementProcessed.contains(view)) {
-							// We can process it
-							addElementsFor(selectionRef.getSelectionRef(), elementToShow, activeEditor, editPart);
-
-							// FIXME we may need to add all new elements as processed
-							// Record that it is processed
-							elementProcessed.add((View) view);
-
-							found = true;
-						}
-					}
-				}
-			}
-		}
-	}
-
-	/**
-	 * Find the element to show depending on a list and try to add them to a specific editPart
-	 *
-	 * @param selectionList
-	 *            The selection list of elements to add to the editPart
-	 * @param root
-	 *            The root to search the elements from
-	 * @param activeEditor
-	 *            the editor corresponding to the editPart
-	 * @param editPartToShowIn
-	 *            the editPart to show elements in
-	 */
-	protected void addElementsFor(List<?> selectionList, EObject root, DiagramEditor activeEditor, EditPart editPartToShowIn) {
-		// Go through the SelectionRef
-		for (Object object : selectionList) {
-			if (object instanceof SelectionRef) {
-				SelectionRef selectionRef = (SelectionRef) object;
-
-				// Retrieve the values
-				Object result = root.eGet((EStructuralFeature) selectionRef.getEReference());
-				List<EObject> resultsToProcess = new ArrayList<EObject>();
-
-				if (result instanceof List) {
-					resultsToProcess.addAll((Collection<? extends EObject>) result);
-				} else {
-					resultsToProcess.add((EObject) result);
-				}
-
-				if (selectionRef.getKind() == SelectionKind.FOR_ALL) {
-
-
-					List<EObject> resultsToShow = new ArrayList<EObject>();
-					// Try to match constraints
-					for (EObject elementToMatch : resultsToProcess) {
-						if (matchStereotypedBy(elementToMatch, selectionRef.getStereotypedBy())) {
-							if (selectionRef.isSubTypes()) {
-								// Consider all subtypes
-								if (elementToMatch.eClass().getEAllSuperTypes().contains(selectionRef.getElement()) || elementToMatch.eClass() == selectionRef.getElement()) {
-									// It matches
-									resultsToShow.add(elementToMatch);
-								}
-							} else {
-								if (elementToMatch.eClass() == selectionRef.getElement()) {
-									// It matches
-									resultsToShow.add(elementToMatch);
-								}
-							}
-						}
-					}
-
-					// Process them all
-					int i = 0;
-					for (EObject elementToShow : resultsToShow) {
-
-						EditPart actualEditPart = showElementIn(elementToShow, activeEditor, editPartToShowIn, i);
-						processRecursively(actualEditPart, elementToShow, selectionRef, activeEditor);
-						i++;
-					}
-
-				} else {
-					// FIXME Kind of very dirty
-					for (EObject eObject : resultsToProcess) {
-						String eObjectID = eObject.eResource().getURIFragment(eObject);
-						String elementID = selectionRef.getElement().eResource().getURIFragment(selectionRef.getElement());
-						if (eObjectID.equals(elementID)) {
-							// if(eObject == selectionRef.getElement()) {
-							EditPart actualEditPart = showElementIn(eObject, activeEditor, editPartToShowIn, 0);
-							processRecursively(actualEditPart, eObject, selectionRef, activeEditor);
-						}
-					}
-				}
-			}
-		}
-	}
-
-	/**
-	 * Util method used to find all the children of a certain editpart
-	 *
-	 * @param list
-	 *            the children found recursively
-	 * @param root
-	 *            the root editpart to start the search from
-	 */
-	protected void findAllChildren(List<EditPart> list, EditPart root) {
-		list.addAll(root.getChildren());
-		for (Object editPart : root.getChildren()) {
-			if (editPart instanceof EditPart) {
-				findAllChildren(list, (EditPart) editPart);
-			}
-		}
-	}
-
-	/**
-	 * Try to show an element in an editPart (or its children)
-	 *
-	 * @param elementToShow
-	 *            the element to show
-	 * @param activeEditor
-	 *            the editor corresponding to the editPart
-	 * @param editPart
-	 *            the editPart to show the element in
-	 * @param position
-	 *            position is used to try to distribute the drop
-	 * @return
-	 * 		the editPart in which the element has been actually added
-	 */
-	protected EditPart showElementIn(EObject elementToShow, DiagramEditor activeEditor, EditPart editPart, int position) {
-
-
-		EditPart returnEditPart = null;
-
-		if (elementToShow instanceof Element) {
-
-			DropObjectsRequest dropObjectsRequest = new DropObjectsRequest();
-			ArrayList<Element> list = new ArrayList<Element>();
-			list.add((Element) elementToShow);
-			dropObjectsRequest.setObjects(list);
-			dropObjectsRequest.setLocation(new Point(20, 100 * position));
-			Command commandDrop = editPart.getCommand(dropObjectsRequest);
-
-			boolean processChildren = false;
-			if (commandDrop == null) {
-				processChildren = true;
-			} else {
-				if (commandDrop.canExecute()) {
-					activeEditor.getDiagramEditDomain().getDiagramCommandStack().execute(commandDrop);
-					returnEditPart = editPart;
-					creationReport.put(elementToShow, CreationReportKind.SUCCESS);
-				} else {
-					processChildren = true;
-				}
-			}
-
-			if (processChildren) {
-				// try to add to one of its children
-				boolean found = false;
-
-				ArrayList<EditPart> childrenList = new ArrayList<EditPart>();
-				findAllChildren(childrenList, editPart);
-				for (Object child : childrenList) {
-					if (child instanceof EditPart) {
-						Command commandDropChild = ((EditPart) child).getCommand(dropObjectsRequest);
-						if (commandDropChild != null) {
-							if (commandDropChild.canExecute()) {
-								activeEditor.getDiagramEditDomain().getDiagramCommandStack().execute(commandDropChild);
-								found = true;
-								returnEditPart = (EditPart) child;
-								creationReport.put(elementToShow, CreationReportKind.SUCCESS);
-								break;
-							}
-						}
-					}
-				}
-				if (!found) {
-					creationReport.put(elementToShow, CreationReportKind.FAIL);
-					returnEditPart = editPart;
-				}
-			}
-		}
-
-		return returnEditPart;
-	}
-
-	/**
-	 * Utils method that determine whether an element is stereotypedBy a certain stereotype qualiedName
-	 *
-	 * @param element
-	 *            the element to test
-	 * @param stereotypedBy
-	 *            the qulifiedName of the stereotype to match
-	 * @return
-	 * 		true if matches false else.
-	 */
-	protected boolean matchStereotypedBy(EObject element, String stereotypedBy) {
-		if (element instanceof Element) {
-			// Read stereotypedBy
-			stereotypedBy = stereotypedBy.replaceAll(" ", ""); //$NON-NLS-1$ //$NON-NLS-2$
-			String[] stereotypes = stereotypedBy.split(","); //$NON-NLS-1$
-
-			boolean matchStereotypes = true;
-			for (String stereo : stereotypes) {
-				if (stereo != null && stereo.length() > 0) {
-					if (((Element) element).getAppliedStereotype(stereo) != null) {
-						matchStereotypes = true;
-					} else {
-						matchStereotypes = false;
-						break;
-					}
-				}
-			}
-
-			return matchStereotypes;
-		}
-
-		return false;
-	}
 
 	/**
 	 * Creates the diagrams in a specified Papyrus resource
@@ -497,173 +179,178 @@
 		// Go through the selection and try to find elements in the target model that match
 		for (Object object : selectionList) {
 
-			if (object instanceof AbstractSelection) {
-				AbstractSelection selection = (AbstractSelection) object;
-				CreationCommandDescriptor creationCommandDescriptor = getCreation(diagramDefinition.getDiagramKind());
-				if (creationCommandDescriptor != null) {
+			if (!(object instanceof AbstractSelection)) {
+				continue;
+			}
 
+			AbstractSelection selection = (AbstractSelection) object;
+			CreationCommandDescriptor creationCommandDescriptor = getCreation(diagramDefinition.getDiagramKind());
+			if (null == creationCommandDescriptor) {
+				return;
+			}
 
-					EObject root;
+			EObject root;
+			// If the template is under specified, try to guess
+			if (null == diagramDefinition.getFromRoot()) {
+				root = ((Template) diagramDefinition.eContainer()).getTargetRoot();
+			} else {
+				root = diagramDefinition.getFromRoot();
+			}
 
-					// If the template is under specified, try to guess
-					if (diagramDefinition.getFromRoot() == null) {
-						root = ((Template) diagramDefinition.eContainer()).getTargetRoot();
+			if (null == root) {
+				return;
+			}
+
+			if (selection.getKind() == SelectionKind.FOR_ALL) {
+
+				// Find elements that match
+				List<EObject> content = new ArrayList<>();
+				if (selection instanceof Selection) {
+					if (((Selection) selection).isRecursively()) {
+						// Go through all recursively
+						// FIXME This will go through the dummy/reference ModelSet inside the template
+						// As this ModelSet is not initialized the graphical executions will fail
+						// This reference needs to be changed and point directly to the original ModelSet
+						TreeIterator<EObject> it = root.eAllContents();
+						while (it.hasNext()) {
+							// EObject eObject = it.next();
+							// EObject eObject = FindSelectionInModel.getInstance().findSelectionInModel(modelSet, it.next());
+							EObject eObject = FindSelectionInModel.findSelectionInModel(modelSet, it.next());
+							content.add(eObject);
+						}
 					} else {
-						root = diagramDefinition.getFromRoot();
+						// content.addAll(root.eContents());
+						for (Iterator<EObject> it = root.eContents().iterator(); it.hasNext();) {
+							// EObject eObject = FindSelectionInModel.getInstance().findSelectionInModel(modelSet, it.next());
+							EObject eObject = FindSelectionInModel.findSelectionInModel(modelSet, it.next());
+							content.add(eObject);
+						}
+					}
+					// content.add(root);
+					// EObject eObject = FindSelectionInModel.getInstance().findSelectionInModel(modelSet, root);
+					EObject eObject = FindSelectionInModel.findSelectionInModel(modelSet, root);
+					content.add(eObject);
+				} else {
+					MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), Messages.DiagramTemplateLauncher_3, Messages.DiagramTemplateLauncher_4);
+				}
+
+
+				for (EObject eObject : content) {
+					// if (!(ModelUtils.getInstance().matchStereotypedBy(eObject, selection.getStereotypedBy()))) {
+					if (!(ModelUtils.matchStereotypedBy(eObject, selection.getStereotypedBy()))) {
+						continue;
 					}
 
-					if (root != null) {
-						if (selection.getKind() == SelectionKind.FOR_ALL) {
-
-							// Find elements that match
-							List<EObject> content = new ArrayList<EObject>();
-							if (selection instanceof Selection) {
-								if (((Selection) selection).isRecursively()) {
-									// Go through all recursively
-									TreeIterator<EObject> it = root.eAllContents();
-									while (it.hasNext()) {
-										EObject eObject = it.next();
-										content.add(eObject);
-									}
-								} else {
-									content.addAll(root.eContents());
-								}
-								content.add(root);
-							} else {
-								MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), Messages.DiagramTemplateLauncher_3, Messages.DiagramTemplateLauncher_4);
-							}
+					String name = diagramDefinition.getPrefix();
+					if (eObject instanceof NamedElement) {
+						name += ((NamedElement) eObject).getName();
+					} else {
+						name += eObject.toString();
+					}
 
 
-							for (EObject eObject : content) {
-								if (matchStereotypedBy(eObject, selection.getStereotypedBy())) {
-									String name = diagramDefinition.getPrefix();
-									if (eObject instanceof NamedElement) {
-										name += ((NamedElement) eObject).getName();
-									} else {
-										name += eObject.toString();
-									}
-
-
-									if (selection.isSubTypes()) {
-										// Consider all subtypes
-										if (eObject.eClass().getEAllSuperTypes().contains(selection.getElement()) || eObject.eClass() == selection.getElement()) {
-											// System.err.println("FoundForAll Sub: " + diagramDefinition.getName());
-											// It matches: create a diagram
-											try {
-												creationCommandDescriptor.getCommand().createDiagram(modelSet, eObject, name);
-
-												// Identify the new diagram
-												TreeIterator<EObject> it = NotationUtils.getNotationResource(modelSet).getAllContents();
-												while (it.hasNext()) {
-													EObject diagram = it.next();
-													if (diagram instanceof Diagram) {
-														if (!diagramsInResource.contains(diagram.eResource().getURIFragment(diagram))) {
-															diagramsCreated.put(diagram.eResource().getURIFragment(diagram), selection);
-															diagramsInResource.add(diagram.eResource().getURIFragment(diagram));
-
-															creationReport.put(eObject, CreationReportKind.SUCCESS);
-														}
-													}
-												}
-
-											} catch (BackboneException e) {
-												// TODO Auto-generated catch block
-												e.printStackTrace(System.out);
-											}
-										}
-									} else {
-										if (eObject.eClass() == selection.getElement()) {
-											// System.err.println("FoundForAll Strict: " + diagramDefinition.getName());
-											// It matches: create a diagram
-
-											try {
-												creationCommandDescriptor.getCommand().createDiagram(modelSet, eObject, name);
-
-												// Identify the new diagram
-												TreeIterator<EObject> it = NotationUtils.getNotationResource(modelSet).getAllContents();
-												while (it.hasNext()) {
-													EObject diagram = it.next();
-													if (diagram instanceof Diagram) {
-														if (!diagramsInResource.contains(diagram.eResource().getURIFragment(diagram))) {
-															diagramsCreated.put(diagram.eResource().getURIFragment(diagram), selection);
-															diagramsInResource.add(diagram.eResource().getURIFragment(diagram));
-
-															creationReport.put(eObject, CreationReportKind.SUCCESS);
-														}
-													}
-												}
-
-											} catch (BackboneException e) {
-												// TODO Auto-generated catch block
-												e.printStackTrace(System.out);
-											}
-										}
-									}
-								}
-							}
-						} else if (selection.getKind() == SelectionKind.SPECIFIC) {
-
-							// System.err.println("FoundSpecific");
-							String name = diagramDefinition.getPrefix();
-							if (selection.getElement() instanceof NamedElement) {
-								name += ((NamedElement) selection.getElement()).getName();
-							} else {
-								name += selection.getElement().toString();
-							}
-
+					if (selection.isSubTypes()) {
+						// Consider all subtypes
+						if (eObject.eClass().getEAllSuperTypes().contains(selection.getElement()) || eObject.eClass() == selection.getElement()) {
+							// System.err.println("FoundForAll Sub: " + diagramDefinition.getName());
+							// It matches: create a diagram
 							try {
-								creationCommandDescriptor.getCommand().createDiagram(modelSet, selection.getElement(), name);
+								creationCommandDescriptor.getCommand().createDiagram(modelSet, eObject, name);
 
 								// Identify the new diagram
 								TreeIterator<EObject> it = NotationUtils.getNotationResource(modelSet).getAllContents();
 								while (it.hasNext()) {
 									EObject diagram = it.next();
 									if (diagram instanceof Diagram) {
-										if (!diagramsInResource.contains(diagram.eResource().getURIFragment(diagram))) {
-											diagramsCreated.put(diagram.eResource().getURIFragment(diagram), selection);
-											diagramsInResource.add(diagram.eResource().getURIFragment(diagram));
+										if (!existingDiagrams.contains(diagram)) {
+											createdDiagrams.put((Diagram) diagram, selection);
+											existingDiagrams.add((Diagram) diagram);
 
-											creationReport.put(selection.getElement(), CreationReportKind.SUCCESS);
+											CreationReport.getInstance().addToReport(eObject, CreationReportKind.SUCCESS);
 										}
 									}
 								}
+
 							} catch (BackboneException e) {
-								// TODO Auto-generated catch block
-								e.printStackTrace(System.out);
+								Activator.log.error(e);
+							}
+						}
+					} else {
+						if (eObject.eClass() == selection.getElement()) {
+							// System.err.println("FoundForAll Strict: " + diagramDefinition.getName());
+							// It matches: create a diagram
+
+							try {
+								creationCommandDescriptor.getCommand().createDiagram(modelSet, eObject, name);
+
+								// Identify the new diagram
+								TreeIterator<EObject> it = NotationUtils.getNotationResource(modelSet).getAllContents();
+								while (it.hasNext()) {
+									EObject diagram = it.next();
+									if (diagram instanceof Diagram) {
+										if (!existingDiagrams.contains(diagram)) {
+											createdDiagrams.put((Diagram) diagram, selection);
+											existingDiagrams.add((Diagram) diagram);
+
+											CreationReport.getInstance().addToReport(eObject, CreationReportKind.SUCCESS);
+										}
+									}
+								}
+
+							} catch (BackboneException e) {
+								Activator.log.error(e);
 							}
 						}
 					}
 				}
 			}
-		}
-	}
 
-	/**
-	 * Helper method used to arrange recursively editparts
-	 *
-	 * @param editpart
-	 *            the editpart to process
-	 */
-	protected void arrangeRecursively(EditPart editpart) {
-		// ArrangeRequest request = new ArrangeRequest(ActionIds.ACTION_ARRANGE_ALL, LayoutType.DEFAULT);
-		ArrangeRequest request = new ArrangeRequest(RequestConstants.REQ_ARRANGE_DEFERRED);
-		List<EditPart> listToArrange = new ArrayList<EditPart>();
-		listToArrange.addAll(editpart.getChildren());
+			else if (selection.getKind() == SelectionKind.SPECIFIC) {
 
-		if (!listToArrange.isEmpty()) {
-			for (Object element : editpart.getChildren()) {
-				if (element instanceof EditPart) {
-					arrangeRecursively((EditPart) element);
+				// System.err.println("FoundSpecific");
+				String name = diagramDefinition.getPrefix();
+				if (selection.getElement() instanceof NamedElement) {
+					name += ((NamedElement) selection.getElement()).getName();
+				} else {
+					name += selection.getElement().toString();
+				}
+
+				try {
+					// EObject matchingModelSelection = FindSelectionInModel.getInstance().findSelectionInModel(modelSet, selection);
+					EObject matchingModelSelection = FindSelectionInModel.findSelectionInModel(modelSet, selection);
+					// creationCommandDescriptor.getCommand().createDiagram(modelSet, selection.getElement(), name);
+					if (null == matchingModelSelection) {
+						// We could not find an element matching the selection - FIXME
+						return;
+					}
+					creationCommandDescriptor.getCommand().createDiagram(modelSet, matchingModelSelection, name);
+
+					// Identify the new diagram
+					Resource notationResource = NotationUtils.getNotationResource(modelSet);
+					TreeIterator<EObject> it = notationResource.getAllContents();
+					while (it.hasNext()) {
+						EObject diagram = it.next();
+						if (!(diagram instanceof Diagram)) {
+							continue;
+						}
+
+						if (!existingDiagrams.contains(diagram)) {
+							createdDiagrams.put((Diagram) diagram, selection);
+							existingDiagrams.add((Diagram) diagram);
+
+							CreationReport.getInstance().addToReport(selection.getElement(), CreationReportKind.SUCCESS);
+						}
+					}
+				} catch (BackboneException e) {
+					Activator.log.error(e);
 				}
 			}
-
-			request.setViewAdaptersToArrange(listToArrange);
-
-			Command command = editpart.getCommand(request);
-			command.execute();
 		}
 	}
 
+
+
+
 	/**
 	 * This is the main method for the template launcher. Executes the template
 	 *
@@ -672,150 +359,119 @@
 	 */
 	public void execute(Template template) {
 
-		diagramsInResource = new ArrayList<String>();
-		diagramsCreated = new HashMap<String, AbstractSelection>();
-		creationReport = new HashMap<EObject, CreationReportKind>();
+		existingDiagrams = new ArrayList<>();
+		createdDiagrams = new HashMap<>();
 
-		if (template != null) {
-			ModelSet modelSet = new DiResourceSet();
+		if (null == template) {
+			return;
+		}
+		// modelSet = ModelSetUtils.getInstance().getAssociatedModelSet(template);
+		modelSet = ModelSetUtils.getAssociatedModelSet(template);
 
+		if (null == template.getTargetRoot().eResource()) {
+			return;
+		}
 
+		// Identify already available diagrams
+		Resource notationResource = NotationUtils.getNotationResource(modelSet);
+		if (null == notationResource) {
+			MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), Messages.DiagramTemplateLauncher_6, Messages.DiagramTemplateLauncher_7);
+			return;
+		}
 
-			if (template.getTargetRoot().eResource() != null) {
-				String targetModelLocation = template.getTargetRoot().eResource().getURI().toPlatformString(false);
-				IFile targetModelfile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(targetModelLocation));
-
-				IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(targetModelfile.getFullPath().removeFileExtension().toString() + ".di")); //$NON-NLS-1$
-
-				if (file.exists()) {
-
-					try {
-						modelSet.loadModels(file);
-						initializeDiagramCategories(modelSet);
-					} catch (ModelMultiException ex) {
-						ex.printStackTrace(System.out);
-					}
-
-					try {
-						ServicesRegistry registry = new ExtensionServicesRegistry(org.eclipse.papyrus.infra.core.Activator.PLUGIN_ID);
-						registry.add(ModelSet.class, Integer.MAX_VALUE, modelSet);
-						try {
-							registry.startRegistry();
-						} catch (ServiceException ex) {
-							// Ignore
-						}
-
-						// Identify already available diagrams
-						TreeIterator<EObject> it = NotationUtils.getNotationResource(modelSet).getAllContents();
-						while (it.hasNext()) {
-							EObject diagram = it.next();
-							if (diagram instanceof Diagram) {
-								diagramsInResource.add(diagram.eResource().getURIFragment(diagram));
-							}
-						}
-
-						// Create diagrams
-						if (!template.getDiagramDefinitions().isEmpty()) {
-							for (DiagramDefinition diagramDefinition : template.getDiagramDefinitions()) {
-								createDiagramFor(diagramDefinition.getSelection(), diagramDefinition, modelSet);
-							}
-						} else {
-							// Create empty diagrams
-							// EditorUtils.getTransactionalIPageMngr(DiModelUtils.getDiResource(modelSet), modelSet.getTransactionalEditingDomain());
-						}
-
-						// Save the resource
-						try {
-							modelSet.save(new NullProgressMonitor());
-						} catch (IOException e) {
-							e.printStackTrace(System.out);
-							// return false;
-						}
-
-						try {
-							registry.disposeRegistry();
-						} catch (ServiceException ex) {
-							// Ignore
-						}
-
-					} catch (ServiceException ex) {
-						ex.printStackTrace(System.out);
-					}
-
-					// Open the editor
-					IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
-
-					if (page != null) {
-						try {
-							final IEditorPart editor = IDE.openEditor(page, file, true);
-
-							if (editor instanceof IMultiDiagramEditor) {
-								final ServicesRegistry services = ((IMultiDiagramEditor) editor).getServicesRegistry();
-								TransactionalEditingDomain editingDomain = services.getService(TransactionalEditingDomain.class);
-								org.eclipse.emf.common.command.Command openPagesCommand = new RecordingCommand(editingDomain, "Open created pages") {
-
-									@Override
-									protected void doExecute() {
-										try {
-											System.out.println("Executing");
-											IPageManager pageManager = services.getService(IPageManager.class);
-
-											System.out.println("Close all pages");
-											pageManager.closeAllOpenedPages();
-
-											// Go through the diagrams available in the resource
-											for (Object pageDiagram : pageManager.allPages()) {
-
-												if (pageDiagram instanceof Diagram) {
-													String pageID = ((Diagram) pageDiagram).eResource().getURIFragment((Diagram) pageDiagram);
-
-													if (diagramsCreated.containsKey(pageID)) {
-														System.out.println("Open page");
-														pageManager.openPage(pageDiagram);
-														IEditorPart activeEditor = ((PapyrusMultiDiagramEditor) editor).getActiveEditor();
-
-														if (activeEditor instanceof DiagramEditor) {
-															// Get the GraphicalViewer for this diagram
-															Object result = activeEditor.getAdapter(GraphicalViewer.class);
-															if (result != null && result instanceof GraphicalViewer) {
-																DiagramEditPart diagramEditPart = (DiagramEditPart) ((GraphicalViewer) result).getEditPartRegistry().get(pageDiagram);
-
-																// Retrieve the selection to show for this diagram
-																AbstractSelection selection = diagramsCreated.get(pageID);
-																addElementsFor(selection.getSelectionRef(), ((Diagram) pageDiagram).getElement(), (DiagramEditor) activeEditor, diagramEditPart);
-
-																// Arrange all recursively
-																arrangeRecursively(diagramEditPart);
-															}
-
-															// This page is processed now (may be not necessary)
-															diagramsCreated.remove(pageID);
-														}
-													}
-												}
-											}
-										} catch (ServiceException ex) {
-											ex.printStackTrace(System.out);
-										}
-									}
-								};
-
-								editingDomain.getCommandStack().execute(openPagesCommand);
-							}
-
-							// Report
-							DiagramTemplateLauncherReport.getInstance().showReport(creationReport);
-
-						} catch (PartInitException e) {
-							e.printStackTrace(System.out);
-						} catch (ServiceException e) {
-							e.printStackTrace(System.out);
-						}
-					}
-				} else {
-					MessageDialog.openError(PlatformUI.getWorkbench().getDisplay().getActiveShell(), Messages.DiagramTemplateLauncher_6, Messages.DiagramTemplateLauncher_7);
-				}
+		// Identify the existing diagrams so as to not use them for the upcoming populate action
+		TreeIterator<EObject> it = notationResource.getAllContents();
+		while (it.hasNext()) {
+			EObject diagram = it.next();
+			if (diagram instanceof Diagram) {
+				// exitingDiagrams.add(diagram.eResource().getURIFragment(diagram));
+				existingDiagrams.add((Diagram) diagram);
 			}
 		}
+
+		TransactionalEditingDomain modelSetEditingDomain = modelSet.getTransactionalEditingDomain();
+
+		RecordingCommand executeTemplateCommand = new RecordingCommand(modelSetEditingDomain, "TemplateExecution") {
+
+			@Override
+			protected void doExecute() {
+				// TODO Auto-generated method stub
+
+
+				// Create diagrams that match the template
+				if (!template.getDiagramDefinitions().isEmpty()) {
+					for (DiagramDefinition diagramDefinition : template.getDiagramDefinitions()) {
+						createDiagramFor(diagramDefinition.getSelection(), diagramDefinition, modelSet);
+					}
+				} else {
+					// Create empty diagrams
+					// EditorUtils.getTransactionalIPageMngr(DiModelUtils.getDiResource(modelSet), modelSet.getTransactionalEditingDomain());
+				}
+
+				// IMultiDiagramEditor editor = ModelSetUtils.getInstance().getAssociatedPapyrusEditor(template);
+				IMultiDiagramEditor editor = ModelSetUtils.getAssociatedPapyrusEditor(template);
+
+				if (editor != null) {
+
+					// FIXME Move this inside a single recording command
+					try {
+
+						final ServicesRegistry services = editor.getServicesRegistry();
+						final TransactionalEditingDomain editingDomain = services.getService(TransactionalEditingDomain.class);
+
+						IPageManager pageManager = services.getService(IPageManager.class);
+
+						// Go through the diagrams available in the resource
+						for (final Object pageDiagram : pageManager.allPages()) {
+
+							if (!(pageDiagram instanceof Diagram)) {
+								continue;
+							}
+
+							if (!(createdDiagrams.containsKey(pageDiagram))) {
+								continue;
+							}
+
+							// We need to open the diagram to retrieve its editpart and drop the elements in it
+							// org.eclipse.emf.common.command.Command openCreatedPagesCommand = new OpenDiagramsCommand(editingDomain, "Open created diagrams", createdDiagrams.keySet());
+							org.eclipse.emf.common.command.Command openCreatedPagesCommand = new OpenDiagramsCommand(editingDomain, "Open created diagrams", (Diagram) pageDiagram);
+							openCreatedPagesCommand.execute();
+
+							final IEditorPart activePart = editor.getActiveEditor();
+							// System.out.println(activePart);
+							DiagramEditor diagramEditor = activePart.getAdapter(DiagramEditor.class);
+							if (null == diagramEditor) {
+								continue;
+							}
+
+							// Get the GraphicalViewer for this diagram
+							final Object viewer = activePart.getAdapter(GraphicalViewer.class);
+							if (null == viewer) {
+								continue;
+							}
+
+							org.eclipse.emf.common.command.Command populateCreatedPagesCommand = new PopulateDiagramCommand(editingDomain, "Populate created pages", createdDiagrams.get(pageDiagram), diagramEditor);
+							populateCreatedPagesCommand.execute();
+
+							// Arrange all recursively
+							DiagramUtils.arrangeRecursively(diagramEditor.getDiagramEditPart());
+							// DiagramUtils.arrangeAll(diagramEditor.getDiagramEditPart());
+						}
+
+					} catch (ServiceException e) {
+						Activator.log.error(e);
+					}
+				}
+			}
+		};
+
+		modelSetEditingDomain.getCommandStack().execute(executeTemplateCommand);
+
+		// Report
+		DiagramTemplateLauncherReport.getInstance().showReport(CreationReport.getInstance().getReport());
+
+		// Reset stored informations
+		CreationReport.getInstance().clear();
 	}
+
 }
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/launcher/DiagramTemplateLauncherReport.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/launcher/DiagramTemplateLauncherReport.java
index f5f84c0..b0da475 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/launcher/DiagramTemplateLauncherReport.java
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/launcher/DiagramTemplateLauncherReport.java
@@ -18,9 +18,11 @@
 import org.eclipse.emf.ecore.EObject;
 import org.eclipse.jface.viewers.ILabelProvider;
 import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.papyrus.diagramtemplate.launcher.DiagramTemplateLauncher.CreationReportKind;
-import org.eclipse.papyrus.diagramtemplate.utils.Messages;
+import org.eclipse.papyrus.diagramtemplate.editor.messages.Messages;
+import org.eclipse.papyrus.diagramtemplate.utils.CreationReport.CreationReportKind;
 import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.widgets.Display;
+import org.eclipse.swt.widgets.Shell;
 import org.eclipse.ui.PlatformUI;
 import org.eclipse.ui.dialogs.ElementListSelectionDialog;
 import org.eclipse.uml2.uml.NamedElement;
@@ -108,7 +110,7 @@
 		// ListSelectionDialog dlg = new ListSelectionDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getSite().getShell(), report, new DiagramTemplateLauncherReportContentProvider(), new
 		// DiagramTemplateLauncherReportLabelProvider(), "Report");
 		// dlg.open();
-		ElementListSelectionDialog dlg = new ElementListSelectionDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getSite().getShell(), new DiagramTemplateLauncherReportLabelProvider());
+		ElementListSelectionDialog dlg = new ElementListSelectionDialog(Display.getCurrent().getActiveShell(), new DiagramTemplateLauncherReportLabelProvider());
 		dlg.setElements(report.entrySet().toArray());
 		dlg.setTitle(Messages.DiagramTemplateLauncherReport_6);
 		dlg.open();
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/CreationReport.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/CreationReport.java
new file mode 100755
index 0000000..52c2055
--- /dev/null
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/CreationReport.java
@@ -0,0 +1,62 @@
+/*****************************************************************************
+ * Copyright (c) 2018 CEA LIST and others.
+ * 
+ * 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.diagramtemplate.utils;
+
+import java.util.HashMap;
+
+import org.eclipse.emf.ecore.EObject;
+
+/**
+ * @author Quentin Le Menez
+ *
+ */
+public class CreationReport {
+
+	private static CreationReport INSTANCE;
+
+	private static HashMap<EObject, CreationReportKind> report;
+
+	/**
+	 * Enum used to report on diagram creation
+	 */
+	public enum CreationReportKind {
+		SUCCESS, FAIL
+	}
+
+	private CreationReport() {
+		// singleton
+	}
+
+	public static CreationReport getInstance() {
+		if (INSTANCE == null) {
+			INSTANCE = new CreationReport();
+			report = new HashMap<>();
+		}
+		return INSTANCE;
+	}
+
+	public void addToReport(EObject elementToShow, CreationReportKind status) {
+		report.put(elementToShow, status);
+	}
+
+	public HashMap<EObject, CreationReportKind> getReport() {
+		return report;
+	}
+
+	public void clear() {
+		INSTANCE = null;
+		report.clear();
+	}
+
+}
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/DiagramUtils.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/DiagramUtils.java
new file mode 100755
index 0000000..1c96593
--- /dev/null
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/DiagramUtils.java
@@ -0,0 +1,69 @@
+/*****************************************************************************
+ * Copyright (c) 2018 CEA LIST and others.
+ * 
+ * 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.diagramtemplate.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.eclipse.gef.EditPart;
+import org.eclipse.gef.commands.Command;
+import org.eclipse.gef.commands.CompoundCommand;
+import org.eclipse.gmf.runtime.diagram.ui.actions.ActionIds;
+import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
+import org.eclipse.gmf.runtime.diagram.ui.requests.ArrangeRequest;
+import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants;
+import org.eclipse.gmf.runtime.diagram.ui.services.layout.LayoutType;
+import org.eclipse.papyrus.uml.diagram.menu.actions.ArrangeAction;
+
+/**
+ * @author Quentin Le Menez
+ *
+ */
+public class DiagramUtils {
+
+	/**
+	 * Helper method used to arrange recursively editparts
+	 *
+	 * @param editpart
+	 *            the editpart to process
+	 */
+	public static void arrangeRecursively(EditPart editPart) {
+		ArrangeRequest request = new ArrangeRequest(RequestConstants.REQ_ARRANGE_DEFERRED);
+		List<EditPart> listToArrange = new ArrayList<>();
+		listToArrange.addAll(editPart.getChildren());
+
+		if (!listToArrange.isEmpty()) {
+			for (Object element : editPart.getChildren()) {
+				if (element instanceof EditPart) {
+					arrangeRecursively((EditPart) element);
+				}
+			}
+
+			request.setViewAdaptersToArrange(listToArrange);
+
+			Command command = editPart.getCommand(request);
+			if (null != command && command.canExecute()) {
+				command.execute();
+			}
+		}
+	}
+
+	// FIXME This does not seem to execute itself the same as the arrangeAction handler does...
+	public static void arrangeAll(DiagramEditPart editPart) {
+		ArrangeAction arrangeall = new ArrangeAction(ArrangeAction.ARRANGE_ALL, new ArrayList<>());
+		arrangeall.getCommand().execute();
+	}
+
+
+}
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/FindSelectionInModel.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/FindSelectionInModel.java
new file mode 100755
index 0000000..cfc15a0
--- /dev/null
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/FindSelectionInModel.java
@@ -0,0 +1,99 @@
+/*****************************************************************************
+ * Copyright (c) 2018 CEA LIST and others.
+ * 
+ * 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.diagramtemplate.utils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.papyrus.diagramtemplate.AbstractSelection;
+import org.eclipse.papyrus.diagramtemplate.editor.Activator;
+import org.eclipse.papyrus.infra.core.resource.ModelSet;
+import org.eclipse.papyrus.infra.core.resource.NotFoundException;
+import org.eclipse.papyrus.uml.tools.model.UmlModel;
+import org.eclipse.uml2.uml.NamedElement;
+
+/**
+ * @author Quentin Le Menez
+ *
+ */
+public class FindSelectionInModel {
+
+	// private static FindSelectionInModel INSTANCE;
+
+	// private static Map<ModelSet, List<EObject>> parsedElements;
+
+	private FindSelectionInModel() {
+		// singleton
+	}
+
+	// public static FindSelectionInModel getInstance() {
+	// if (INSTANCE == null) {
+	// INSTANCE = new FindSelectionInModel();
+	// parsedElements = new HashMap<>();
+	// }
+	// return INSTANCE;
+	// }
+
+	public static EObject findSelectionInModel(ModelSet modelSet, AbstractSelection selection) {
+		return findSelectionInModel(modelSet, selection.getElement());
+	}
+
+
+	public static EObject findSelectionInModel(ModelSet modelSet, EObject selection) {
+		try {
+			// if (!parsedElements.keySet().contains(modelSet)) {
+			UmlModel umlModel = (UmlModel) modelSet.getModel(UmlModel.MODEL_ID);
+			List<EObject> containedElements = new ArrayList<>();
+			umlModel.lookupRoot().eAllContents().forEachRemaining(containedElements::add);
+			// parsedElements.put(modelSet, containedElements);
+			// }
+
+			// return loopOnContent(parsedElements.get(modelSet), selection);
+			return loopOnContent(containedElements, selection);
+
+		} catch (NotFoundException e) {
+			Activator.log.error(e);
+		}
+
+		return null;
+
+	}
+
+
+	protected static EObject loopOnContent(List<EObject> containedElements, EObject selectionElement) {
+
+		for (EObject eObject : containedElements) {
+			if (eObject instanceof NamedElement && selectionElement instanceof NamedElement) {
+				String eObjectURIf = eObject.eResource().getURIFragment(eObject);
+				String selectionElementURIf = selectionElement.eResource().getURIFragment(selectionElement);
+
+				if (eObjectURIf.equals(selectionElementURIf)) {
+					return eObject;
+				}
+			}
+		}
+
+		return null;
+	}
+
+
+	// public void clear() {
+	// INSTANCE = null;
+	// parsedElements.clear();
+	// }
+
+}
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/ModelSetUtils.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/ModelSetUtils.java
new file mode 100755
index 0000000..807aef5
--- /dev/null
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/ModelSetUtils.java
@@ -0,0 +1,248 @@
+/*****************************************************************************
+ * Copyright (c) 2018 CEA LIST and others.
+ * 
+ * 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.diagramtemplate.utils;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.eclipse.core.runtime.IAdaptable;
+import org.eclipse.emf.common.util.URI;
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.papyrus.diagramtemplate.Template;
+import org.eclipse.papyrus.infra.architecture.ArchitectureDomainManager;
+import org.eclipse.papyrus.infra.architecture.representation.PapyrusRepresentationKind;
+import org.eclipse.papyrus.infra.core.architecture.RepresentationKind;
+import org.eclipse.papyrus.infra.core.architecture.merged.MergedArchitectureContext;
+import org.eclipse.papyrus.infra.core.architecture.merged.MergedArchitectureViewpoint;
+import org.eclipse.papyrus.infra.core.resource.ModelSet;
+import org.eclipse.papyrus.infra.core.services.ServiceException;
+import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
+import org.eclipse.papyrus.infra.viewpoints.policy.ViewPrototype;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.IEditorReference;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ * @author Quentin Le Menez
+ *
+ */
+public class ModelSetUtils {
+
+	/**
+	 * List of diagram categories to consider
+	 */
+	// protected List<ViewPrototype> representationsKinds;
+
+	// private static ModelSetUtils INSTANCE;
+
+	// protected ModelSet modelSet;
+
+
+	// public static ModelSetUtils getInstance() {
+	// if (INSTANCE == null) {
+	// INSTANCE = new ModelSetUtils();
+	// }
+	// return INSTANCE;
+	// }
+
+
+	/**
+	 * Get the last opened ModelSet associated to the currently opened window
+	 * 
+	 * @return
+	 * 		the ModelSet or null if none was found
+	 */
+	public static ModelSet getAssociatedModelSet() {
+		return getAssociatedModelSet(null);
+	}
+
+	/**
+	 * Get the ModelSet associated to the executed template in the currently opened window
+	 * 
+	 * @return
+	 * 		the ModelSet or null if none was found
+	 */
+	public static ModelSet getAssociatedModelSet(Template template) {
+
+		ModelSet modelSet = null;
+		IMultiDiagramEditor part = getAssociatedPapyrusEditor(template);
+
+		if (null != part && null == modelSet) {
+			// try to resolve the modelSet from the active editor if no template has been provided
+			try {
+				modelSet = part.getServicesRegistry().getService(ModelSet.class);
+			} catch (ServiceException e) {
+				e.printStackTrace();
+			}
+		}
+
+		// initialize the available viewprototypes that will be used to match against the diagram creations (types)
+		initializeDiagramCategories();
+
+		return modelSet;
+	}
+
+
+	/**
+	 * Used to get the the last opened MultiDiagramEditor part
+	 * 
+	 * @return
+	 * 		The part or null if none has been found
+	 */
+	public static IMultiDiagramEditor getAssociatedPapyrusEditor() {
+		return resolvePapyrusEditor(getActivePage(), null);
+	}
+
+	/**
+	 * Used to get the the MultiDiagramEditor part associated to the executed template
+	 * 
+	 * @return
+	 * 		The part or null if none has been found
+	 */
+	public static IMultiDiagramEditor getAssociatedPapyrusEditor(Template template) {
+		return resolvePapyrusEditor(getActivePage(), template);
+	}
+
+
+	/**
+	 * 
+	 * @return
+	 * 		The active workbench page
+	 */
+	private static IWorkbenchPage getActivePage() {
+		try {
+			IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+			if (activeWorkbenchWindow == null) {
+				return null;
+			}
+
+			IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
+			if (activePage == null) {
+				return null;
+			}
+
+			return activePage;
+		} catch (NullPointerException e) {
+			// An element is not active yet
+			return null;
+		}
+	}
+
+
+	/**
+	 * 
+	 * @param activePage
+	 * @param template
+	 * @return
+	 * 		The IMultiDiagramEditor or null if none has been found
+	 */
+	private static IMultiDiagramEditor resolvePapyrusEditor(IWorkbenchPage activePage, Template template) {
+		// FIXME - This needs to ask the last handled (IMulti)DiangramEditor from the workspace
+		// Eclipse can see it, as its tab is still in front of the others when switching to other editors
+		// As it is this will work if the template points to a model but reverts to the last editor if not
+		IMultiDiagramEditor part = null;
+
+		if (null == activePage) {
+			return part;
+		}
+
+		for (IEditorReference editorRef : activePage.getEditorReferences()) {
+			IEditorPart editorPart = editorRef.getEditor(true);
+
+			IMultiDiagramEditor multiDiagramEditor = editorPart instanceof IAdaptable ? ((IAdaptable) editorPart).getAdapter(IMultiDiagramEditor.class) : null;
+			if (null != multiDiagramEditor) {
+				part = multiDiagramEditor;
+			}
+
+			if (null != template) {
+				EObject templateRoot = template.getTargetRoot();
+				if (null == templateRoot) {
+					continue;
+				}
+
+				URI modelURI = templateRoot.eResource().getURI().trimFileExtension();
+				try {
+					ModelSet modelSet = part.getServicesRegistry().getService(ModelSet.class);
+					if (null == modelSet) {
+						continue;
+					}
+
+					if (!modelSet.getURIWithoutExtension().equals(modelURI)) {
+						continue;
+					}
+
+					return part;
+				} catch (ServiceException e) {
+					e.printStackTrace();
+				}
+			}
+		}
+
+		return part;
+	}
+
+
+	/**
+	 * Get the ViewPrototypes associated to the Papyrus diagrams
+	 * 
+	 * @return
+	 * 		The list of the ViewPrototypes or null if none can be found
+	 */
+	public static List<ViewPrototype> getRepresentationKinds() {
+		// if (representationsKinds == null || representationsKinds.isEmpty()) {
+		// initializeDiagramCategories();
+		// }
+		//
+		// return representationsKinds;
+		return initializeDiagramCategories();
+	}
+
+
+	/**
+	 * Get the ViewPrototypes associated to the viewpoint
+	 * 
+	 * @param modelSet
+	 */
+	// private void initializeDiagramCategories() {
+	private static List<ViewPrototype> initializeDiagramCategories() {
+		List<ViewPrototype> representationsKinds = new ArrayList<>();
+
+		ArchitectureDomainManager manager = ArchitectureDomainManager.getInstance();
+		Collection<MergedArchitectureContext> contexts = manager.getVisibleArchitectureContexts();
+
+		for (MergedArchitectureContext mergedArchitectureContext : contexts) {
+			Collection<MergedArchitectureViewpoint> viewpoints = mergedArchitectureContext.getViewpoints();
+
+			for (MergedArchitectureViewpoint mergedArchitectureViewpoint : viewpoints) {
+				Collection<RepresentationKind> representations = mergedArchitectureViewpoint.getRepresentationKinds();
+				for (RepresentationKind representationKind : representations) {
+					if (representationKind instanceof PapyrusRepresentationKind) {
+						representationsKinds.add(ViewPrototype.get((PapyrusRepresentationKind) representationKind));
+					}
+				}
+			}
+		}
+
+		return representationsKinds;
+	}
+
+	// public void clear() {
+	// INSTANCE = null;
+	// modelSet = null;
+	// representationsKinds.clear();
+	// }
+}
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/ModelUtils.java b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/ModelUtils.java
new file mode 100755
index 0000000..eb0148a
--- /dev/null
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate.editor/src/org/eclipse/papyrus/diagramtemplate/utils/ModelUtils.java
@@ -0,0 +1,72 @@
+/*****************************************************************************
+ * Copyright (c) 2018 CEA LIST and others.
+ * 
+ * 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.diagramtemplate.utils;
+
+import org.eclipse.emf.ecore.EObject;
+import org.eclipse.uml2.uml.Element;
+
+/**
+ * @author Quentin Le Menez
+ *
+ */
+public class ModelUtils {
+
+	// private static ModelUtils INSTANCE;
+
+	private ModelUtils() {
+		// singleton
+	}
+
+	// public static ModelUtils getInstance() {
+	// if (INSTANCE == null) {
+	// return new ModelUtils();
+	// }
+	// return INSTANCE;
+	// }
+
+	/**
+	 * Utils method that determine whether an element is stereotypedBy a certain stereotype qualiedName
+	 *
+	 * @param element
+	 *            the element to test
+	 * @param stereotypedBy
+	 *            the qulifiedName of the stereotype to match
+	 * @return
+	 * 		true if matches false else.
+	 */
+	public static boolean matchStereotypedBy(EObject element, String stereotypedBy) {
+		if (element instanceof Element) {
+			// Read stereotypedBy
+			stereotypedBy = stereotypedBy.replaceAll(" ", ""); //$NON-NLS-1$ //$NON-NLS-2$
+			String[] stereotypes = stereotypedBy.split(","); //$NON-NLS-1$
+
+			boolean matchStereotypes = true;
+			for (String stereo : stereotypes) {
+				if (stereo != null && stereo.length() > 0) {
+					if (((Element) element).getAppliedStereotype(stereo) != null) {
+						matchStereotypes = true;
+					} else {
+						matchStereotypes = false;
+						break;
+					}
+				}
+			}
+
+			return matchStereotypes;
+		}
+
+		return false;
+	}
+
+}
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/.classpath b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/.classpath
index 240e23b..26e67d6 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/.classpath
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/.classpath
@@ -1,8 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
-	<classpathentry kind="src" path="src-gen"/>
-	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
 	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
-	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+	<classpathentry kind="src" path="src-gen"/>
 	<classpathentry kind="output" path="bin"/>
 </classpath>
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/.settings/org.eclipse.jdt.core.prefs b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/.settings/org.eclipse.jdt.core.prefs
index c585cc4..b3aa6d6 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/.settings/org.eclipse.jdt.core.prefs
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/.settings/org.eclipse.jdt.core.prefs
@@ -1,10 +1,10 @@
 eclipse.preferences.version=1
 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
-org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.compliance=1.8
 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
 org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.5
+org.eclipse.jdt.core.compiler.source=1.8
 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/META-INF/MANIFEST.MF b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/META-INF/MANIFEST.MF
index f8c79cc..fd92874 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/META-INF/MANIFEST.MF
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/META-INF/MANIFEST.MF
@@ -12,4 +12,4 @@
 Bundle-Name: %pluginName
 Bundle-ManifestVersion: 2
 Bundle-SymbolicName: org.eclipse.papyrus.diagramtemplate;singleton:=true
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
+Bundle-RequiredExecutionEnvironment: JavaSE-1.8
diff --git a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/build.properties b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/build.properties
index 2b28a0f..3f89e9d 100755
--- a/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/build.properties
+++ b/diagramtemplate/plugins/org.eclipse.papyrus.diagramtemplate/build.properties
@@ -11,6 +11,6 @@
                plugin.properties,\
                about.html
 jars.compile.order = .
-source.. = src/
+source.. = src-gen/
 output.. = bin/
 src.includes = about.html