Skip to main content
summaryrefslogtreecommitdiffstats
blob: 0722f8daa7af85189327c66abbd5604e70518bac (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
/*******************************************************************************
 * Copyright (c) 2005 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.core.internal.registry.osgi;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.ResourceBundle;
import javax.xml.parsers.SAXParserFactory;
import org.eclipse.core.internal.registry.*;
import org.eclipse.core.internal.runtime.ResourceTranslator;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.spi.RegistryStrategy;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

/**
 * The registry strategy that can be used in OSGi world. It provides the following functionality:
 * 
 *  - Event scheduling is done using Eclipse job scheduling mechanism
 *  - Translation is done with Equinox ResourceTranslator
 *  - Uses OSGi bundles for namespace resolution (contributors: plugins and fragments)
 *  - Registry is filled with information stored in plugin.xml / fragment.xml of OSGi bundles
 *  - Uses bunlde-based class loading to create executable extensions
 *  - Performs registry validation based on the time stamps of the plugin.xml / fragment.xml files
 *  - XML parser is obtained via an OSGi service
 *  
 * @see RegistryFactory#setRegistryProvider(IRegistryProvider)
 * @since org.eclipse.equinox.registry 1.0
 */

public class RegistryStrategyOSGI extends RegistryStrategy {

	/**
	 * Registry access key
	 */
	private Object token;

	/**
	 * Debug extension registry
	 */
	protected boolean DEBUG;

	/**
	 * Debug extension registry events
	 */
	protected boolean DEBUG_REGISTRY_EVENTS;

	/**
	 * Tracker for the XML parser service
	 */
	private ServiceTracker xmlTracker = null;

	/**
	 * @param theStorageDir - file system directory to store cache files; might be null
	 * @param cacheReadOnly - true: cache is read only; false: cache is read/write
	 * @param key - control key for the registry (should be the same key as used in 
	 * the RegistryManager#createExtensionRegistry() of this registry
	 */
	public RegistryStrategyOSGI(File theStorageDir, boolean cacheReadOnly, Object key) {
		super(theStorageDir, cacheReadOnly);
		token = key;
	}

	public boolean isModifiable() {
		return false; // Clients are not allowed to add information into this registry
	}

	public final String translate(String key, ResourceBundle resources) {
		return ResourceTranslator.getResourceString(null, key, resources);
	}

	//////////////////////////////////////////////////////////////////////////////////////////
	// Use Eclipse job scheduling mechanism

	private final static class ExtensionEventDispatcherJob extends Job {
		// an "identy rule" that forces extension events to be queued		
		private final static ISchedulingRule EXTENSION_EVENT_RULE = new ISchedulingRule() {
			public boolean contains(ISchedulingRule rule) {
				return rule == this;
			}

			public boolean isConflicting(ISchedulingRule rule) {
				return rule == this;
			}
		};
		private Map deltas;
		private Object[] listenerInfos;
		private Object registry;

		public ExtensionEventDispatcherJob(Object[] listenerInfos, Map deltas, Object registry) {
			// name not NL'd since it is a system job
			super("Registry event dispatcher"); //$NON-NLS-1$
			setSystem(true);
			this.listenerInfos = listenerInfos;
			this.deltas = deltas;
			this.registry = registry;
			// all extension event dispatching jobs use this rule
			setRule(EXTENSION_EVENT_RULE);
		}

		public IStatus run(IProgressMonitor monitor) {
			return RegistryStrategy.processChangeEvent(listenerInfos, deltas, registry);
		}
	}

	public final void scheduleChangeEvent(Object[] listeners, Map deltas, Object registry) {
		new ExtensionEventDispatcherJob(listeners, deltas, registry).schedule();
	}

	////////////////////////////////////////////////////////////////////////////////////////
	// Use OSGi bundles for namespace resolution (contributors: plugins and fragments)

	/**
	 * The default load factor for the bundle cache. 
	 */
	private static float DEFAULT_BUNDLECACHE_LOADFACTOR = 0.75f;

	/**
	 * The expected bundle cache size (calculated as a number of bundles divided 
	 * by the DEFAULT_BUNDLECACHE_LOADFACTOR). The bundle cache will be resized 
	 * automatically is this number is exceeded. 
	 */
	private static int DEFAULT_BUNDLECACHE_SIZE = 200;

	/**
	 * For performance, we cache mapping of IDs to Bundles.
	 * 
	 * We don't expect mapping to change during the runtime. (Or, in the OSGI terms,
	 * we don't expect bundle IDs to be reused during the Eclipse run.)
	 * The Bundle object is stored as a weak reference to facilitate GC
	 * in case the bundle was uninstalled during the Eclipse run.
	 */
	private ReferenceMap bundleMap = new ReferenceMap(ReferenceMap.SOFT, DEFAULT_BUNDLECACHE_SIZE, DEFAULT_BUNDLECACHE_LOADFACTOR);

	// String Id to OSGi Bundle conversion
	public Bundle getBundle(String id) {
		if (id == null)
			return null;
		long OSGiId;
		try {
			OSGiId = Long.parseLong(id);
		} catch (NumberFormatException e) {
			return null;
		}
		// We assume here that OSGI Id will fit into "int". As the number of 
		// registry elements themselves are expected to fit into "int", this
		// is a valid assumption for the time being.
		Bundle bundle = (Bundle) bundleMap.get((int) OSGiId);
		if (bundle != null)
			return bundle;
		bundle = Activator.getContext().getBundle(OSGiId);
		bundleMap.put((int) OSGiId, bundle);
		return bundle;
	}

	// Getting String Id from an OSGi Bundle
	static public String getId(Bundle bundle) {
		if (bundle == null)
			return null;
		return Long.toString(bundle.getBundleId());
	}

	private Bundle getNamespaceBundle(String contributingBundleId) {
		Bundle contributingBundle = getBundle(contributingBundleId);
		if (contributingBundle == null) // When restored from disk the underlying bundle may have been uninstalled
			throw new IllegalStateException("Internal error in extension registry. The bundle corresponding to this contribution has been uninstalled."); //$NON-NLS-1$
		if (OSGIUtils.getDefault().isFragment(contributingBundle)) {
			Bundle[] hosts = OSGIUtils.getDefault().getHosts(contributingBundle);
			if (hosts != null)
				return hosts[0];
		}
		return contributingBundle;
	}

	public String getNamespaceOwnerId(String contributorId) {
		if (contributorId == null)
			return null;
		Bundle namespaceBundle = getNamespaceBundle(contributorId);
		return getId(namespaceBundle);
	}

	public String getNamespace(String contributorId) {
		if (contributorId == null)
			return null;
		Bundle namespaceBundle = getNamespaceBundle(contributorId);
		if (namespaceBundle == null)
			return null;
		return namespaceBundle.getSymbolicName();
	}

	public String[] getNamespaceContributors(String namespace) {
		Bundle correspondingHost = OSGIUtils.getDefault().getBundle(namespace);
		if (correspondingHost == null)
			return new String[0];
		Bundle[] fragments = OSGIUtils.getDefault().getFragments(correspondingHost);
		if (fragments == null)
			return new String[] {getId(correspondingHost)};
		String[] result = new String[fragments.length + 1];
		for (int i = 0; i < fragments.length; i++) {
			result[i] = getId(fragments[i]);
		}
		result[fragments.length] = getId(correspondingHost);
		return result;
	}

	/////////////////////////////////////////////////////////////////////////////////////
	// Executable extensions: bundle-based class loading

	public Object createExecutableExtension(String pluginName, String namespaceOwnerId, String namespaceName, String className, Object initData, String propertyName, org.eclipse.core.runtime.IConfigurationElement confElement) throws CoreException {

		if (pluginName != null && !pluginName.equals("") && !pluginName.equals(namespaceName)) { //$NON-NLS-1$
			Bundle otherBundle = null;
			otherBundle = OSGIUtils.getDefault().getBundle(pluginName);
			return createExecutableExtension(otherBundle, className, initData, propertyName, confElement);
		}

		Bundle contributingBundle = getBundle(namespaceOwnerId);
		return createExecutableExtension(contributingBundle, className, initData, propertyName, confElement);
	}

	private Object createExecutableExtension(Bundle bundle, String className, Object initData, String propertyName, org.eclipse.core.runtime.IConfigurationElement confElement) throws CoreException {
		// load the requested class from this plugin
		Class classInstance = null;
		try {
			classInstance = bundle.loadClass(className);
		} catch (Exception e1) {
			throwException(NLS.bind(RegistryMessages.plugin_loadClassError, bundle.getSymbolicName(), className), e1);
		} catch (LinkageError e) {
			throwException(NLS.bind(RegistryMessages.plugin_loadClassError, bundle.getSymbolicName(), className), e);
		}

		// create a new instance
		Object result = null;
		try {
			result = classInstance.newInstance();
		} catch (Exception e) {
			throwException(NLS.bind(RegistryMessages.plugin_instantiateClassError, bundle.getSymbolicName(), className), e);
		}

		return result;
	}

	private void throwException(String message, Throwable exception) throws CoreException {
		throw new CoreException(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, IRegistryConstants.PLUGIN_ERROR, message, exception));
	}

	/////////////////////////////////////////////////////////////////////////////////////
	// Start / stop extra processing: adding bundle listener; fill registry if not filled from cache

	/**
	 * Listening to the bunlde events.
	 */
	private EclipseBundleListener pluginBundleListener = null;

	public void onStart(Object registry) {
		super.onStart(registry);
		if (!(registry instanceof ExtensionRegistry))
			return;
		ExtensionRegistry theRegistry = (ExtensionRegistry) registry;

		// register a listener to catch new bundle installations/resolutions.
		pluginBundleListener = new EclipseBundleListener(theRegistry, token);
		Activator.getContext().addBundleListener(pluginBundleListener);

		// populate the registry with all the currently installed bundles.
		// There is a small window here while processBundles is being
		// called where the pluginBundleListener may receive a BundleEvent 
		// to add/remove a bundle from the registry.  This is ok since
		// the registry is a synchronized object and will not add the
		// same bundle twice.
		if (!theRegistry.filledFromCache())
			pluginBundleListener.processBundles(Activator.getContext().getBundles());
	}

	public void onStop(Object registry) {
		if (pluginBundleListener != null)
			Activator.getContext().removeBundleListener(pluginBundleListener);
		if (xmlTracker != null) {
			xmlTracker.close();
			xmlTracker = null;
		}
		super.onStop(registry);
	}

	//////////////////////////////////////////////////////////////////////////////////////
	// Cache strategy

	public boolean cacheUse() {
		return !"true".equals(RegistryProperties.getProperty(IRegistryConstants.PROP_NO_REGISTRY_CACHE)); //$NON-NLS-1$
	}

	public boolean cacheLazyLoading() {
		return !("true".equalsIgnoreCase(RegistryProperties.getProperty(IRegistryConstants.PROP_NO_LAZY_CACHE_LOADING))); //$NON-NLS-1$
	}

	public long cacheComputeTimeStamp() {
		BundleContext context = Activator.getContext();
		if (context == null)
			return 0;
		// If the check config prop is false or not set then exit
		if (!"true".equalsIgnoreCase(context.getProperty(IRegistryConstants.PROP_CHECK_CONFIG))) //$NON-NLS-1$  
			return 0;
		Bundle[] allBundles = context.getBundles();
		long result = 0;
		for (int i = 0; i < allBundles.length; i++) {
			URL pluginManifest = allBundles[i].getEntry("plugin.xml"); //$NON-NLS-1$
			if (pluginManifest == null)
				pluginManifest = allBundles[i].getEntry("fragment.xml"); //$NON-NLS-1$
			if (pluginManifest == null)
				continue;
			try {
				URLConnection connection = pluginManifest.openConnection();
				result ^= connection.getLastModified() + allBundles[i].getBundleId();
			} catch (IOException e) {
				return 0;
			}
		}
		return result;
	}

	public SAXParserFactory getXMLParser() {
		if (xmlTracker == null) {
			xmlTracker = new ServiceTracker(Activator.getContext(), SAXParserFactory.class.getName(), null);
			xmlTracker.open();
		}
		return (SAXParserFactory) xmlTracker.getService();
	}

}

Back to the top