Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 23d2b03fe0476e924ab001d968f7edf81179a5b5 (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
/*******************************************************************************
 * Copyright (c) 2011 - 2015 Wind River Systems, Inc. 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:
 * Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.tcf.te.ui.terminals.types;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.tcf.te.ui.terminals.activator.UIPlugin;
import org.eclipse.tcf.te.ui.terminals.interfaces.IConnectorType;
import org.eclipse.tcf.te.ui.terminals.nls.Messages;

/**
 * Terminal connector type extension point manager implementation.
 */
public class ConnectorManager {
	// Flag to mark the extension point manager initialized (extensions loaded).
	private boolean initialized = false;

	// The map containing all loaded contributions
	private final Map<String, Proxy> extensionsMap = new HashMap<String, Proxy>();

	// The extension point comparator
	private ExtensionPointComparator comparator = null;

	/**
	 * Executable extension proxy implementation.
	 */
	/* default */ static class Proxy {
		// The extension instance. Created on first access
		private IConnectorType instance;
		// The configuration element
		private final IConfigurationElement element;
		// The unique id of the extension.
		private String id;

		/**
		 * Constructor.
		 *
		 * @param element The configuration element. Must not be <code>null</code>.
		 * @throws CoreException In case the configuration element attribute <i>id</i> is <code>null</code> or empty.
		 */
		public Proxy(IConfigurationElement element) throws CoreException {
			Assert.isNotNull(element);
			this.element = element;

			// Extract the extension attributes
			id = element.getAttribute("id"); //$NON-NLS-1$
			if (id == null || id.trim().length() == 0) {
				throw new CoreException(new Status(IStatus.ERROR,
						UIPlugin.getUniqueIdentifier(),
						0,
						NLS.bind(Messages.Extension_error_missingRequiredAttribute, "id", element.getContributor().getName()), //$NON-NLS-1$
						null));
			}

			instance = null;
		}

		/**
		 * Returns the extensions unique id.
		 *
		 * @return The unique id.
		 */
		public String getId() {
			return id;
		}

		/**
		 * Returns the configuration element for this extension.
		 *
		 * @return The configuration element.
		 */
		public IConfigurationElement getConfigurationElement() {
			return element;
		}

		/**
		 * Returns the terminal connector type class instance. The contributing
		 * plug-in will be activated if not yet activated anyway.
		 *
		 * @return The extension class instance or <code>null</code> if the instantiation fails.
		 */
		public IConnectorType getInstance() {
			if (instance == null) instance = newInstance();
			return instance;
		}

		/**
		 * Returns always a new terminal connector type class instance which is different
		 * to what {@link #getInstance()} would return.
		 *
		 * @return A new extension class instance or <code>null</code> if the instantiation fails.
		 */
	    public IConnectorType newInstance() {
			IConfigurationElement element = getConfigurationElement();
			Assert.isNotNull(element);

			// The "class" to load can be specified either as attribute or as child element
			if (element.getAttribute("class") != null || element.getChildren("class").length > 0) { //$NON-NLS-1$ //$NON-NLS-2$
				try {
					return (IConnectorType)element.createExecutableExtension("class"); //$NON-NLS-1$
				} catch (Exception e) {
					// Possible exceptions: CoreException, ClassCastException.
					Platform.getLog(UIPlugin.getDefault().getBundle()).log(new Status(IStatus.ERROR,
									UIPlugin.getUniqueIdentifier(),
									NLS.bind(Messages.Extension_error_invalidExtensionPoint, element.getDeclaringExtension().getUniqueIdentifier()), e));
				}
			}
			return null;
		}

		/* (non-Javadoc)
		 * @see java.lang.Object#equals(java.lang.Object)
		 */
		@Override
		public boolean equals(Object obj) {
			// Proxies are equal if they have encapsulate an element
			// with the same unique id
			if (obj instanceof Proxy) {
				return getId().equals(((Proxy)obj).getId());
			}
			return super.equals(obj);
		}

		/* (non-Javadoc)
		 * @see java.lang.Object#hashCode()
		 */
		@Override
		public int hashCode() {
			// The hash code of a proxy is the one from the id
			return getId().hashCode();
		}
	}

	/**
	 * Extension point comparator implementation.
	 * <p>
	 * The comparator assure that extension are read in a predictable order.
	 * <p>
	 * The order of the extensions is defined as following:<br>
	 * <ul><li>Extensions contributed by our own plug-ins (<code>org.eclipse.tcf.te.*</code>)
	 *         in ascending alphabetic order and</li>
	 *     <li>Extensions contributed by any other plug-in in ascending alphabetic order.</li>
	 *     <li>Extensions contributed by the same plug-in in ascending alphabetic order by the
	 *         extensions unique id</li>
	 */
	/* default */ static class ExtensionPointComparator implements Comparator<IExtension> {
		private final static String OWN_PLUGINS_PATTERN = "org.eclipse.tcf.te."; //$NON-NLS-1$

		/* (non-Javadoc)
		 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
		 */
		@Override
	    public int compare(IExtension o1, IExtension o2) {
			// We ignore any comparisation with null and
			if (o1 == null || o2 == null) return 0;
			// Check if it is the exact same element
			if (o1 == o2) return 0;

			// The extensions are compared by the unique id of the contributing plug-in first
			String contributor1 = o1.getContributor().getName();
			String contributor2 = o2.getContributor().getName();

			// Contributions from our own plug-ins comes before 3rdParty plug-ins
			if (contributor1.startsWith(OWN_PLUGINS_PATTERN) && !contributor2.startsWith(OWN_PLUGINS_PATTERN))
				return -1;
			if (!contributor1.startsWith(OWN_PLUGINS_PATTERN) && contributor2.startsWith(OWN_PLUGINS_PATTERN))
				return 1;
			if (contributor1.startsWith(OWN_PLUGINS_PATTERN) && contributor2.startsWith(OWN_PLUGINS_PATTERN)) {
				int value = contributor1.compareTo(contributor2);
				// Within the same plug-in, the extension are sorted by their unique id (if available)
				if (value == 0 && o1.getUniqueIdentifier() != null && o2.getUniqueIdentifier() != null)
					return o1.getUniqueIdentifier().compareTo(o2.getUniqueIdentifier());
				// Otherwise, just return the comparisation result from the contributors
				return value;
			}

			// Contributions from all other plug-ins are sorted alphabetical
			int value = contributor1.compareTo(contributor2);
			// Within the same plug-in, the extension are sorted by their unique id (if available)
			if (value == 0 && o1.getUniqueIdentifier() != null && o2.getUniqueIdentifier() != null)
				return o1.getUniqueIdentifier().compareTo(o2.getUniqueIdentifier());
			// Otherwise, just return the comparisation result from the contributors
			return value;
		}

	}

	/*
	 * Thread save singleton instance creation.
	 */
	private static class LazyInstanceHolder {
		public static ConnectorManager instance = new ConnectorManager();
	}

	/**
	 * Returns the singleton instance for the terminal connector type extension point manager.
	 */
	public static ConnectorManager getInstance() {
		return LazyInstanceHolder.instance;
	}

	/**
	 * Constructor.
	 */
	ConnectorManager() {
		super();
	}

	/**
	 * Returns the list of all contributed terminal connector types.
	 *
	 * @param unique If <code>true</code>, the method returns new instances for each
	 *               contributed terminal connector type.
	 *
	 * @return The list of contributed terminal connector types, or an empty array.
	 */
	public IConnectorType[] getConnectorTypes(boolean unique) {
		List<IConnectorType> contributions = new ArrayList<IConnectorType>();
		for (Proxy connectorType : getExtensions().values()) {
			IConnectorType instance = unique ? connectorType.newInstance() : connectorType.getInstance();
			if (instance != null && !contributions.contains(instance)) {
				contributions.add(instance);
			}
		}

		return contributions.toArray(new IConnectorType[contributions.size()]);
	}

	/**
	 * Returns the terminal connector type identified by its unique id. If no terminal
	 * connector type with the specified id is registered, <code>null</code> is returned.
	 *
	 * @param id The unique id of the terminal connector type or <code>null</code>
	 * @param unique If <code>true</code>, the method returns new instances of the terminal connector type contribution.
	 *
	 * @return The terminal connector type instance or <code>null</code>.
	 */
	public IConnectorType getConnectorType(String id, boolean unique) {
		IConnectorType contribution = null;
		if (getExtensions().containsKey(id)) {
			Proxy proxy = getExtensions().get(id);
			// Get the extension instance
			contribution = unique ? proxy.newInstance() : proxy.getInstance();
		}

		return contribution;
	}

	/**
	 * Returns the map of managed extensions. If not loaded before,
	 * this methods trigger the loading of the extensions to the managed
	 * extension point.
	 *
	 * @return The map of extensions.
	 */
	protected Map<String, Proxy> getExtensions() {
		// Load and store the extensions thread-safe!
		synchronized (extensionsMap) {
			if (!initialized) { loadExtensions(); initialized = true; }
		}
		return extensionsMap;
	}

	/**
	 * Returns the extension point comparator instance. If not available,
	 * {@link #doCreateExtensionPointComparator()} is called to create a new instance.
	 *
	 * @return The extension point comparator or <code>null</code> if the instance creation fails.
	 */
	protected final ExtensionPointComparator getExtensionPointComparator() {
		if (comparator == null) {
			comparator = new ExtensionPointComparator();
		}
		return comparator;
	}

	/**
	 * Returns the extensions of the specified extension point sorted.
	 * <p>
	 * For the order of the extensions, see {@link ExtensionPointComparator}.
	 *
	 * @param point The extension point. Must not be <code>null</code>.
	 * @return The extensions in sorted order or an empty array if the extension point has no extensions.
	 */
	protected IExtension[] getExtensionsSorted(IExtensionPoint point) {
		Assert.isNotNull(point);

		List<IExtension> extensions = new ArrayList<IExtension>(Arrays.asList(point.getExtensions()));
		if (extensions.size() > 0) {
			Collections.sort(extensions, getExtensionPointComparator());
		}

		return extensions.toArray(new IExtension[extensions.size()]);
	}

	/**
	 * Loads the extensions for the managed extension point.
	 */
	protected void loadExtensions() {
		// If already initialized, this method will do nothing.
		if (initialized)  return;

		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IExtensionPoint point = registry.getExtensionPoint("org.eclipse.tcf.te.ui.terminals.connectorTypes"); //$NON-NLS-1$
		if (point != null) {
			IExtension[] extensions = getExtensionsSorted(point);
			for (IExtension extension : extensions) {
				IConfigurationElement[] elements = extension.getConfigurationElements();
				for (IConfigurationElement element : elements) {
					if ("connectorType".equals(element.getName())) { //$NON-NLS-1$
						try {
							Proxy candidate = new Proxy(element);
							if (candidate.getId() != null) {
								// If no extension with this id had been registered before, register now.
								if (!extensionsMap.containsKey(candidate.getId())) {
									extensionsMap.put(candidate.getId(), candidate);
								}
								else {
									throw new CoreException(new Status(IStatus.ERROR,
											UIPlugin.getUniqueIdentifier(),
											0,
											NLS.bind(Messages.Extension_error_duplicateExtension, candidate.getId(), element.getContributor().getName()),
											null));
								}
							} else {
								throw new CoreException(new Status(IStatus.ERROR,
										UIPlugin.getUniqueIdentifier(),
										0,
										NLS.bind(Messages.Extension_error_missingRequiredAttribute, "id", element.getAttribute("label")), //$NON-NLS-1$ //$NON-NLS-2$
										null));
							}
						} catch (CoreException e) {
							Platform.getLog(UIPlugin.getDefault().getBundle()).log(new Status(IStatus.ERROR,
											UIPlugin.getUniqueIdentifier(),
											NLS.bind(Messages.Extension_error_invalidExtensionPoint, element.getDeclaringExtension().getUniqueIdentifier()), e));
						}
					}
				}
			}
		}
	}
}

Back to the top