Skip to main content
summaryrefslogtreecommitdiffstats
blob: 6d99cfbfd992a5a8ecd274b5d7dae67230568b49 (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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/*******************************************************************************
 * Copyright (c) 2003, 2006 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.osgi.framework.internal.core;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import org.eclipse.osgi.framework.adaptor.BundleData;
import org.eclipse.osgi.framework.adaptor.BundleWatcher;
import org.eclipse.osgi.framework.debug.Debug;
import org.eclipse.osgi.service.resolver.BundleDescription;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.*;

public class BundleHost extends AbstractBundle {

	/** 
	 * The BundleLoader proxy; a lightweight object that acts as a proxy
	 * to the BundleLoader and allows lazy creation of the BundleLoader object
	 */
	private BundleLoaderProxy proxy;

	/** The BundleContext that represents this Bundle and all of its fragments */
	protected BundleContextImpl context;

	/** The List of BundleFragments */
	protected BundleFragment[] fragments;

	public BundleHost(BundleData bundledata, Framework framework) throws BundleException {
		super(bundledata, framework);
		context = null;
		fragments = null;
	}

	/**
	 * Load the bundle.
	 */
	protected void load() {
		if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
			if ((state & (INSTALLED)) == 0) {
				Debug.println("Bundle.load called when state != INSTALLED: " + this); //$NON-NLS-1$
				Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
			}
			if (proxy != null) {
				Debug.println("Bundle.load called when proxy != null: " + this); //$NON-NLS-1$
				Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
			}
		}

		if (framework.isActive()) {
			SecurityManager sm = System.getSecurityManager();

			if (sm != null && framework.permissionAdmin != null) {
				domain = framework.permissionAdmin.createProtectionDomain(this);
			}

		}
		proxy = null;
	}

	/**
	 * Reload from a new bundle.
	 * This method must be called while holding the bundles lock.
	 *
	 * @param newBundle Dummy Bundle which contains new data.
	 * @return  true if an exported package is "in use". i.e. it has been imported by a bundle
	 */
	protected boolean reload(AbstractBundle newBundle) {
		if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
			if ((state & (INSTALLED | RESOLVED)) == 0) {
				Debug.println("Bundle.reload called when state != INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
				Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
			}
		}

		boolean exporting = false;

		if (framework.isActive()) {
			if (state == RESOLVED) {
				BundleLoaderProxy curProxy = getLoaderProxy();
				exporting = curProxy.inUse();
				if (exporting)
					// make sure the BundleLoader is created.
					curProxy.getBundleLoader().createClassLoader();
				else
					closeBundleLoader(proxy);
				state = INSTALLED;
				proxy = null;
				fragments = null;
			}

		} else {
			/* close the outgoing jarfile */
			try {
				this.bundledata.close();
			} catch (IOException e) {
				// Do Nothing
			}
		}
		this.bundledata = newBundle.bundledata;
		this.bundledata.setBundle(this);
		// create a new domain for the bundle because its signers/symbolic-name may have changed
		if (framework.isActive() && System.getSecurityManager() != null && framework.permissionAdmin != null)
			domain = framework.permissionAdmin.createProtectionDomain(this);
		return (exporting);
	}

	/**
	 * Refresh the bundle. This is called by Framework.refreshPackages.
	 * This method must be called while holding the bundles lock.
	 */
	protected void refresh() {
		if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
			if ((state & (UNINSTALLED | INSTALLED | RESOLVED)) == 0) {
				Debug.println("Bundle.reload called when state != UNINSTALLED | INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
				Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
			}
		}
		if (state == RESOLVED) {
			closeBundleLoader(proxy);
			proxy = null;
			fragments = null;
			state = INSTALLED;
			// Do not publish UNRESOLVED event here.  This is done by caller 
			// to resolve if appropriate.
		}
		manifestLocalization = null;
	}

	/**
	 * Unload the bundle.
	 * This method must be called while holding the bundles lock.
	 *
	 * @return  true if an exported package is "in use". i.e. it has been imported by a bundle
	 */
	protected boolean unload() {
		if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
			if ((state & (UNINSTALLED | INSTALLED | RESOLVED)) == 0) {
				Debug.println("Bundle.unload called when state != UNINSTALLED | INSTALLED | RESOLVED: " + this); //$NON-NLS-1$
				Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
			}
		}

		boolean exporting = false;

		if (framework.isActive()) {
			if (state == RESOLVED) {
				BundleLoaderProxy curProxy = getLoaderProxy();
				exporting = curProxy.inUse();
				if (exporting)
					// make sure the BundleLoader is created.
					curProxy.getBundleLoader().createClassLoader();
				else
					closeBundleLoader(proxy);

				state = INSTALLED;
				proxy = null;
				fragments = null;
				domain = null;
			}
		}
		if (!exporting){
			try {
				this.bundledata.close();
			} catch (IOException e) { // Do Nothing.
			}
		}

		return (exporting);
	}

	private BundleLoader checkLoader() {
		checkValid();

		// check to see if the bundle is resolved
		if (!isResolved()) {
			if (!framework.packageAdmin.resolveBundles(new Bundle[] {this})) {
				return null;
			}
		}
		if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
			if ((state & (STARTING | ACTIVE | STOPPING | RESOLVED)) == 0) {
				Debug.println("Bundle.checkLoader() called when state != STARTING | ACTIVE | STOPPING | RESOLVED: " + this); //$NON-NLS-1$ 
				Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
			}
		}

		BundleLoader loader = getBundleLoader();
		if (loader == null) {
			if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
				Debug.println("Bundle.checkLoader() called when loader == null: " + this); //$NON-NLS-1$ 
				Debug.printStackTrace(new Exception("Stack trace")); //$NON-NLS-1$
			}
			return null;
		}
		return loader;
	}

	/**
	 * This method loads a class from the bundle.
	 *
	 * @param      name     the name of the desired Class.
	 * @param      checkPermission indicates whether a permission check should be done.
	 * @return     the resulting Class
	 * @exception  java.lang.ClassNotFoundException  if the class definition was not found.
	 */
	protected Class loadClass(String name, boolean checkPermission) throws ClassNotFoundException {
		if (checkPermission) {
			try {
				framework.checkAdminPermission(this, AdminPermission.CLASS);
			} catch (SecurityException e) {
				throw new ClassNotFoundException();
			}
		}
		BundleLoader loader = checkLoader();
		if (loader == null)
			throw new ClassNotFoundException(NLS.bind(Msg.BUNDLE_CNFE_NOT_RESOLVED, getBundleData().getLocation(), name)); 
		return (loader.loadClass(name));
	}

	/**
	 * Find the specified resource in this bundle.
	 *
	 * This bundle's class loader is called to search for the named resource.
	 * If this bundle's state is <tt>INSTALLED</tt>, then only this bundle will
	 * be searched for the specified resource. Imported packages cannot be searched
	 * when a bundle has not been resolved.
	 *
	 * @param name The name of the resource.
	 * See <tt>java.lang.ClassLoader.getResource</tt> for a description of
	 * the format of a resource name.
	 * @return a URL to the named resource, or <tt>null</tt> if the resource could
	 * not be found or if the caller does not have
	 * the <tt>AdminPermission</tt>, and the Java Runtime Environment supports permissions.
	 * 
	 * @exception java.lang.IllegalStateException If this bundle has been uninstalled.
	 */
	public URL getResource(String name) {
		BundleLoader loader = null;
		try {
			framework.checkAdminPermission(this, AdminPermission.RESOURCE);
		} catch (SecurityException ee) {
			return null;
		}
		loader = checkLoader();
		if (loader == null)
			return null;
		return (loader.getResource(name));
	}

	public Enumeration getResources(String name) throws IOException {
		BundleLoader loader = null;
		try {
			framework.checkAdminPermission(this, AdminPermission.RESOURCE);
		} catch (SecurityException ee) {
			return null;
		}
		loader = checkLoader();
		if (loader == null)
			return null;
		Enumeration result = loader.getResources(name);
		if (result.hasMoreElements())
			return result;
		return null;
	}

	/**
	 * Internal worker to start a bundle.
	 *
	 * @param persistent if true persistently record the bundle was started.
	 */
	protected void startWorker(boolean persistent) throws BundleException {
		if (persistent) {
			setStatus(Constants.BUNDLE_STARTED, true);
		}
		long start = 0;
		if (framework.active) {
			if ((state & (STARTING | ACTIVE)) != 0) {
				return;
			}
			boolean shouldStart = false;
			try {
				if (state == INSTALLED) {
					if (!framework.packageAdmin.resolveBundles(new Bundle[] {this})) {
						throw new BundleException(getResolutionFailureMessage());
					}
				}

				if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
					Debug.println("Bundle: Active sl = " + framework.startLevelManager.getStartLevel() + "; Bundle " + getBundleId() + " sl = " + getStartLevel()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
				}
				shouldStart = getStartLevel() <= framework.startLevelManager.getStartLevel();
				if (shouldStart) {
					//STARTUP TIMING Start here					
					if (Debug.DEBUG) {
						BundleWatcher bundleStats = framework.adaptor.getBundleWatcher();
						if (bundleStats != null)
							bundleStats.watchBundle(this, BundleWatcher.START_ACTIVATION);
						if (Debug.DEBUG_BUNDLE_TIME) {
							start = System.currentTimeMillis();
							System.out.println("Starting " + getSymbolicName()); //$NON-NLS-1$
						}
					}
					state = STARTING;
					framework.publishBundleEvent(BundleEvent.STARTING, this);
					context = createContext();
					try {
						context.start();

						if (framework.active) {
							state = ACTIVE;

							if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
								Debug.println("->started " + this); //$NON-NLS-1$
							}

							framework.publishBundleEvent(BundleEvent.STARTED, this);
						}

					} catch (BundleException e) {
						context.close();
						context = null;

						state = RESOLVED;

						throw e;
					}

					if (state == UNINSTALLED) {
						context.close();
						context = null;
						throw new BundleException(NLS.bind(Msg.BUNDLE_UNINSTALLED_EXCEPTION, getBundleData().getLocation())); 
					}
				}
			} finally {
				if (Debug.DEBUG && shouldStart) {
					BundleWatcher bundleStats = framework.adaptor.getBundleWatcher();
					if (bundleStats != null)
						bundleStats.watchBundle(this, BundleWatcher.END_ACTIVATION);
					if (Debug.DEBUG_BUNDLE_TIME)
						System.out.println("End starting " + getSymbolicName() + " " + (System.currentTimeMillis() - start)); //$NON-NLS-1$ //$NON-NLS-2$
				}
			}
		}
	}

	/**
	 * Create a BundleContext for this bundle.
	 *
	 * @return BundleContext for this bundle.
	 */
	protected BundleContextImpl createContext() {
		return (new BundleContextImpl(this));
	}

	/**
	 * Return the current context for this bundle.
	 *
	 * @return BundleContext for this bundle.
	 */
	protected BundleContextImpl getContext() {
		return (context);
	}

	/**
	 * Internal worker to stop a bundle.
	 *
	 * @param persistent if true persistently record the bundle was stopped.
	 */
	protected void stopWorker(boolean persistent) throws BundleException {
		if (persistent) {
			setStatus(Constants.BUNDLE_STARTED, false);
		}

		if (framework.active) {
			if ((state & (STOPPING | RESOLVED | INSTALLED)) != 0) {
				return;
			}
			if (Debug.DEBUG) {
				BundleWatcher bundleStats = framework.adaptor.getBundleWatcher();
				if (bundleStats != null)
					bundleStats.watchBundle(this, BundleWatcher.START_DEACTIVATION);
			}
			state = STOPPING;
			framework.publishBundleEvent(BundleEvent.STOPPING, this);
			try {
				context.stop();
			} finally {
				context.close();
				context = null;

				checkValid();

				state = RESOLVED;

				if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
					Debug.println("->stopped " + this); //$NON-NLS-1$
				}

				framework.publishBundleEvent(BundleEvent.STOPPED, this);
				if (Debug.DEBUG) {
					BundleWatcher bundleStats = framework.adaptor.getBundleWatcher();
					if (bundleStats != null)
						bundleStats.watchBundle(this, BundleWatcher.END_DEACTIVATION);
				}
			}
		}
	}

	/**
	 * Provides a list of {@link ServiceReferenceImpl}s for the services
	 * registered by this bundle
	 * or <code>null</code> if the bundle has no registered
	 * services.
	 *
	 * <p>The list is valid at the time
	 * of the call to this method, but the framework is a very dynamic
	 * environment and services can be modified or unregistered at anytime.
	 *
	 * @return An array of {@link ServiceReferenceImpl} or <code>null</code>.
	 * @exception java.lang.IllegalStateException If the
	 * bundle has been uninstalled.
	 * @see ServiceRegistrationImpl
	 * @see ServiceReferenceImpl
	 */
	public org.osgi.framework.ServiceReference[] getRegisteredServices() {
		checkValid();

		if (context == null) {
			return (null);
		}

		return (context.getRegisteredServices());
	}

	/**
	 * Provides a list of {@link ServiceReferenceImpl}s for the
	 * services this bundle is using,
	 * or <code>null</code> if the bundle is not using any services.
	 * A bundle is considered to be using a service if the bundle's
	 * use count for the service is greater than zero.
	 *
	 * <p>The list is valid at the time
	 * of the call to this method, but the framework is a very dynamic
	 * environment and services can be modified or unregistered at anytime.
	 *
	 * @return An array of {@link ServiceReferenceImpl} or <code>null</code>.
	 * @exception java.lang.IllegalStateException If the
	 * bundle has been uninstalled.
	 * @see ServiceReferenceImpl
	 */
	public org.osgi.framework.ServiceReference[] getServicesInUse() {
		checkValid();

		if (context == null) {
			return (null);
		}

		return (context.getServicesInUse());
	}

	protected Bundle[] getFragments() {
		synchronized (framework.bundles) {
			if (fragments == null)
				return null;
			Bundle[] result = new Bundle[fragments.length];
			System.arraycopy(fragments, 0, result, 0, result.length);
			return result;
		}
	}

	/**
	 * Attaches a fragment to this BundleHost.  Fragments must be attached to
	 * the host by ID order.  If the ClassLoader of the host is already created
	 * then the fragment must be attached to the host ClassLoader
	 * @param fragment The fragment bundle to attach
	 * return true if the fragment successfully attached; false if the fragment
	 * could not be logically inserted at the end of the fragment chain.
	 */
	protected void attachFragment(BundleFragment fragment) throws BundleException {
		// do not force the creation of the bundle loader here
		BundleLoader loader = getLoaderProxy().getBasicBundleLoader();
		// If the Host ClassLoader exists then we must attach
		// the fragment to the ClassLoader.
		if (loader != null)
			loader.attachFragment(fragment);

		if (fragments == null) {
			fragments = new BundleFragment[] {fragment};
		} else {
			boolean inserted = false;
			// We must keep our fragments ordered by bundle ID; or 
			// install order.
			BundleFragment[] newFragments = new BundleFragment[fragments.length + 1];
			for (int i = 0; i < fragments.length; i++) {
				if (fragment == fragments[i])
					return; // this fragment is already attached
				if (!inserted && fragment.getBundleId() < fragments[i].getBundleId()) {
					// if the loader has already been created
					// then we cannot attach a fragment into the middle
					// of the fragment chain.
					if (loader != null) {
						throw new BundleException(NLS.bind(Msg.BUNDLE_LOADER_ATTACHMENT_ERROR, fragments[i].getSymbolicName(), getSymbolicName())); 
					}
					newFragments[i] = fragment;
					inserted = true;
				}
				newFragments[inserted ? i + 1 : i] = fragments[i];
			}
			if (!inserted)
				newFragments[newFragments.length - 1] = fragment;
			fragments = newFragments;
		}
	}

	protected BundleLoader getBundleLoader() {
		return getLoaderProxy().getBundleLoader();
	}

	protected synchronized BundleLoaderProxy getLoaderProxy() {
		if (proxy != null)
			return proxy;
		BundleDescription bundleDescription = getBundleDescription();
		proxy = new BundleLoaderProxy(this, bundleDescription);
		bundleDescription.setUserObject(proxy);
		return proxy;
	}

	static void closeBundleLoader(BundleLoaderProxy proxy) {
		if (proxy == null)
			return;
		// First close the BundleLoader
		BundleLoader loader = proxy.getBasicBundleLoader();
		if (loader != null)
			loader.close();
		proxy.setStale();
		// if proxy is not null then make sure to unset user object
		// associated with the proxy in the state
		BundleDescription description = proxy.getBundleDescription();
		description.setUserObject(null);
	}
}

Back to the top