Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 89f968afccea14718fa75301202aeb98c15fd6f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
/*****************************************************************************
 * Copyright (c) 2015 Christian W. Damus 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:
 *   Christian W. Damus - Initial API and implementation
 *   
 *****************************************************************************/

package org.eclipse.papyrus.infra.gmfdiag.canonical.tests;

import static org.eclipse.papyrus.infra.gmfdiag.common.utils.DiagramEditPartsUtil.isCanonical;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.util.AbstractTreeIterator;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.ENamedElement;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.edit.command.AddCommand;
import org.eclipse.emf.edit.command.RemoveCommand;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.requests.GroupRequest;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand;
import org.eclipse.gmf.runtime.diagram.core.edithelpers.CreateElementRequestAdapter;
import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateConnectionViewAndElementRequest;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewAndElementRequest;
import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
import org.eclipse.gmf.runtime.emf.type.core.ElementTypeRegistry;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.emf.type.core.IHintedType;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper;
import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper;
import org.eclipse.papyrus.infra.core.utils.AdapterUtils;
import org.eclipse.papyrus.infra.emf.utils.TreeIterators;
import org.eclipse.papyrus.infra.gmfdiag.common.commands.SetCanonicalCommand;
import org.eclipse.papyrus.infra.gmfdiag.common.utils.DiagramEditPartsUtil;
import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
import org.eclipse.papyrus.infra.services.edit.utils.ElementTypeUtils;
import org.eclipse.papyrus.junit.framework.classification.tests.AbstractPapyrusTest;
import org.eclipse.papyrus.junit.utils.JUnitUtils;
import org.eclipse.papyrus.junit.utils.rules.HouseKeeper;
import org.eclipse.papyrus.junit.utils.rules.PapyrusEditorFixture;
import org.eclipse.papyrus.uml.diagram.clazz.edit.parts.ClassAttributeCompartmentEditPart;
import org.eclipse.papyrus.uml.diagram.clazz.edit.parts.ClassNestedClassifierCompartmentEditPart;
import org.eclipse.papyrus.uml.diagram.clazz.edit.parts.ClassOperationCompartmentEditPart;
import org.eclipse.papyrus.uml.diagram.clazz.edit.parts.EnumerationEnumerationLiteralCompartmentEditPart;
import org.eclipse.papyrus.uml.diagram.clazz.edit.parts.PackagePackageableElementCompartmentEditPart;
import org.eclipse.papyrus.uml.diagram.clazz.providers.UMLElementTypes;
import org.eclipse.uml2.uml.AggregationKind;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Dependency;
import org.eclipse.uml2.uml.DirectedRelationship;
import org.eclipse.uml2.uml.LiteralUnlimitedNatural;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.util.UMLUtil;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.Futures;

/**
 * Common implementation of canonical test cases.
 */
public class AbstractCanonicalTest extends AbstractPapyrusTest {
	@Rule
	public final HouseKeeper houseKeeper = new HouseKeeper();

	@Rule
	public final TestRule annotationRule = new AnnotationRule();

	@Rule
	public final PapyrusEditorFixture editor = new PapyrusEditorFixture();

	private ComposedAdapterFactory adapterFactory;

	private boolean needUIEvents;

	public AbstractCanonicalTest() {
		super();
	}

	@Before
	public void createAdapterFactory() {
		houseKeeper.setField("adapterFactory", new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE));
	}

	protected DiagramEditPart getDiagramEditPart() {
		return editor.getActiveDiagramEditor().getDiagramEditPart();
	}

	protected TreeIterator<IGraphicalEditPart> allContents(EditPart root, boolean includeRoot) {
		return TreeIterators.filter(DiagramEditPartsUtil.getAllContents(root, includeRoot), IGraphicalEditPart.class);
	}

	protected IGraphicalEditPart getEditPart(EObject element) {
		return getEditPart(element, getDiagramEditPart());
	}

	protected IGraphicalEditPart getEditPart(EObject element, IGraphicalEditPart scope) {
		IGraphicalEditPart result = null;

		for (Iterator<IGraphicalEditPart> iter = allContents(scope, true); iter.hasNext();) {
			IGraphicalEditPart next = iter.next();
			View view = next.getNotationView();
			if ((view != null) && (view.getElement() == element)) {
				result = next;
				break;
			}
		}

		return result;
	}

	protected IGraphicalEditPart requireEditPart(EObject element) {
		IGraphicalEditPart result = getEditPart(element, getDiagramEditPart());
		assertThat("No edit part for " + label(element), result, notNullValue());
		return result;
	}

	protected IGraphicalEditPart getConnectionEditPart(EObject element) {
		IGraphicalEditPart result = null;

		for (Iterator<IGraphicalEditPart> iter = Iterators.filter(getDiagramEditPart().getConnections().iterator(), IGraphicalEditPart.class); iter.hasNext();) {
			IGraphicalEditPart next = iter.next();
			View view = next.getNotationView();
			if ((view != null) && (view.getElement() == element)) {
				result = next;
				break;
			}
		}

		return result;
	}

	protected IGraphicalEditPart requireConnectionEditPart(EObject element) {
		IGraphicalEditPart result = getConnectionEditPart(element);
		assertThat("No connection edit part for " + label(element), result, notNullValue());
		return result;
	}

	protected View getView(EObject element, View scope) {
		View result = null;

		for (Iterator<View> iter = Iterators.filter(scope.eAllContents(), View.class); (result == null) && iter.hasNext();) {
			View next = iter.next();
			if (next.getElement() == element) {
				result = next;
			}
		}

		return result;
	}

	protected View requireView(EObject element, View scope) {
		View result = getView(element, scope);
		assertThat("View not found: " + label(element), result, notNullValue());
		return result;
	}

	protected void assertNoView(EObject element, View scope) {
		View view = getView(element, scope);
		assertThat("View exists: " + label(element), view, nullValue());
	}

	protected IGraphicalEditPart getCompartment(IGraphicalEditPart parent, int type) {
		return parent.getChildBySemanticHint(Integer.toString(type));
	}

	protected IGraphicalEditPart getClassAttributeCompartment(IGraphicalEditPart class_) {
		return getCompartment(class_, ClassAttributeCompartmentEditPart.VISUAL_ID);
	}

	protected IGraphicalEditPart getClassOperationCompartment(IGraphicalEditPart class_) {
		return getCompartment(class_, ClassOperationCompartmentEditPart.VISUAL_ID);
	}

	protected IGraphicalEditPart getClassNestedClassifierCompartment(IGraphicalEditPart class_) {
		return getCompartment(class_, ClassNestedClassifierCompartmentEditPart.VISUAL_ID);
	}

	protected IGraphicalEditPart getEnumerationLiteralCompartment(IGraphicalEditPart enumeration) {
		return getCompartment(enumeration, EnumerationEnumerationLiteralCompartmentEditPart.VISUAL_ID);
	}

	protected IGraphicalEditPart getPackageContentsCompartment(IGraphicalEditPart package_) {
		return getCompartment(package_, PackagePackageableElementCompartmentEditPart.VISUAL_ID);
	}

	protected <T extends DirectedRelationship> T getRelationship(NamedElement from, NamedElement to, Class<T> type) {
		T result = null;

		for (T next : Iterables.filter(from.getSourceDirectedRelationships(), type)) {
			if (next.getTargets().contains(to)) {
				result = next;
				break;
			}
		}

		return result;
	}

	protected void execute(ICommand command) {
		execute(GMFtoEMFCommandWrapper.wrap(command));
	}

	protected void execute(Command command) {
		execute(GEFtoEMFCommandWrapper.wrap(command));
	}

	protected void execute(org.eclipse.emf.common.command.Command command) {
		assertThat("Cannot execute command", command.canExecute(), is(true));
		editor.getEditingDomain().getCommandStack().execute(command);
		waitForUIEvents();
	}

	protected final void waitForUIEvents() {
		// If we're running the tests in the IDE, we should see what's happening. Or, it could be that a
		// particular test actually needs UI events to be processed before proceeding
		if (!JUnitUtils.isAutomatedBuildExecution() || isNeedUIEvents()) {
			editor.flushDisplayEvents();
		}
	}

	protected final boolean isNeedUIEvents() {
		return needUIEvents;
	}

	protected void execute(final Runnable writeOperation) {
		execute(new RecordingCommand(editor.getEditingDomain()) {

			@Override
			protected void doExecute() {
				writeOperation.run();
			}
		});
	}

	protected <V> V execute(final Callable<V> writeOperation) {
		final FutureTask<V> result = new FutureTask<>(writeOperation);
		execute(result);
		return Futures.getUnchecked(result);
	}

	protected void undo() {
		CommandStack stack = editor.getEditingDomain().getCommandStack();
		assertThat("Cannot undo", stack.canUndo(), is(true));
		stack.undo();
		waitForUIEvents();
	}

	protected void redo() {
		CommandStack stack = editor.getEditingDomain().getCommandStack();
		assertThat("Cannot redo", stack.canRedo(), is(true));
		stack.redo();
		waitForUIEvents();
	}

	protected void setEditPartsCanonical(boolean canonical, Iterable<? extends EditPart> editParts) {
		final TransactionalEditingDomain domain = editor.getEditingDomain();

		ICommand command = new CompositeTransactionalCommand(domain, "Toggle Synchronize with Model");
		for (EditPart editPart : editParts) {
			if (canonical != isCanonical(editPart)) {
				command = command.compose(new SetCanonicalCommand(domain, (View) editPart.getModel(), canonical));
			} else {
				command = UnexecutableCommand.INSTANCE;
				break;
			}
		}

		command = command.reduce();

		execute(command);
	}

	protected void setCanonical(boolean canonical, EditPart first, EditPart second, EditPart... rest) {
		setEditPartsCanonical(canonical, Lists.asList(first, second, rest));
	}

	protected void setCanonical(boolean canonical, EditPart editPart) {
		final TransactionalEditingDomain domain = editor.getEditingDomain();

		ICommand command = UnexecutableCommand.INSTANCE;
		if (canonical != isCanonical(editPart)) {
			command = new SetCanonicalCommand(domain, (View) editPart.getModel(), canonical);
		}

		execute(command);
	}

	protected void setElementsCanonical(boolean canonical, Iterable<? extends EObject> elements) {
		List<EditPart> editParts = Lists.newArrayList();
		for (EObject next : elements) {
			editParts.add(requireEditPart(next));
		}
		setEditPartsCanonical(canonical, editParts);
	}

	protected void setCanonical(boolean canonical, EObject first, EObject second, EObject... rest) {
		setElementsCanonical(canonical, Lists.asList(first, second, rest));
	}

	protected void setCanonical(boolean canonical, EObject element) {
		setCanonical(canonical, requireEditPart(element));
	}

	/**
	 * Adds a new semantic {@code element} to the model.
	 * Relies on canonical edit policy to create the notation view.
	 */
	protected void add(EObject owner, EObject element, EReference feature) {
		execute(AddCommand.create(editor.getEditingDomain(), owner, feature, element));
	}

	/**
	 * Creates a new semantic element in the model with its notation view. So, not a canonical scenario, but intended to regression-test this behaviour
	 * in a canonical context.
	 */
	protected <T extends EObject> T createWithView(EObject owner, EClass metaclass, Class<T> type) {
		IGraphicalEditPart editPart = requireEditPart(owner);
		if (owner instanceof org.eclipse.uml2.uml.Package) {
			// Package edit parts don't implement getTargetEditPart API
			editPart = getPackageContentsCompartment(editPart);
		}

		Command command = findNodeCreationCommand(editPart, owner, metaclass);
		assertThat("No executable command provided to create " + label(metaclass), command, notNullValue());
		execute(command);

		return getNewObject(command, type);
	}

	private Command findNodeCreationCommand(EditPart editPart, EObject owner, EClass metaclass) {
		Command result = null;

		for (IElementType next : getClassDiagramElementTypes(metaclass)) {
			Command command = getNodeCreationCommand(editPart, owner, next);
			if ((command != null) && command.canExecute()) {
				result = command;
				break;
			}
		}

		return result;
	}

	private Command getNodeCreationCommand(EditPart editPart, EObject owner, IElementType elementType) {
		CreateElementRequestAdapter adapter = new CreateElementRequestAdapter(new CreateElementRequest(owner, elementType));
		String hint = (elementType instanceof IHintedType) ? ((IHintedType) elementType).getSemanticHint() : null;
		CreateViewAndElementRequest.ViewAndElementDescriptor descriptor = new CreateViewAndElementRequest.ViewAndElementDescriptor(adapter, Node.class, hint, editor.getPreferencesHint());
		CreateViewAndElementRequest request = new CreateViewAndElementRequest(descriptor);

		EditPart targetEditPart = editPart.getTargetEditPart(request);
		return targetEditPart.getCommand(request);
	}

	private List<? extends IElementType> getClassDiagramElementTypes(EClass metaclass) {
		List<IElementType> result = Lists.newArrayListWithExpectedSize(3);
		IElementType base = ElementTypeRegistry.getInstance().getElementType(metaclass, ElementTypeUtils.getEditContext());

		// Filter for class diagram types matching the exact metaclass (e.g., no Usage for Dependency or Port for Property)
		for (IElementType next : ElementTypeRegistry.getInstance().getSpecializationsOf(base.getId())) {
			if ((next.getEClass() == metaclass) && UMLElementTypes.isKnownElementType(next)) {
				result.add(next);
			}
		}

		return result;
	}

	private <T extends EObject> T getNewObject(Command command, Class<T> type) {
		Iterator<ICommandProxy> proxies = Iterators.filter(leafCommands(command), ICommandProxy.class);

		Object adapter = Iterators.find(Iterators.transform(proxies, new Function<ICommandProxy, Object>() {
			@Override
			public Object apply(ICommandProxy input) {
				CommandResult result = input.getICommand().getCommandResult();
				Object resultValue = (result == null) ? null : result.getReturnValue();
				if (resultValue instanceof Iterable<?>) {
					for (Object next : (Iterable<?>) resultValue) {
						resultValue = AdapterUtils.adapt(next, EObject.class, null);
						if (resultValue != null) {
							break;
						}
					}
				} else {
					resultValue = AdapterUtils.adapt(resultValue, EObject.class, null);
				}
				return resultValue;
			}
		}), Predicates.notNull());

		T result;

		EObject eObject = AdapterUtils.adapt(adapter, EObject.class, null);
		if (eObject instanceof View) {
			result = type.cast(((View) eObject).getElement());
		} else {
			result = type.cast(eObject);
		}

		return result;
	}

	private Iterator<Command> leafCommands(Command command) {
		return new AbstractTreeIterator<Command>(command, true) {
			private static final long serialVersionUID = 1L;

			@SuppressWarnings("unchecked")
			@Override
			protected Iterator<? extends Command> getChildren(Object object) {
				if (object instanceof CompoundCommand) {
					return ((Iterable<? extends Command>) ((CompoundCommand) object).getCommands()).iterator();
				} else {
					return Collections.emptyIterator();
				}
			}
		};
	}

	/**
	 * Adds a new association to the model, which is slightly more complex than owned directed relationships.
	 * Relies on canonical edit policy to create the notation view.
	 */
	protected Dependency addDependency(final NamedElement client, final NamedElement supplier) {
		return execute(new Callable<Dependency>() {

			@Override
			public Dependency call() throws Exception {
				return client.createDependency(supplier);
			}
		});
	}

	/**
	 * Adds a new association to the model, which is more complex than owned directed relationships.
	 * Relies on canonical edit policy to create the notation view.
	 */
	protected Association addAssociation(final Type end1, final Type end2) {
		return execute(new Callable<Association>() {

			@Override
			public Association call() throws Exception {
				String end1Name = end2.getName().substring(0, 1).toLowerCase() + end2.getName().substring(1);
				String end2Name = end1.getName().substring(0, 1).toLowerCase() + end1.getName().substring(1);
				return end1.createAssociation(true, AggregationKind.NONE_LITERAL, end1Name, 0, 1, end2,
						false, AggregationKind.NONE_LITERAL, end2Name, 0, LiteralUnlimitedNatural.UNLIMITED);
			}
		});
	}

	/**
	 * Creates a new dependency in the model with its notation view. So, not a canonical scenario, but intended to regression-test this behaviour
	 * in a canonical context.
	 */
	protected Dependency createDependencyWithView(NamedElement client, NamedElement supplier) {
		EditPart sourceEditPart = requireEditPart(client);
		EditPart targetEditPart = requireEditPart(supplier);

		Command command = findConnectionCreationCommand(sourceEditPart, targetEditPart, UMLPackage.Literals.DEPENDENCY);

		assertThat("No executable command provided to create dependency", command, notNullValue());
		execute(command);

		return getNewObject(command, Dependency.class);
	}

	private Command findConnectionCreationCommand(EditPart sourceEditPart, EditPart targetEditPart, EClass metaclass) {
		Command result = null;

		for (IElementType next : getClassDiagramElementTypes(metaclass)) {
			Command command = getConnectionCreationCommand(sourceEditPart, targetEditPart, next);
			if ((command != null) && command.canExecute()) {
				result = command;
				break;
			}
		}

		return result;
	}

	private Command getConnectionCreationCommand(EditPart sourceEditPart, EditPart targetEditPart, IElementType elementType) {
		Command result = null;

		String hint = (elementType instanceof IHintedType) ? ((IHintedType) elementType).getSemanticHint() : null;
		// Don't attempt to create relationship "nodes" like the DependencyNode or AssociationNode
		if ((hint != null) && Integer.parseInt(hint) >= 4000) {
			CreateConnectionViewAndElementRequest request = new CreateConnectionViewAndElementRequest(elementType, hint, editor.getPreferencesHint());
			request.setType(RequestConstants.REQ_CONNECTION_START);
			request.setLocation(new Point(0, 0));

			Command command = sourceEditPart.getCommand(request);
			if ((command != null) && command.canExecute()) {
				request.setSourceEditPart(sourceEditPart);
				request.setTargetEditPart(targetEditPart);
				request.setType(RequestConstants.REQ_CONNECTION_END);
				request.setLocation(new Point(0, 0));

				result = targetEditPart.getCommand(request);
			}
		}

		return result;
	}

	/**
	 * Simply removes a semantic {@code element} from the model.
	 * Relies on canonical edit policy to remove the notation view.
	 */
	protected void remove(EObject element) {
		execute(RemoveCommand.create(editor.getEditingDomain(), element.eContainer(), element.eContainmentFeature(), element));
	}

	/**
	 * Uses the edit-service {@linkplain #DestroyElementRequest destroy} command to effect deletion of the semantic {@code element} and all of its views. So, not a canonical scenario, but intended to regression-test this behaviour
	 * in a canonical context.
	 */
	protected void removeWithView(EObject element) {
		IElementEditService service = ElementEditServiceUtils.getCommandProvider(element.eContainer());
		ICommand command = service.getEditCommand(new DestroyElementRequest(element, false));
		assertThat("No command provided to delete " + label(element), command, notNullValue());
		assertThat("Cannot execute command to delete " + label(element), command.canExecute(), is(true));
		execute(command);
	}

	protected void delete(EditPart editPart) {
		Command command = editPart.getCommand(new GroupRequest(RequestConstants.REQ_DELETE));
		assertThat("No view deletion command provided", command, notNullValue());
		assertThat("Cannot execute view deletion command", command.canExecute(), is(true));
		execute(command);
	}

	protected String label(EObject object) {
		String result;

		if (object instanceof ENamedElement) {
			result = ((UMLUtil.getQualifiedName((ENamedElement) object, NamedElement.SEPARATOR)));
		} else {
			IItemLabelProvider labels = (IItemLabelProvider) adapterFactory.adapt(object, IItemLabelProvider.class);
			result = (labels == null) ? String.valueOf(object) : labels.getText(object);
		}

		return result;
	}

	protected View getView(EObject object) {
		IGraphicalEditPart editPart = getEditPart(object);
		if (editPart == null) {
			// Maybe it's an edge
			editPart = getConnectionEditPart(object);
		}
		return (editPart == null) ? null : editPart.getNotationView();
	}

	protected View requireView(EObject object) {
		View result = getView(object);
		assertThat("No view for " + label(object), result, notNullValue());
		return result;
	}

	protected void assertNoView(EObject object) {
		View view = getView(object);
		assertThat("View exists for " + label(object), view, nullValue());
	}

	protected Map<EObject, View> getViews(Iterable<? extends EObject> objects) {
		Map<EObject, View> result = Maps.newHashMap();

		for (EObject object : objects) {
			IGraphicalEditPart editPart = getEditPart(object);
			if (editPart == null) {
				// Maybe it's an edge
				editPart = getConnectionEditPart(object);
			}
			if ((editPart != null) && (editPart.getNotationView() != null)) {
				result.put(object, editPart.getNotationView());
			}
		}

		return result;
	}

	protected Map<EObject, View> getViews(EObject first, EObject second, EObject... rest) {
		return getViews(Lists.asList(first, second, rest));
	}

	protected Map<EObject, View> requireViews(Iterable<? extends EObject> objects) {
		Map<EObject, View> result = Maps.newHashMap();

		for (EObject object : objects) {
			result.put(object, requireView(object));
		}

		return result;
	}

	protected Map<EObject, View> requireViews(EObject first, EObject second, EObject... rest) {
		return requireViews(Lists.asList(first, second, rest));
	}

	protected void assertNoViews(Iterable<? extends EObject> objects) {
		Map<EObject, View> views = getViews(objects);

		if (!views.isEmpty()) {
			fail("View exists for " + label(Iterables.getFirst(views.keySet(), null)));
		}
	}

	protected void assertNoViews(EObject first, EObject second, EObject... rest) {
		assertNoViews(Lists.asList(first, second, rest));
	}

	protected void assertAttached(EObject element) {
		assertThat("Model does not contain " + label(element), element.eResource(), notNullValue());
	}

	protected void assertAttached(Iterable<? extends EObject> elements) {
		for (EObject next : elements) {
			assertAttached(next);
		}
	}

	protected void assertAttached(EObject first, EObject second, EObject... rest) {
		assertAttached(Lists.asList(first, second, rest));
	}

	protected void assertDetached(EObject element) {
		assertThat("Model must not contain " + label(element), element.eResource(), nullValue());
	}

	protected void assertDetached(Iterable<? extends EObject> elements) {
		for (EObject next : elements) {
			assertDetached(next);
		}
	}

	protected void assertDetached(EObject first, EObject second, EObject... rest) {
		assertDetached(Lists.asList(first, second, rest));
	}

	//
	// Nested types
	//

	@Retention(RetentionPolicy.RUNTIME)
	@Target({ ElementType.TYPE, ElementType.METHOD })
	protected @interface NeedsUIEvents {
		// Empty
	}

	private class AnnotationRule extends TestWatcher {
		@Override
		protected void starting(Description description) {
			needUIEvents = JUnitUtils.getAnnotation(description, NeedsUIEvents.class) != null;
		}
	}
}

Back to the top