Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 8108ce73fdb98dc6e6b50688dc554cbc25820a48 (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
/*
 * Copyright (c) 2014, 2016 CEA, 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 (CEA) - Initial API and implementation
 *   Christian W. Damus - bugs 463631, 485220
 *
 */
package org.eclipse.papyrus.infra.ui.internal.emf.readonly.handlers;

import static org.eclipse.papyrus.infra.core.resource.ReadOnlyAxis.discretionAxes;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeThat;

import java.util.Collections;
import java.util.Set;

import org.eclipse.core.commands.operations.IOperationHistory;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.IWorkspaceCommandStack;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.notation.NotationPackage;
import org.eclipse.papyrus.infra.core.resource.EditingDomainServiceFactory;
import org.eclipse.papyrus.infra.core.resource.ModelSet;
import org.eclipse.papyrus.infra.core.resource.ModelsReader;
import org.eclipse.papyrus.infra.core.services.ServiceDescriptor;
import org.eclipse.papyrus.infra.core.services.ServiceDescriptor.ServiceTypeKind;
import org.eclipse.papyrus.infra.core.services.ServiceStartKind;
import org.eclipse.papyrus.infra.core.services.ServicesRegistry;
import org.eclipse.papyrus.infra.emf.readonly.internal.ControlledResourceTracker;
import org.eclipse.papyrus.infra.services.controlmode.ControlModeManager;
import org.eclipse.papyrus.infra.services.controlmode.ControlModeRequest;
import org.eclipse.papyrus.junit.framework.classification.tests.AbstractPapyrusTest;
import org.eclipse.uml2.common.util.CacheAdapter;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Model;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Property;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;


/**
 * Test suite for the {@link ReferencedModelReadOnlyHandler} class.
 */
public class ReferencedModelReadOnlyHandlerTest extends AbstractPapyrusTest {

	@Rule
	public final TestName testName = new TestName();

	private ServicesRegistry services;

	private TransactionalEditingDomain domain;

	private ReferencedModelReadOnlyHandler fixture;

	private IProject project;

	private Model model;

	private Package core;

	private Class person;

	public ReferencedModelReadOnlyHandlerTest() {
		super();
	}

	/**
	 * Test that cross-referenced workspace model resources are read-only by default.
	 */
	@Test
	public void testCrossReferencedWorkspaceModelElementsAreReadOnly() {
		Property ssn = person.getAttribute("ssn", null);
		assertReadOnly(ssn.getType());
	}

	/**
	 * Test that cross-referenced plug-in model resources are not handled by this read-only handler.
	 */
	@Test
	public void testCrossReferencedPluginModelElementsAreUnhandled() {
		Property lastName = person.getAttribute("lastName", null);
		assertNotReadOnly(lastName.getType());
	}

	/**
	 * Test that the main model resources are not considered as read-only by this read-only handler.
	 */
	@Test
	public void testMainModelElementsAreUnhandled() {
		Property ssn = person.getAttribute("ssn", null);
		assertNotReadOnly(ssn);
		assertLocalViewsNotReadOnly(ssn.getType());
	}

	/**
	 * Test that we can make cross-referenced workspace model resources writable.
	 */
	@Test
	public void testCrossReferencedWorkspaceModelElementsMadeWritable() {
		Property ssn = person.getAttribute("ssn", null);
		assumeReadOnly(ssn.getType());
		assertThat(fixture.canMakeWritable(discretionAxes(), ssn.getType()).or(false), is(true));
		assertThat(fixture.makeWritable(discretionAxes(), ssn.getType()).or(false), is(true));
		assertNotReadOnly(ssn.getType());
		assertNotReadOnly(person.getAttribute("registered", null).getType());
	}

	/**
	 * Test that the sub-model units of the main model resources are not considered as read-only by this read-only handler.
	 */
	@Test
	public void testSubModelElementsAreUnhandled() {
		control(core);

		Property ssn = person.getAttribute("ssn", null);
		assertNotReadOnly(ssn);
		assertLocalViewsNotReadOnly(ssn.getType());
	}

	/**
	 * Test that a referenced resource is not considered read-only if it does not exist, because in that case it couldn't
	 * possibly be subject to conflicting edits in some other editor.
	 */
	@Test
	public void testNonExistentResourceIsUnhandled() {
		Property ssn = person.getAttribute("ssn", null);

		Resource referenced = ssn.getType().eResource();

		// Don't use the URIConverter delete API for this
		IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(referenced.getURI().toPlatformString(true)));
		assertThat(file.exists(), is(true));
		try {
			file.delete(true, null);
		} catch (CoreException e) {
			e.printStackTrace();
			fail("Failed to delete referenced resource's underlying file: " + e.getLocalizedMessage());
		}

		assertNotReadOnly(ssn.getType());
	}

	/**
	 * Test that we do not get confused by clients that pass object URIs (including fragments) into the read-only handler API,
	 * resulting in thinking that an object in a writable resource is read-only because its file-extension-trimmed URI doesn't
	 * match the resource's.
	 */
	@Test
	public void testObjectURIsWithFragment() {
		Property ssn = person.getAttribute("ssn", null);
		URI uri = EcoreUtil.getURI(ssn);
		assertThat(fixture.anyReadOnly(discretionAxes(), new URI[] { uri }).or(false), is(false));
		assertThat(fixture.canMakeWritable(discretionAxes(), new URI[] { uri }).or(true), is(false));
	}

	//
	// Test framework
	//

	@Before
	public void createFixture() throws Exception {
		createProject();
		createServiceRegistry();

		domain = services.getService(TransactionalEditingDomain.class);
		fixture = new ReferencedModelReadOnlyHandler(domain);
		fixture.setInteractive(false);

		Resource res = importModel();
		saveModels();

		model = (Model) res.getContents().get(0);
		core = model.getNestedPackage("core");
		person = (Class) core.getOwnedType("Person");
	}

	protected void createProject() throws Exception {
		project = ResourcesPlugin.getWorkspace().getRoot().getProject(testName.getMethodName());
		if (!project.exists()) {
			project.create(null);
		}
		if (!project.isOpen()) {
			project.open(null);
		}
	}

	protected void createServiceRegistry() throws Exception {
		services = new ServicesRegistry();
		services.add(ModelSet.class, 10, new ModelSet());

		ServiceDescriptor desc = new ServiceDescriptor(TransactionalEditingDomain.class, EditingDomainServiceFactory.class.getName(), ServiceStartKind.STARTUP, 10, Collections.singletonList(ModelSet.class.getName()));
		desc.setServiceTypeKind(ServiceTypeKind.serviceFactory);
		desc.setClassBundleID(org.eclipse.papyrus.infra.core.Activator.PLUGIN_ID);
		services.add(desc);

		services.startRegistry();
	}

	@After
	public void destroyFixture() throws Exception {
		try {
			project.delete(true, true, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		ResourceSet rset = domain.getResourceSet();

		model = null;
		core = null;
		person = null;

		domain.dispose();
		domain = null;
		fixture = null;

		for (Resource next : rset.getResources()) {
			next.unload();
			next.eAdapters().clear();
		}

		rset.getResources().clear();
		rset.eAdapters().clear();

		services.disposeRegistry();
	}

	Resource importModel() throws Exception {
		ModelSet rset = services.getService(ModelSet.class);

		importModel(rset, "referencing");
		importModel(rset, "referenced");

		// Set the ModelSet's main URI and initialize it
		URI mainURI = URI.createPlatformResourceURI(String.format("%s/%s", project.getName(), "referencing"), true);
		new ModelsReader().readModel(rset);
		rset.loadModels(mainURI);

		return rset.getResource(mainURI.appendFileExtension("uml"), false);
	}

	void importModel(ModelSet rset, String name) throws Exception {
		URI source = URI.createPlatformPluginURI("org.eclipse.papyrus.infra.ui.emf.tests/resources/" + name, true);
		URI destination = URI.createPlatformResourceURI(project.getName(), true);

		for (String component : ImmutableList.of("uml", "notation", "di")) {
			Resource res = rset.getResource(source.appendFileExtension(component), true);
			EcoreUtil.resolveAll(res);
			res.setURI(destination.appendSegment(res.getURI().lastSegment()));
		}
	}

	void saveModels() throws Exception {
		for (Resource next : services.getService(ModelSet.class).getResources()) {
			if (next.getURI().isPlatformResource()) {
				next.save(null);
			}
		}
	}

	void control(NamedElement element) {
		URI unit = element.eResource().getURI().trimSegments(1).appendSegment("units").appendSegment(URI.encodeSegment(element.getName() + ".uml", true));
		execute(ControlModeManager.getInstance().getControlCommand(new ControlModeRequest(domain, element, unit)));

		assertThat("Controlling the unit failed", ((InternalEObject) element).eDirectResource(), notNullValue());

		try {
			saveModels();
		} catch (Exception e) {
			e.printStackTrace();
			fail("Failed to save sub-model units: " + e.getLocalizedMessage());
		}
	}

	void execute(ICommand command) {
		IOperationHistory history = ((IWorkspaceCommandStack) domain.getCommandStack()).getOperationHistory();

		try {
			history.execute(command, null, null);
		} catch (Exception e) {
			e.printStackTrace();
			fail("Failed to execute command: " + e.getLocalizedMessage());
		}
	}

	void assertReadOnly(EObject object) {
		Optional<Boolean> status = fixture.isReadOnly(discretionAxes(), object);
		assertThat("Not read-only", status.or(false), is(true));
	}

	void assertNotReadOnly(EObject object) {
		Optional<Boolean> status = fixture.isReadOnly(discretionAxes(), object);
		assertThat("Should not be either read-only or definitely writable", status.isPresent(), is(false));
	}

	void assumeReadOnly(EObject object) {
		Optional<Boolean> status = fixture.isReadOnly(discretionAxes(), object);
		assumeThat("Not read-only", status.or(false), is(true));
	}

	void assertLocalViewsNotReadOnly(EObject object) {
		boolean foundSomeLocalViews = false;

		for (EStructuralFeature.Setting setting : CacheAdapter.getCacheAdapter(object).getNonNavigableInverseReferences(object)) {
			if (setting.getEStructuralFeature() == NotationPackage.Literals.VIEW__ELEMENT) {
				EObject view = setting.getEObject();
				Set<URI> uris = ControlledResourceTracker.getInstance(domain).getRootResourceURIs(view.eResource().getURI());
				assertThat(uris.size(), is(1));
				if (Iterables.getOnlyElement(uris).trimFileExtension().lastSegment().equals("referencing")) {
					foundSomeLocalViews = true;
					assertNotReadOnly(view);
				}
			}
		}

		assertThat("No local views of the object found", foundSomeLocalViews, is(true));
	}
}

Back to the top