Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 9cbdf6400bb5c46db08d66c941e80d54adde8b44 (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
/*******************************************************************************
 * Copyright (c) 2006, 2007 IBM Corporation 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:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

package org.eclipse.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.internal.WorkbenchPlugin;
import org.osgi.framework.Bundle;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.util.tracker.ServiceTracker;

/**
 * Basic IWorkingSetElementAdapter implementation that allows plugins to decribe
 * simple declarative element adapters.
 * <p>
 * The executable extension format for this class is as follows:<br/>
 * <code>&lt;workingSet
 * elementAdapterClass="org.eclipse.ui.BasicWorkingSetElementAdapter:class1.to.adapt.to[;option1=value1][;option2=value2],class2.to.adapt.to[;option1=value1][;option2=value2],..."&gt;
 * ... &lt;/workingSet&gt;</code>
 * </p>
 * <p>
 * The valid options are:<br/>
 * <dl>
 * <dt>adapt</dt>
 * <dd>Values: <code>true</code> or <code>true</code>. Specifies whether
 * or not the platform {@link org.eclipse.core.runtime.IAdapterManager} and the
 * {@link org.eclipse.core.runtime.IAdaptable} interface should be consulted.</dd>
 * </dl>
 * </p>
 * 
 * Please see the {@link #adaptElements(IWorkingSet, IAdaptable[])} method for
 * details on behavior of this implementation.
 * 
 * @since 3.3
 */
public final class BasicWorkingSetElementAdapter implements
		IWorkingSetElementAdapter, IExecutableExtension {

	private class Type {
		private static final int NONE = 0;
		private static final int ADAPT = 1;
		String className;
		int flags;
	}

	private Type[] preferredTypes = new Type[0];

	private ServiceTracker packageTracker;

	/**
	 * When invoked this method will iterate over all classes specified as
	 * IExecutableExtension arguements to this class in order and compare with
	 * the elements. If the element is directly assignable to the provided class
	 * then it is added to the result array as is. If the class has specified
	 * "adapt=true" as an argument and there is an available adapter in the
	 * platform IAdapterManager then it is returned. Finally, if "adapt=true"
	 * and the class is already loaded (determined by inspecting exported
	 * bundles via the platform PackageAdmin) a direct query for the adapter is
	 * made on the object and if it is not <code>null</code> then it is
	 * returned.
	 * <p>
	 * A consequence of the above is that it is possible for this method to
	 * return differing results based on the state of bundles loaded within the
	 * system.
	 * </p>
	 * 
	 * @see org.eclipse.ui.IWorkingSetElementAdapter#adaptElements(org.eclipse.ui.IWorkingSet,
	 *      org.eclipse.core.runtime.IAdaptable[])
	 * @see org.eclipse.core.runtime.IAdapterManager#getAdapter(Object, String)
	 * @see org.osgi.service.packageadmin.PackageAdmin#getExportedPackage(String)
	 */
	public IAdaptable[] adaptElements(IWorkingSet ws, IAdaptable[] elements) {
		List adaptedElements = new ArrayList();
		for (int i = 0; i < elements.length; i++) {
			IAdaptable adaptable = adapt(elements[i]);
			if (adaptable != null)
				adaptedElements.add(adaptable);
		}

		return (IAdaptable[]) adaptedElements
				.toArray(new IAdaptable[adaptedElements.size()]);
	}

	/**
	 * Adapt the given adaptable. Compares the given adaptable against the list
	 * of desired types and returns the first type that generates a match.
	 * 
	 * @param adaptable
	 *            the adaptable to adapt
	 * @return the resultant adaptable. May be the same adaptable, a new
	 *         adaptable, or <code>null</code>.
	 */
	private IAdaptable adapt(IAdaptable adaptable) {
		for (int i = 0; i < preferredTypes.length; i++) {
			IAdaptable adaptedAdaptable = adapt(preferredTypes[i], adaptable);
			if (adaptedAdaptable != null)
				return adaptedAdaptable;
		}
		return null;
	}

	/**
	 * Adapt the given adaptable given the reference type.
	 * 
	 * @param type
	 *            the reference type
	 * @param adaptable
	 *            the adaptable to adapt
	 * @return the resultant adaptable. May be the same adaptable, a new
	 *         adaptable, or <code>null</code>.
	 */
	private IAdaptable adapt(Type type, IAdaptable adaptable) {
		IAdapterManager adapterManager = Platform.getAdapterManager();
		Class[] directClasses = adapterManager.computeClassOrder(adaptable
				.getClass());
		for (int i = 0; i < directClasses.length; i++) {
			Class clazz = directClasses[i];
			if (clazz.getName().equals(type.className))
				return adaptable;
		}

		if ((type.flags & Type.ADAPT) != 0) {
			Object adapted = adapterManager.getAdapter(adaptable,
					type.className);
			if (adapted instanceof IAdaptable)
				return (IAdaptable) adapted;

			PackageAdmin admin = getPackageAdmin();
			if (admin != null) {
				int lastDot = type.className.lastIndexOf('.');
				if (lastDot > 0) { // this lives in a package
					String packageName = type.className.substring(0, lastDot);
					ExportedPackage[] packages = admin
							.getExportedPackages(packageName);
					if (packages != null && packages.length == 1) {
						// if there is exactly one exporter of this
						// package
						// we can go further
						if (packages[0].getExportingBundle().getState() == Bundle.ACTIVE) {
							try {
								// if the bundle is loaded we can safely get the
								// class object and check for an adapter on the
								// object directly
								adapted = adaptable.getAdapter(packages[0]
										.getExportingBundle().loadClass(
												type.className));
								if (adapted instanceof IAdaptable)
									return (IAdaptable) adapted;

							} catch (ClassNotFoundException e) {
								WorkbenchPlugin.log(e);
							}
						}
					}
				}
			}
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IWorkingSetElementAdapter#dispose()
	 */
	public void dispose() {
		if (packageTracker != null)
			packageTracker.close();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement,
	 *      java.lang.String, java.lang.Object)
	 */
	public void setInitializationData(IConfigurationElement config,
			String propertyName, Object data) {

		if (data instanceof String) {
			List preferredTypes = new ArrayList(0);
			for (StringTokenizer toker = new StringTokenizer((String) data, ","); toker.hasMoreTokens();) {//$NON-NLS-1$
				String classNameAndOptions = toker.nextToken();
				Type record = new Type();
				parseOptions(classNameAndOptions, record);
				preferredTypes.add(record);
			}
			this.preferredTypes = (Type[]) preferredTypes
					.toArray(new Type[preferredTypes.size()]);
		}
	}

	/**
	 * Parse classname/option strings in the form:<br/>
	 * <code>some.package.Class[:option1=value1][:option2=value2]...
	 * 
	 * @param classNameAndOptions the class name and possibly options to parse
	 * @param record the record to fill
	 */
	private void parseOptions(String classNameAndOptions, Type record) {
		for (StringTokenizer toker = new StringTokenizer(classNameAndOptions,
				";"); toker.hasMoreTokens();) { //$NON-NLS-1$
			String token = toker.nextToken();
			if (record.className == null)
				record.className = token;
			else {
				for (StringTokenizer pair = new StringTokenizer(token, "="); pair.hasMoreTokens();) {//$NON-NLS-1$
					if (pair.countTokens() == 2) {
						String param = pair.nextToken();
						String value = pair.nextToken();
						if ("adapt".equals(param)) { //$NON-NLS-1$
							record.flags ^= "true".equals(value) ? Type.ADAPT : Type.NONE; //$NON-NLS-1$
						}
					}
				}
			}
		}
	}

	/**
	 * Prime the PackageAdmin service tracker and return the service (if
	 * available).
	 * 
	 * @return the PackageAdmin service or null if it is not available
	 */
	private PackageAdmin getPackageAdmin() {
		if (packageTracker == null) {
			packageTracker = new ServiceTracker(WorkbenchPlugin.getDefault()
					.getBundleContext(), PackageAdmin.class.getName(), null);
			packageTracker.open();
		}

		return (PackageAdmin) packageTracker.getService();
	}
}

Back to the top