Skip to main content
summaryrefslogtreecommitdiffstats
blob: 89452d4e93dab721c9f35b32b474378b263559ad (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
/*******************************************************************************
 * Copyright (c) 2014, 2017 Obeo 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:
 *     Obeo - initial API and implementation
 *     Philip Langer - bug 516493
 *******************************************************************************/
package org.eclipse.emf.compare.ide.internal.utils;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import org.eclipse.core.runtime.ListenerList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.compare.internal.utils.DiffUtil;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.ExtendedMetaData;
import org.eclipse.emf.ecore.xmi.XMIException;
import org.eclipse.emf.ecore.xmi.XMLDefaultHandler;
import org.eclipse.emf.ecore.xmi.XMLHelper;
import org.eclipse.emf.ecore.xmi.XMLLoad;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.XMLHandler;
import org.eclipse.emf.ecore.xmi.impl.XMLParserPoolImpl;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

/**
 * This implementation of an XML parser pool will notify a list of {@link INamespaceDeclarationListener
 * namespace declaration listeners} of all namespaces declared in the parsed resource (xsi:schemalocation),
 * then a list of {@link IProxyCreationListener proxy creation listeners} of each and every proxy it sees
 * while loading an XML file as an EMF model.
 * 
 * @author <a href="mailto:laurent.goubet@obeo.fr">Laurent Goubet</a>
 */
public class NotifyingParserPool extends XMLParserPoolImpl {
	/** Only set containment reference values, ignore the rest. */
	protected final boolean containmentOnly;

	/** The list of parties interested by our proxies. */
	private ListenerList proxyListeners;

	/** The list of parties interested in the declaration of namespaces. */
	private ListenerList namespaceDeclarationListeners;

	/**
	 * Default constructor.
	 * 
	 * @param containmentOnly
	 *            only set containment reference values. The model will be mostly empty except for its
	 *            containment tree.
	 */
	public NotifyingParserPool(boolean containmentOnly) {
		super(false);
		this.proxyListeners = new ListenerList();
		this.namespaceDeclarationListeners = new ListenerList();
		this.containmentOnly = containmentOnly;
	}

	/** {@inheritDoc} */
	@Override
	public synchronized XMLDefaultHandler getDefaultHandler(XMLResource resource, XMLLoad xmlLoad,
			XMLHelper helper, Map<?, ?> options) {
		final NotifyingXMLHelper wrapper = new NotifyingXMLHelper(helper, containmentOnly);
		for (Object listener : proxyListeners.getListeners()) {
			wrapper.addProxyListener((IProxyCreationListener)listener);
		}
		final XMLDefaultHandler handler = createDefaultHandler(resource, xmlLoad, wrapper, options);
		final NamespaceDeclarationNotifyingXMLDefaultHandler handlerWrapper = new NamespaceDeclarationNotifyingXMLDefaultHandler(
				handler);
		for (Object listener : namespaceDeclarationListeners.getListeners()) {
			handlerWrapper.addNamespaceDeclarationListener((INamespaceDeclarationListener)listener);
		}
		// The helper may now have extendedMetadata that we'll need to keep
		// in case there is an unknown feature in the XML file
		// and the option to record the unknown features is set
		// See bug 490430
		Map<Object, Object> tmpMap = new HashMap<Object, Object>();
		tmpMap.putAll(options);
		ExtendedMetaData extendedMetaData = helper.getExtendedMetaData();
		if (extendedMetaData != null && !options.containsKey(XMLResource.OPTION_EXTENDED_META_DATA)) {
			tmpMap.put(XMLResource.OPTION_EXTENDED_META_DATA, extendedMetaData);
		}
		handlerWrapper.prepare(resource, wrapper, tmpMap);
		return handlerWrapper;
	}

	/**
	 * Create the default (unwrapped) XMLDefaultHandler. This is merely a call to <code>super</code> but can
	 * be sub-classed.
	 * 
	 * @param resource
	 *            The resource to load.
	 * @param xmlLoad
	 *            The XML load to pass on tho the handler.
	 * @param helper
	 *            The XML helper to pass on tho the handler.
	 * @param options
	 *            The load options for this resource.
	 * @return The created XMLDefaultHandler.
	 * @see #getDefaultHandler(XMLResource, XMLLoad, XMLHelper, Map)
	 */
	protected XMLDefaultHandler createDefaultHandler(XMLResource resource, XMLLoad xmlLoad, XMLHelper helper,
			Map<?, ?> options) {
		return super.getDefaultHandler(resource, xmlLoad, helper, options);
	}

	/**
	 * Add a proxy creation listener to this parser pool's list.
	 * 
	 * @param listener
	 *            The listener to add to this pool's list.
	 */
	public void addProxyListener(IProxyCreationListener listener) {
		proxyListeners.add(listener);
	}

	/**
	 * Remove a proxy creation listener from this parser pool's list.
	 * 
	 * @param listener
	 *            The listener to remove from this pool's list.
	 */
	public void removeProxyListener(IProxyCreationListener listener) {
		proxyListeners.remove(listener);
	}

	/**
	 * Add a namespace declaration listener to this parser pool's list.
	 * 
	 * @param listener
	 *            The listener to add to this pool's list.
	 */
	public void addNamespaceDeclarationListener(INamespaceDeclarationListener listener) {
		namespaceDeclarationListeners.add(listener);
	}

	/**
	 * Remove a namespace declaration listener from this parser pool's list.
	 * 
	 * @param listener
	 *            The listener to remove from this pool's list.
	 */
	public void removeNamespaceDeclarationListener(INamespaceDeclarationListener listener) {
		namespaceDeclarationListeners.remove(listener);
	}

	/**
	 * An XMLDefaultHandler that will notify interested {@link INamespaceDeclarationListener listeners} of its
	 * namespace declarations.
	 */
	private static class NamespaceDeclarationNotifyingXMLDefaultHandler extends ForwardingXMLDefaultHandler {
		/** The list of parties interested in the declaration of namespaces. */
		private ListenerList namespaceDeclarationListeners;

		/** <code>true</code> only when we're parsing the very first element. */
		private boolean isRoot;

		/** The helper currently in use by our delegate. */
		private XMLHelper delegateHelper;

		/**
		 * Constructs a wrapper given its delegate.
		 * 
		 * @param delegate
		 *            The delegate handler.
		 */
		NamespaceDeclarationNotifyingXMLDefaultHandler(XMLDefaultHandler delegate) {
			super(delegate);
			this.namespaceDeclarationListeners = new ListenerList();
		}

		@Override
		public void startDocument() throws SAXException {
			isRoot = true;
			super.startDocument();
		}

		@Override
		public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException {
			if (isRoot) {
				String xsiSchemaLocation = arg3.getValue(ExtendedMetaData.XSI_URI,
						XMLResource.SCHEMA_LOCATION);
				if (xsiSchemaLocation != null) {
					declareSchemaLocation(xsiSchemaLocation);
				}
				isRoot = false;
			}
			super.startElement(arg0, arg1, arg2, arg3);
		}

		@Override
		public void endElement(String arg0, String arg1, String arg2) throws SAXException {
			if (delegateHelper instanceof NotifyingXMLHelper) {
				((NotifyingXMLHelper)delegateHelper).checkProxies();
			}
			super.endElement(arg0, arg1, arg2);
		}

		@Override
		public void endDocument() throws SAXException {
			if (delegateHelper instanceof NotifyingXMLHelper) {
				((NotifyingXMLHelper)delegateHelper).checkProxies();
			}
			super.endDocument();
		}

		@Override
		public void prepare(XMLResource resource, XMLHelper helper, Map<?, ?> options) {
			super.prepare(resource, helper, options);
			delegateHelper = helper;
		}

		/**
		 * Add a namespace declaration listener to this helper's list.
		 * 
		 * @param listener
		 *            The listener to add to this helper's list.
		 */
		public void addNamespaceDeclarationListener(INamespaceDeclarationListener listener) {
			namespaceDeclarationListeners.add(listener);
		}

		/**
		 * We've read the headers of the resource to load. Notify our {@link #namespaceDeclarationListeners
		 * listeners} about the schema locations that can be found therein.
		 * 
		 * @param xsiSchemaLocation
		 *            The String of xsi:schemalocation declarations in the file.
		 */
		private void declareSchemaLocation(String xsiSchemaLocation) {
			StringTokenizer stringTokenizer = new StringTokenizer(xsiSchemaLocation, " "); //$NON-NLS-1$
			while (stringTokenizer.hasMoreTokens()) {
				String key = stringTokenizer.nextToken();
				if (stringTokenizer.hasMoreTokens()) {
					String value = stringTokenizer.nextToken();
					URI uri = URI.createURI(value);
					for (Object listener : namespaceDeclarationListeners.getListeners()) {
						((INamespaceDeclarationListener)listener).schemaLocationDeclared(key, uri);
					}
				}
			}
		}
	}

	/**
	 * An XMLHelper wrapper that's capable of notifying {@link IProxyCreationListener listeners}s about proxy
	 * creations.
	 */
	private static class NotifyingXMLHelper extends ForwardingXMLHelper {
		/** The list of parties interested by our proxy creations. */
		private final ListenerList proxyListeners;

		/** Only set containment reference values, ignore the rest. */
		private final boolean containmentOnly;

		/**
		 * Some EObjects are passed to us before their proxy URI is set. We'll keep track of these and check
		 * them afterwards.
		 */
		private Set<ProxyEntry> potentialProxies = new LinkedHashSet<ProxyEntry>();

		/**
		 * Constructs a wrapper given its delegate XMLHelper.
		 * 
		 * @param delegate
		 *            The delegate XMLHelper.
		 * @param containmentOnly
		 *            Only set containment reference values.
		 */
		NotifyingXMLHelper(XMLHelper delegate, boolean containmentOnly) {
			super(delegate);
			this.proxyListeners = new ListenerList();
			this.containmentOnly = containmentOnly;
		}

		@Override
		public void setValue(EObject eObject, EStructuralFeature feature, Object value, int position) {
			if (feature instanceof EReference) {
				boolean isContainment = feature instanceof EReference
						&& ((EReference)feature).isContainment();
				if (!containmentOnly || isContainment) {
					super.setValue(eObject, feature, value, position);
				}
				if (value instanceof EObject) {
					final EObject eObjectValue = (EObject)value;
					final ProxyEntry entry = new ProxyEntry(eObject, feature, eObjectValue, position);
					if (eObjectValue.eIsProxy()) {
						notifyProxy(entry);
					} else if (!isContainment) {
						potentialProxies.add(entry);
					}
				}
			} else if (!containmentOnly) {
				super.setValue(eObject, feature, value, position);
			}
		}

		/**
		 * Called by {@link XMLHandler} to set the values of the given many-valued forward reference. The
		 * target feature may already contain values resolved from backward references and set by
		 * {@link #setValue(EObject, EStructuralFeature, Object, int)}. The given reference also specifies the
		 * insertion indexes necessary to insert the new values at the correct positions.
		 * <p>
		 * Note that the super-implementation will throw an {@link ArrayIndexOutOfBoundsException} if the
		 * insertion indexes do not match the contents of the target feature, that is, if it contains too few
		 * elements.
		 * 
		 * @param reference
		 *            The reference to set
		 * @param location
		 *            The location
		 * @return An empty list if the reference must be ignored, and the result of the parent implementation
		 *         otherwise.
		 */
		@Override
		public List<XMIException> setManyReference(ManyReference reference, String location) {
			EStructuralFeature eStructuralFeature = reference.getFeature();
			boolean isContainment = DiffUtil.isContainmentReference(eStructuralFeature);
			if (!containmentOnly || isContainment) {
				return super.setManyReference(reference, location);
			}

			return Collections.emptyList();
		}

		/** Check the {@link #potentialProxies} list for {@link EObject#eIsProxy() actual proxies}. */
		public void checkProxies() {
			Iterator<ProxyEntry> candidateIterator = potentialProxies.iterator();
			while (candidateIterator.hasNext()) {
				final ProxyEntry candidate = candidateIterator.next();
				if (candidate.getValue().eIsProxy()) {
					notifyProxy(candidate);
				}
				candidateIterator.remove();
			}
		}

		/**
		 * Tells our registered listeners about a proxy we've found.
		 * 
		 * @param proxy
		 *            The proxy we found in the model.
		 */
		private void notifyProxy(ProxyEntry proxy) {
			for (Object listener : proxyListeners.getListeners()) {
				((IProxyCreationListener)listener).proxyCreated(getResource(), proxy.getEObject(),
						proxy.getFeature(), proxy.getValue(), proxy.getPosition());
			}
		}

		/**
		 * Add a proxy creation listener to this helper's list.
		 * 
		 * @param listener
		 *            The listener to add to this helper's list.
		 */
		public void addProxyListener(IProxyCreationListener listener) {
			proxyListeners.add(listener);
		}
	}

	/** Keeps track of a potential proxy as it was passed to us. */
	private static class ProxyEntry {
		/** The EObject which may reference a proxy. */
		private EObject eObject;

		/** Feature on which we've set a new EObject. */
		private EStructuralFeature feature;

		/** The actual object that may {@link EObject#eIsProxy() be a proxy}. */
		private EObject value;

		/** The position in {@link #feature} at which {@link #value} has been added. */
		private int position;

		/**
		 * Constructs our DTO given its content.
		 * 
		 * @param eObject
		 *            see {@link #eObject}.
		 * @param feature
		 *            see {@link #feature}.
		 * @param value
		 *            see {@link #value}.
		 * @param position
		 *            see {@link #position}.
		 */
		ProxyEntry(EObject eObject, EStructuralFeature feature, EObject value, int position) {
			this.eObject = eObject;
			this.feature = feature;
			this.value = value;
			this.position = position;
		}

		public EObject getEObject() {
			return eObject;
		}

		public EStructuralFeature getFeature() {
			return feature;
		}

		public EObject getValue() {
			return value;
		}

		public int getPosition() {
			return position;
		}
	}
}

Back to the top