Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 646fb5df22e25f50e2818e795b42d637faf0b1bd (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
/*****************************************************************************
 * Copyright (c) 2008 CEA LIST.
 *
 *    
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Cedric Dumoulin  Cedric.dumoulin@lifl.fr - Initial API and implementation
 *  Emilien Perico emilien.perico@atosorigin.com - manage loading strategies
 *
 *****************************************************************************/
package org.eclipse.papyrus.infra.core.resource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.impl.ResourceImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.WorkspaceEditingDomainFactory;
import org.eclipse.papyrus.infra.core.resource.additional.AdditionalResourcesModel;

/**
 * This class is used to manage a set of {@link IModel}.
 * 
 * <h2>>Usage</h2>
 * <ul>
 * <li>First, register associated model. A loader can be used.</li>
 * <li>Second, call load() or create()</li>
 * <li>Then, it is possible to get associated models</li>
 * <li>Finally, call save()</li>
 * </ul>
 * 
 * Please note that indirectly referenced models are loaded on demand. If a
 * model contains a cross reference towards another model (e.g. an import in
 * case of UML) the referenced resource does not appear initially in the set.
 * However, it is added once the referenced model is resolved.
 * 
 * TODO Modify ModelSetSnippet in order to inform them of model addition.
 * 
 * @author cedric dumoulin
 * 
 */
public class ModelSet extends ResourceSetImpl {

	/** The associated IModels. */
	private Map<String, IModel> models = new HashMap<String, IModel>();

	/** The snippets. */
	private ModelSetSnippetList snippets = new ModelSetSnippetList();

	private AdditionalResourcesModel additional = new AdditionalResourcesModel();

	/**
	 * The associated EditingDomain.
	 */
	private TransactionalEditingDomain transactionalEditingDomain;

	/**
	 * The filename path, without extension, used for action on models.
	 */
	private IPath filenameWithoutExtension;

	/**
	 * 
	 * Constructor.
	 * 
	 */
	public ModelSet() {
		registerModel(additional);
		this.setURIResourceMap(new HashMap<URI, Resource>());
		getLoadOptions().put(XMLResource.OPTION_DEFER_ATTACHMENT, true);
		getLoadOptions().put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION, true);
	}

	/**
	 * Register the specified model under its associated key. The key is defined
	 * in the model itself. It is usually the model type from
	 * (ModelPackage.eCONTENT_TYPE).
	 * 
	 * @param model
	 *        the model
	 */
	public void registerModel(IModel model) {
		models.put(model.getIdentifier(), model);
		model.init(this);
	}

	/**
	 * Get a model by its key. TODO throw an exception if not found.
	 * 
	 * @param key
	 *        the key
	 * @return the model
	 */
	public IModel getModel(String key) {
		return models.get(key);
	}

	/**
	 * Get a model by its key. TODO throw an exception if not found.
	 * 
	 * @param key
	 *        the key
	 * @return the model
	 * @throws NotFoundException
	 *         If no model is registered under the key.
	 */
	public IModel getModelChecked(String key) throws NotFoundException {
		IModel model = models.get(key);
		if(model == null)
			throw new NotFoundException("Can't find model for identifier '" + key + "'.");

		return model;
	}

	@Override
	public Resource getResource(URI uri, boolean loadOnDemand) {
		Resource r = super.getResource(uri, loadOnDemand);
		if(r instanceof ResourceImpl) {
			ResourceImpl impl = (ResourceImpl)r;
			impl.setTrackingModification(true);
			if(impl.getIntrinsicIDToEObjectMap() == null) {
				impl.setIntrinsicIDToEObjectMap(new HashMap<String, EObject>());
			}
		}
		return r;
	}

	/**
	 * Create the transactional editing domain.
	 * 
	 * @return the transactional editing domain
	 */
	public TransactionalEditingDomain getTransactionalEditingDomain() {
		transactionalEditingDomain = WorkspaceEditingDomainFactory.INSTANCE.getEditingDomain(this);

		if(transactionalEditingDomain == null) {
			transactionalEditingDomain = TransactionalEditingDomainManager.createTransactionalEditingDomain(this);
			// What for?
			transactionalEditingDomain.setID("SharedEditingDomain"); //$NON-NLS-1$
		}
		return transactionalEditingDomain;
	}

	/**
	 * @return the filenameWithoutExtension
	 */
	public IPath getFilenameWithoutExtension() {
		return filenameWithoutExtension;
	}

	/**
	 * @return the filenameWithoutExtension
	 * @throws BadStateException
	 */
	protected IPath getFilenameWithoutExtensionChecked() throws BadStateException {
		if(filenameWithoutExtension == null)
			throw new BadStateException("Path should be set prior calling any operations.");

		return filenameWithoutExtension;
	}

	/**
	 * @param filenameWithoutExtension
	 *        the filenameWithoutExtension to set
	 */
	protected void setFilenameWithoutExtension(IPath filenameWithoutExtension) {
		this.filenameWithoutExtension = filenameWithoutExtension;
	}

	/**
	 * Create all the associated models. This creates the models, regardless if
	 * they already exist.
	 * 
	 * @param newFile
	 *        The file from which path is extracted to create the new
	 *        resources
	 */
	public void createsModels(IFile newFile) {

		// Get the file name, without extension.
		filenameWithoutExtension = newFile.getFullPath().removeFileExtension();

		// Walk all registered models
		for(IModel model : models.values()) {
			model.createModel(filenameWithoutExtension);
		}

		// call snippets to allow them to do their stuff
		snippets.performStart(this);
	}

	/**
	 * Create the model specified by the identifiers. Other models are
	 * untouched, unless they are sharing something with specified models.
	 * 
	 * This creates the models, regardless if they already exist.
	 * 
	 * @param newFile
	 *        The file from which path is extracted to create the new
	 *        resources
	 */
	public void createsModels(ModelIdentifiers modelIdentifiers) {

		// Walk all registered models
		for(String modelId : modelIdentifiers) {
			IModel model = getModel(modelId);

			// Load models using the default path
			model.createModel(filenameWithoutExtension);
		}

		// call snippets to allow them to do their stuff
		// snippets.modelsAdded(modelIdentifiers);
	}

	/**
	 * Load only the specified model. ModelSetSnippets are not called. Model is
	 * loaded using the ModelSet Path.
	 * 
	 * @param modelIdentifier
	 *        the model identifier
	 * @param file
	 *        the file
	 * @return the i model
	 * @throws BadStateException
	 *         If the global path is not specified.
	 * @returns The loaded model.
	 */
	public IModel loadModel(String modelIdentifier) throws BadStateException {

		IModel model = getModel(modelIdentifier);
		model.loadModel(getFilenameWithoutExtensionChecked());

		return model;
	}

	/**
	 * Import only the specified model. ModelSetSnippets are not called.
	 * 
	 * @param modelIdentifier
	 *        the model identifier
	 * @param file
	 *        the file
	 * @return the i model
	 * @throws ModelException
	 * @returns The loaded model.
	 * @deprecated Use {@link #importModel(ModelIdentifier, IFile)}
	 */
	public IModel loadModel(String modelIdentifier, IFile file) throws ModelException {

		importModels(new ModelIdentifiers(modelIdentifier), file);

		return getModel(modelIdentifier);
	}

	/**
	 * Load all the associated models from a handle on one of the associated
	 * file.
	 * 
	 * @param file
	 *        The file to load (no matter the extension)
	 */
	public void loadModels(IFile file) throws ModelMultiException {

		// Get the file name, without extension.
		filenameWithoutExtension = file.getFullPath().removeFileExtension();

		ModelMultiException exceptions = null;

		// Walk all registered models
		for(IModel model : models.values()) {
			// Try to load each model. Catch exceptions in order to load other
			// models.
			try {
				model.loadModel(filenameWithoutExtension);
			} catch (Exception e) {
				// Record the exception
				if(exceptions == null) {

					exceptions = new ModelMultiException("Problems encountered while loading one of the models.");
				}
				exceptions.addException(model.getIdentifier(), e);
			}
		}

		// call snippets to allow them to do their stuff
		snippets.performStart(this);

		// Report exceptions if any
		if(exceptions != null)
			throw exceptions;
	}

	/**
	 * Import specified models into the ModelSet. The models are imported using
	 * the specified IFile. After import, the models are associated with the
	 * ModelSet Path.
	 * 
	 * @param modelIdentifiers
	 *        The model to import from the specified IFile.
	 * @param file
	 *        The IFile used to import the model.
	 * @throws ModelException
	 *         If an error occur during import.
	 */
	public void importModels(ModelIdentifiers modelIdentifiers, IFile file) throws ModelException {

		IPath path = file.getFullPath().removeFileExtension();
		// Walk all registered models
		for(String modelId : modelIdentifiers) {
			IModel model = getModel(modelId);

			// Load models using the default path
			model.importModel(path);
			if(filenameWithoutExtension != null)
				model.changeModelPath(filenameWithoutExtension);
		}
	}

	/**
	 * Import only the specified model. ModelSetSnippets are not called. An
	 * import can be performed after model are loaded. Normally, it should not
	 * be done before a model is loaded.
	 * 
	 * @param modelIdentifier
	 *        the model identifier
	 * @param file
	 *        the file
	 * @throws ModelException
	 * @returns The loaded model.
	 */
	public IModel importModel(String modelIdentifier, IFile file) throws ModelException {

		importModels(new ModelIdentifiers(modelIdentifier), file);

		return getModel(modelIdentifier);
	}

	/**
	 * Create models that are not already created or loaded.
	 */
	public void createMissingModels() throws ModelException {
		throw new UnsupportedOperationException("Not yet implemented");

	}

	/**
	 * Load models that are not already created or loaded.
	 */
	public void loadMissingModels() throws ModelException {
		throw new UnsupportedOperationException("Not yet implemented");

	}

	/**
	 * Save the resources.
	 * 
	 * @param monitor
	 *        The monitor.
	 * @throws IOException
	 *         IO Error.
	 */
	public void save(IProgressMonitor monitor) throws IOException {

		// Initialize monitor with the number of models
		Collection<IModel> modelList = models.values();
		monitor.beginTask("Saving resources", modelList.size());

		try {
			// Walk all registered models
			for(IModel model : modelList) {
				if(!(model instanceof AdditionalResourcesModel)) {
					model.saveModel();
					monitor.worked(1);
				}
			}
			additional.saveModel();
		} finally {
			monitor.done();
		}
	}

	/**
	 * The resources are already loaded, but we want to save them under another
	 * name.
	 * 
	 * @param path
	 *        the path
	 * @throws IOException
	 *         Signals that an I/O exception has occurred.
	 */
	public void saveAs(IPath path) throws IOException {

		// Get the file name, without extension.
		filenameWithoutExtension = path.removeFileExtension();

		// Walk all registered models
		for(IModel model : models.values()) {
			model.changeModelPath(filenameWithoutExtension);
		}

		// Save with new paths
		save(new NullProgressMonitor());
	}

	/**
	 * Unload all the resources. Do not disguard associated models.
	 */
	public void unload() {

		// call snippets to allow them to do their stuff
		snippets.performDispose(this);

		// Walk all registered models
		for(IModel model : models.values()) {
			if(!(model instanceof AdditionalResourcesModel)) {
				model.unload();
			}
		}
		additional.unload();

		// Unload remaining resources
		for(Iterator<Resource> iter = getResources().iterator(); iter.hasNext();) {
			iter.next().unload();
			iter.remove();
		}
	}

	/**
	 * Add a {@link IModelSetSnippet}. A snippet allows to add code that will
	 * perform additional operations on the ModelSet.
	 * 
	 * @param snippet
	 *        The snippet to add.
	 */
	public void addModelSetSnippet(IModelSetSnippet snippet) {
		snippets.add(snippet);
	}

	/**
	 * A list of {@link IModelSetSnippet}.
	 * 
	 * Used by Models to maintain their list of Snippets.
	 * 
	 * @author cedric dumoulin
	 * 
	 */
	public class ModelSetSnippetList extends ArrayList<IModelSetSnippet> {

		/** The Constant serialVersionUID. */
		private static final long serialVersionUID = 1L;

		/**
		 * Call the start method on all registered snippets.
		 * 
		 * @param modelsManager
		 *        The model that is starting
		 */
		public void performStart(ModelSet modelsManager) {
			for(IModelSetSnippet snippet : this) {
				snippet.start(modelsManager);
			}
		}

		/**
		 * Call the start method on all registered snippets.
		 * 
		 * @param modelsManager
		 *        The model that is stopping
		 */
		public void performDispose(ModelSet modelsManager) {
			for(IModelSetSnippet snippet : this) {
				snippet.dispose(modelsManager);
			}

		}
	}

	/**
	 * Check is a resource is additional in the resource set
	 * 
	 * @param uri
	 *        the specified URI of the resource
	 * @return true if it is an additional resource
	 */
	public boolean isAdditionalResource(URI uri) {
		if(uri != null) {
			String platformString = uri.trimFileExtension().toPlatformString(false);
			return ((platformString == null) || !getFilenameWithoutExtension().toString().equals(platformString.toString()));
		}
		return false;
	}

}

Back to the top