Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: e24fcf1479619c29c0c9829ed83702a196ea8843 (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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
/*******************************************************************************
 * Copyright (c) 2003, 2004 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.core.runtime.adaptor;

import java.io.*;
import java.net.MalformedURLException;
import java.util.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import org.eclipse.osgi.framework.adaptor.*;
import org.eclipse.osgi.framework.adaptor.core.*;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.eclipse.osgi.framework.debug.Debug;
import org.eclipse.osgi.framework.debug.DebugOptions;
import org.eclipse.osgi.framework.log.*;
import org.eclipse.osgi.framework.stats.StatsManager;
import org.eclipse.osgi.internal.resolver.StateImpl;
import org.eclipse.osgi.internal.resolver.StateManager;
import org.eclipse.osgi.service.datalocation.FileManager;
import org.eclipse.osgi.service.datalocation.Location;
import org.eclipse.osgi.service.pluginconversion.PluginConverter;
import org.eclipse.osgi.service.resolver.*;
import org.eclipse.osgi.service.urlconversion.URLConverter;
import org.osgi.framework.*;

/**
 * Internal class.
 */
public class EclipseAdaptor extends AbstractFrameworkAdaptor {
	public static final String PROP_CLEAN = "osgi.clean"; //$NON-NLS-1$

	public static final String PROP_EXITONERROR = "eclipse.exitOnError"; //$NON-NLS-1$

	static final String F_LOG = ".log"; //$NON-NLS-1$

	// TODO rename it to Eclipse-PluginClass
	public static final String PLUGIN_CLASS = "Plugin-Class"; //$NON-NLS-1$

	public static final String ECLIPSE_AUTOSTART = "Eclipse-AutoStart"; //$NON-NLS-1$

	// TODO rename constant to ECLIPSE_AUTOSTART_EXCEPTIONS
	public static final String ECLIPSE_AUTOSTART_EXCEPTIONS = "exceptions"; //$NON-NLS-1$

	public static final String SAXFACTORYNAME = "javax.xml.parsers.SAXParserFactory"; //$NON-NLS-1$

	public static final String DOMFACTORYNAME = "javax.xml.parsers.DocumentBuilderFactory"; //$NON-NLS-1$

	private static final String RUNTIME_ADAPTOR = FRAMEWORK_SYMBOLICNAME + "/eclipseadaptor"; //$NON-NLS-1$

	private static final String OPTION_PLATFORM_ADMIN = RUNTIME_ADAPTOR + "/debug/platformadmin"; //$NON-NLS-1$

	private static final String OPTION_PLATFORM_ADMIN_RESOLVER = RUNTIME_ADAPTOR + "/debug/platformadmin/resolver"; //$NON-NLS-1$

	private static final String OPTION_MONITOR_PLATFORM_ADMIN = RUNTIME_ADAPTOR + "/resolver/timing"; //$NON-NLS-1$

	private static final String OPTION_RESOLVER_READER = RUNTIME_ADAPTOR + "/resolver/reader/timing"; //$NON-NLS-1$

	private static final String OPTION_CONVERTER = RUNTIME_ADAPTOR + "/converter/debug"; //$NON-NLS-1$

	private static final String OPTION_LOCATION = RUNTIME_ADAPTOR + "/debug/location"; //$NON-NLS-1$	

	public static final byte BUNDLEDATA_COMPATIBLE_VERSION = 10;
	public static final byte BUNDLEDATA_VERSION_11 = 11;
	public static final byte BUNDLEDATA_VERSION_12 = 12;
	public static final byte BUNDLEDATA_VERSION = 12;

	public static final byte NULL = 0;

	public static final byte OBJECT = 1;

	private static EclipseAdaptor instance;

	private byte cacheVersion;

	private long timeStamp = 0;

	private String installURL = null;

	private boolean exitOnError = true;

	private BundleStopper stopper;

	private FileManager fileManager;

	private boolean reinitialize = false;

	/*
	 * Should be instantiated only by the framework (through reflection).
	 */
	public EclipseAdaptor(String[] args) {
		super(args);
		instance = this;
		setDebugOptions();
	}

	public static EclipseAdaptor getDefault() {
		return instance;
	}

	private FrameworkLog createPerformanceLog() {
		String logFileProp = System.getProperty(EclipseStarter.PROP_LOGFILE);
		if (logFileProp != null) {
			int lastSlash = logFileProp.lastIndexOf(File.separatorChar);
			if (lastSlash > 0) {
				String logFile = logFileProp.substring(0, lastSlash+1) + "performance.log"; //$NON-NLS-1$
				return new EclipseLog(new File(logFile));
			}
		}
		//if all else fails, write to std err
		return new EclipseLog(new PrintWriter(System.err));
	}

	public void initialize(EventPublisher publisher) {
		if (Boolean.getBoolean(EclipseAdaptor.PROP_CLEAN))
			cleanOSGiCache();
		fileManager = initFileManager(LocationManager.getOSGiConfigurationDir(), LocationManager.getConfigurationLocation().isReadOnly() ? "none" : null); //$NON-NLS-1$
		readHeaders();
		checkLocationAndReinitialize();
		super.initialize(publisher);
	}

	public void initializeMetadata() {
		// do nothing here; metadata is already initialized by readHeaders.
	}

	protected void initBundleStoreRootDir() {
		File configurationLocation = LocationManager.getOSGiConfigurationDir();
		if (configurationLocation != null) {
			bundleStoreRootDir = new File(configurationLocation, LocationManager.BUNDLES_DIR);
			bundleStore = bundleStoreRootDir.getAbsolutePath();
		} else {
			// last resort just default to "bundles"
			bundleStore = LocationManager.BUNDLES_DIR;
			bundleStoreRootDir = new File(bundleStore);
		}

		/* store bundleStore back into adaptor properties for others to see */
		properties.put(BUNDLE_STORE, bundleStoreRootDir.getAbsolutePath());
	}

	protected FrameworkLog createFrameworkLog() {
		if (frameworkLog != null)
			return frameworkLog;
		return EclipseStarter.createFrameworkLog();
	}

	private File[] findStateFiles() {
		if (reinitialize)
			return new File[2]; // return null enties to indicate reinitialize
		File stateFile = null;
		File lazyFile = null;
		try {
			stateFile = fileManager.lookup(LocationManager.STATE_FILE, false);
			lazyFile = fileManager.lookup(LocationManager.LAZY_FILE, false);
		} catch (IOException ex) {
			if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
				Debug.println("Error reading state file " + ex.getMessage()); //$NON-NLS-1$
				Debug.printStackTrace(ex);
			}
		}
		//if it does not exist, try to read it from the parent
		if (stateFile == null || !stateFile.isFile()) { // NOTE this check is redundant since it
			// is done in StateManager, however it
			// is more convenient to have it here
			Location parentConfiguration = null;
			Location currentConfiguration = LocationManager.getConfigurationLocation();
			if (currentConfiguration != null && (parentConfiguration = currentConfiguration.getParentLocation()) != null) {
				try {
					File stateLocationDir = new File(parentConfiguration.getURL().getFile(), FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME);
					FileManager newFileManager = initFileManager(stateLocationDir, parentConfiguration.isReadOnly() ? "none" : null); //$NON-NLS-1$);
					stateFile = newFileManager.lookup(LocationManager.STATE_FILE, true);
					lazyFile = newFileManager.lookup(LocationManager.LAZY_FILE, true);
				} catch (IOException ex) {
					if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
						Debug.println("Error reading state file " + ex.getMessage()); //$NON-NLS-1$
						Debug.printStackTrace(ex);
					}
				}
			} else {
				try {
					//it did not exist in either place, so create it in the original location
					stateFile = fileManager.lookup(LocationManager.STATE_FILE, true);
					lazyFile = fileManager.lookup(LocationManager.LAZY_FILE, true);
				} catch (IOException ex) {
					if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
						Debug.println("Error reading state file " + ex.getMessage()); //$NON-NLS-1$
						Debug.printStackTrace(ex);
					}
				}
			}
		}
		return new File[] {stateFile, lazyFile};
	}

	protected StateManager createStateManager() {
		File[] stateFiles = findStateFiles();
		File stateFile = stateFiles[0];
		File lazyFile = stateFiles[1];

		stateManager = new StateManager(stateFile, lazyFile, context, timeStamp);
		stateManager.setInstaller(new EclipseBundleInstaller());
		StateImpl systemState = null;
		if (!invalidState) {
			systemState = stateManager.readSystemState();
			if (systemState != null)
				return stateManager;
		}
		systemState = stateManager.createSystemState();
		Bundle[] installedBundles = context.getBundles();
		if (installedBundles == null)
			return stateManager;
		StateObjectFactory factory = stateManager.getFactory();
		for (int i = 0; i < installedBundles.length; i++) {
			Bundle toAdd = installedBundles[i];
			try {
				Dictionary toAddManifest = toAdd.getHeaders(""); //$NON-NLS-1$
				// if this is a cached manifest need to get the real one
				if (toAddManifest instanceof CachedManifest)
					toAddManifest = ((CachedManifest) toAddManifest).getManifest();
				BundleDescription newDescription = factory.createBundleDescription(toAddManifest, toAdd.getLocation(), toAdd.getBundleId());
				systemState.addBundle(newDescription);
			} catch (BundleException be) {
				// just ignore bundle datas with invalid manifests
			}
		}
		// we need the state resolved
		systemState.setTimeStamp(timeStamp);
		systemState.resolve();
		invalidState = false;
		return stateManager;
	}

	public void shutdownStateManager() {
		if (stateManager.getCachedTimeStamp() == stateManager.getSystemState().getTimeStamp())
			return;
		try {
			File stateTmpFile = File.createTempFile(LocationManager.STATE_FILE, ".new", LocationManager.getOSGiConfigurationDir()); //$NON-NLS-1$
			File lazyTmpFile = File.createTempFile(LocationManager.LAZY_FILE, ".new", LocationManager.getOSGiConfigurationDir()); //$NON-NLS-1$
			stateManager.shutdown(stateTmpFile, lazyTmpFile);
			fileManager.lookup(LocationManager.STATE_FILE, true);
			fileManager.lookup(LocationManager.LAZY_FILE, true);
			fileManager.update(new String[] {LocationManager.STATE_FILE, LocationManager.LAZY_FILE}, new String[] {stateTmpFile.getName(), lazyTmpFile.getName()});
		} catch (IOException e) {
			frameworkLog.log(new FrameworkEvent(FrameworkEvent.ERROR, context.getBundle(), e));
		}
	}

	private void cleanOSGiCache() {
		File osgiConfig = LocationManager.getOSGiConfigurationDir();
		if (!rm(osgiConfig)) {
			// TODO log error?
		}
	}

	private void checkLocationAndReinitialize() {
		if (installURL == null) {
			installURL = EclipseStarter.getSysPath(); // TODO This reference to the starter should be avoided
			return;
		}
		if (!EclipseStarter.getSysPath().equals(installURL)) {
			// reinitialize bundledata and state files
			reinitialize = true;

			installURL = EclipseStarter.getSysPath();
		}
	}

	private void readHeaders() {
		InputStream bundleDataStream = findBundleDataFile();
		if (bundleDataStream == null)
			return;

		try {
			DataInputStream in = new DataInputStream(new BufferedInputStream(bundleDataStream));
			try {
				cacheVersion = in.readByte();
				if (cacheVersion >= BUNDLEDATA_COMPATIBLE_VERSION) {
					timeStamp = in.readLong();
					installURL = in.readUTF();
					initialBundleStartLevel = in.readInt();
					nextId = in.readLong();
				}
			} finally {
				in.close();
			}
		} catch (IOException e) {
			if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
				Debug.println("Error reading framework metadata: " + e.getMessage()); //$NON-NLS-1$
				Debug.printStackTrace(e);
			}
		}
	}

	public AdaptorElementFactory getElementFactory() {
		if (elementFactory == null)
			elementFactory = new EclipseElementFactory();
		return elementFactory;
	}

	public void frameworkStart(BundleContext aContext) throws BundleException {
		// must register the xml parser and initialize the plugin converter
		// instance first because we may need it when creating the statemanager
		// in super.frameworkStart(context)
		registerEndorsedXMLParser(aContext);
		PluginConverter converter = new PluginConverterImpl(aContext);
		super.frameworkStart(aContext);
		Bundle bundle = aContext.getBundle();
		Location location;

		// Less than optimal reference to EclipseStarter here. Not sure how we
		// can make the location
		// objects available. They are needed very early in EclipseStarter but
		// these references tie the adaptor to that starter.
		location = LocationManager.getUserLocation();
		Hashtable locationProperties = new Hashtable(1);
		if (location != null) {
			locationProperties.put("type", LocationManager.PROP_USER_AREA); //$NON-NLS-1$
			aContext.registerService(Location.class.getName(), location, locationProperties);
		}
		location = LocationManager.getInstanceLocation();
		if (location != null) {
			locationProperties.put("type", LocationManager.PROP_INSTANCE_AREA); //$NON-NLS-1$
			aContext.registerService(Location.class.getName(), location, locationProperties);
		}
		location = LocationManager.getConfigurationLocation();
		if (location != null) {
			locationProperties.put("type", LocationManager.PROP_CONFIG_AREA); //$NON-NLS-1$
			aContext.registerService(Location.class.getName(), location, locationProperties);
		}
		location = LocationManager.getInstallLocation();
		if (location != null) {
			locationProperties.put("type", LocationManager.PROP_INSTALL_AREA); //$NON-NLS-1$
			aContext.registerService(Location.class.getName(), location, locationProperties);
		}

		register(org.eclipse.osgi.service.environment.EnvironmentInfo.class.getName(), EnvironmentInfo.getDefault(), bundle);
		register(PlatformAdmin.class.getName(), stateManager, bundle);
		register(PluginConverter.class.getName(), converter, bundle);
		register(URLConverter.class.getName(), new URLConverterImpl(), bundle);
		register(CommandProvider.class.getName(), new EclipseCommandProvider(aContext), bundle);
		register(FrameworkLog.class.getName(), getFrameworkLog(), bundle);
		registerPerformanceLog(bundle);
		register(org.eclipse.osgi.service.localization.BundleLocalization.class.getName(), new BundleLocalizationImpl(), bundle);
	}

	private void registerPerformanceLog(Bundle bundle) {
		Object service = createPerformanceLog();
		String serviceName = FrameworkLog.class.getName();
		Hashtable serviceProperties = new Hashtable(7);
		Dictionary headers = bundle.getHeaders();

		serviceProperties.put(Constants.SERVICE_VENDOR, headers.get(Constants.BUNDLE_VENDOR));
		serviceProperties.put(Constants.SERVICE_RANKING, new Integer(Integer.MIN_VALUE));
		serviceProperties.put(Constants.SERVICE_PID, bundle.getBundleId() + '.' + service.getClass().getName());
		serviceProperties.put(FrameworkLog.SERVICE_PERFORMANCE, Boolean.TRUE.toString());

		context.registerService(serviceName, service, serviceProperties);
	}

	private void setDebugOptions() {
		DebugOptions options = DebugOptions.getDefault();
		// may be null if debugging is not enabled
		if (options == null)
			return;
		StateManager.DEBUG = options != null;
		StateManager.DEBUG_READER = options.getBooleanOption(OPTION_RESOLVER_READER, false);
		StateManager.MONITOR_PLATFORM_ADMIN = options.getBooleanOption(OPTION_MONITOR_PLATFORM_ADMIN, false);
		StateManager.DEBUG_PLATFORM_ADMIN = options.getBooleanOption(OPTION_PLATFORM_ADMIN, false);
		StateManager.DEBUG_PLATFORM_ADMIN_RESOLVER = options.getBooleanOption(OPTION_PLATFORM_ADMIN_RESOLVER, false);
		PluginConverterImpl.DEBUG = options.getBooleanOption(OPTION_CONVERTER, false);
		BasicLocation.DEBUG = options.getBooleanOption(OPTION_LOCATION, false);
	}

	private void registerEndorsedXMLParser(BundleContext bc) {
		try {
			Class.forName(SAXFACTORYNAME);
			bc.registerService(SAXFACTORYNAME, new SaxParsingService(), new Hashtable());
			Class.forName(DOMFACTORYNAME);
			bc.registerService(DOMFACTORYNAME, new DomParsingService(), new Hashtable());
		} catch (ClassNotFoundException e) {
			// In case the JAXP API is not on the boot classpath
			String message = EclipseAdaptorMsg.formatter.getString("ECLIPSE_ADAPTOR_ERROR_XML_SERVICE"); //$NON-NLS-1$
			getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, e, null));
		}
	}

	private class SaxParsingService implements ServiceFactory {
		public Object getService(Bundle bundle, ServiceRegistration registration) {
			return SAXParserFactory.newInstance();
		}

		public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {
			// Do nothing.
		}
	}

	private class DomParsingService implements ServiceFactory {
		public Object getService(Bundle bundle, ServiceRegistration registration) {
			return DocumentBuilderFactory.newInstance();
		}

		public void ungetService(Bundle bundle, ServiceRegistration registration, Object service) {
			// Do nothing.
		}
	}

	public void frameworkStop(BundleContext aContext) throws BundleException {
		saveMetaData();
		super.frameworkStop(aContext);
		printStats();
		PluginParser.releaseXMLParsing();
		fileManager.close();
	}

	private void printStats() {
		DebugOptions debugOptions = DebugOptions.getDefault();
		if (debugOptions == null)
			return;
		String registryParsing = debugOptions.getOption("org.eclipse.core.runtime/registry/parsing/timing/value"); //$NON-NLS-1$
		if (registryParsing != null)
			EclipseAdaptorMsg.debug("Time spent in registry parsing: " + registryParsing); //$NON-NLS-1$
		String packageAdminResolution = debugOptions.getOption("debug.packageadmin/timing/value"); //$NON-NLS-1$
		if (packageAdminResolution != null)
			System.out.println("Time spent in package admin resolve: " + packageAdminResolution); //$NON-NLS-1$			
		String constraintResolution = debugOptions.getOption("org.eclipse.core.runtime.adaptor/resolver/timing/value"); //$NON-NLS-1$
		if (constraintResolution != null)
			System.out.println("Time spent resolving the dependency system: " + constraintResolution); //$NON-NLS-1$ 
	}

	private InputStream findBundleDataFile() {
		if (reinitialize)
			return null; // return null to indicate we are reinitializing
		File metadata = null;
		try {
			metadata = fileManager.lookup(LocationManager.BUNDLE_DATA_FILE, false);
		} catch (IOException ex) {
			if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
				Debug.println("Error reading framework metadata: " + ex.getMessage()); //$NON-NLS-1$
				Debug.printStackTrace(ex);
			}
		}
		InputStream bundleDataStream = null;
		if (metadata != null && metadata.isFile()) {
			try {
				bundleDataStream = new FileInputStream(metadata);
			} catch (FileNotFoundException e1) {
				// this can not happen since it is tested before entering here.
			}
		} else {
			Location currentConfiguration = LocationManager.getConfigurationLocation();
			Location parentConfiguration = null;
			if (currentConfiguration != null && (parentConfiguration = currentConfiguration.getParentLocation()) != null) {
				try {
					File bundledataLocationDir = new File(parentConfiguration.getURL().getFile(), FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME);
					FileManager newFileManager = initFileManager(bundledataLocationDir, parentConfiguration.isReadOnly() ? "none" : null); //$NON-NLS-1$
					File bundleData = newFileManager.lookup(LocationManager.BUNDLE_DATA_FILE, true);
					bundleDataStream = new FileInputStream(bundleData);
				} catch (MalformedURLException e1) {
					// This will not happen since all the URLs are derived by us
					// and we are GODS!
				} catch (IOException e1) {
					// That's ok we will regenerate the .bundleData
				}
			}
		}
		return bundleDataStream;
	}

	/**
	 * @see org.eclipse.osgi.framework.adaptor.FrameworkAdaptor#getInstalledBundles()
	 */
	public BundleData[] getInstalledBundles() {
		InputStream bundleDataStream = findBundleDataFile();
		if (bundleDataStream == null)
			return null;

		try {
			DataInputStream in = new DataInputStream(new BufferedInputStream(bundleDataStream));
			try {
				if (in.readByte() < BUNDLEDATA_COMPATIBLE_VERSION)
					return null;
				// skip timeStamp - was read by readHeaders
				in.readLong();
				in.readUTF();
				in.readInt();
				in.readLong();

				int bundleCount = in.readInt();
				ArrayList result = new ArrayList(bundleCount);
				long id = -1;

				for (int i = 0; i < bundleCount; i++) {
					try {
						try {
							id = in.readLong();
							if (id != 0) {
								EclipseBundleData data = (EclipseBundleData) getElementFactory().createBundleData(this, id);
								loadMetaDataFor(data, in);
								data.initializeExistingBundle();
								if (Debug.DEBUG && Debug.DEBUG_GENERAL)
									Debug.println("BundleData created: " + data); //$NON-NLS-1$
								processExtension(data, EXTENSION_INITIALIZE);
								result.add(data);
							}
						} catch (NumberFormatException e) {
							// should never happen
						} catch (BundleException e) {
							// should never happen
						}
					} catch (IOException e) {
						if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
							Debug.println("Error reading framework metadata: " + e.getMessage()); //$NON-NLS-1$ 
							Debug.printStackTrace(e);
						}
					}
				}
				return (BundleData[]) result.toArray(new BundleData[result.size()]);
			} finally {
				in.close();
			}
		} catch (IOException e) {
			if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
				Debug.println("Error reading framework metadata: " + e.getMessage()); //$NON-NLS-1$ 
				Debug.printStackTrace(e);
			}
		}
		return null;
	}

	protected void loadMetaDataFor(EclipseBundleData data, DataInputStream in) throws IOException {
		byte flag = in.readByte();
		if (flag == NULL)
			return;
		data.setLocation(readString(in, false));
		data.setFileName(readString(in, false));
		data.setSymbolicName(readString(in, false));
		data.setVersion(Version.parseVersion(readString(in, false)));
		data.setActivator(readString(in, false));
		data.setAutoStart(in.readBoolean());
		int exceptionsCount = in.readInt();
		String[] autoStartExceptions = exceptionsCount > 0 ? new String[exceptionsCount] : null;
		for (int i = 0; i < exceptionsCount; i++)
			autoStartExceptions[i] = in.readUTF();
		data.setAutoStartExceptions(autoStartExceptions);
		data.setPluginClass(readString(in, false));
		data.setClassPathString(readString(in, false));
		data.setNativePaths(readString(in, false));
		data.setExecutionEnvironment(readString(in, false));
		data.setDynamicImports(readString(in, false));
		data.setGeneration(in.readInt());
		data.setStartLevel(in.readInt());
		data.setStatus(in.readInt());
		data.setReference(in.readBoolean());
		if (cacheVersion <= BUNDLEDATA_VERSION_11)
			if (in.readBoolean())
				data.setType(BundleData.TYPE_FRAGMENT);
		data.setManifestTimeStamp(in.readLong());
		data.setManifestType(in.readByte());
		if (cacheVersion >= BUNDLEDATA_VERSION_11)
			data.setLastModified(in.readLong());
		if (cacheVersion >= BUNDLEDATA_VERSION_12)
			data.setType(in.readInt());
	}

	public void saveMetaDataFor(EclipseBundleData data) throws IOException {
		if (!data.isAutoStartable()) {
			timeStamp--; // Change the value of the timeStamp, as a marker
			// that something changed.
		}
	}

	public void persistInitialBundleStartLevel(int value) {
		// Change the value of the timeStamp, as a marker that something
		// changed.
		timeStamp--;
	}

	public void persistNextBundleID(long value) {
		// Do nothing the timeStamp will have changed because the state will be
		// updated.
	}

	protected void saveMetaDataFor(BundleData data, DataOutputStream out) throws IOException {
		if (data.getBundleID() == 0 || !(data instanceof AbstractBundleData)) {
			out.writeByte(NULL);
			return;
		}
		EclipseBundleData bundleData = (EclipseBundleData) data;
		out.writeByte(OBJECT);
		writeStringOrNull(out, bundleData.getLocation());
		writeStringOrNull(out, bundleData.getFileName());
		writeStringOrNull(out, bundleData.getSymbolicName());
		writeStringOrNull(out, bundleData.getVersion().toString());
		writeStringOrNull(out, bundleData.getActivator());
		out.writeBoolean(bundleData.isAutoStart());
		String[] autoStartExceptions = bundleData.getAutoStartExceptions();
		if (autoStartExceptions == null)
			out.writeInt(0);
		else {
			out.writeInt(autoStartExceptions.length);
			for (int i = 0; i < autoStartExceptions.length; i++)
				out.writeUTF(autoStartExceptions[i]);
		}
		writeStringOrNull(out, bundleData.getPluginClass());
		writeStringOrNull(out, bundleData.getClassPathString());
		writeStringOrNull(out, bundleData.getNativePathsString());
		writeStringOrNull(out, bundleData.getExecutionEnvironment());
		writeStringOrNull(out, bundleData.getDynamicImports());
		out.writeInt(bundleData.getGeneration());
		out.writeInt(bundleData.getStartLevel());
		out.writeInt(bundleData.getPersistentStatus());
		out.writeBoolean(bundleData.isReference());
		out.writeLong(bundleData.getManifestTimeStamp());
		out.writeByte(bundleData.getManifestType());
		out.writeLong(bundleData.getLastModified());
		out.writeInt(bundleData.getType());
	}

	private String readString(DataInputStream in, boolean intern) throws IOException {
		byte type = in.readByte();
		if (type == NULL)
			return null;
		return intern ? in.readUTF().intern() : in.readUTF();
	}

	private void writeStringOrNull(DataOutputStream out, String string) throws IOException {
		if (string == null)
			out.writeByte(NULL);
		else {
			out.writeByte(OBJECT);
			out.writeUTF(string);
		}
	}

	public void saveMetaData() {
		// the cache and the state match
		if (timeStamp == stateManager.getSystemState().getTimeStamp())
			return;
		File metadata = null;
		try {
			metadata = File.createTempFile(LocationManager.BUNDLE_DATA_FILE, ".new", LocationManager.getOSGiConfigurationDir());//$NON-NLS-1$
			DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(metadata)));
			try {
				out.writeByte(BUNDLEDATA_VERSION);
				out.writeLong(stateManager.getSystemState().getTimeStamp());
				out.writeUTF(installURL);
				out.writeInt(initialBundleStartLevel);
				out.writeLong(nextId);
				Bundle[] bundles = context.getBundles();
				out.writeInt(bundles.length);
				for (int i = 0; i < bundles.length; i++) {
					long id = bundles[i].getBundleId();
					out.writeLong(id);
					if (id != 0) {
						BundleData data = ((org.eclipse.osgi.framework.internal.core.AbstractBundle) bundles[i]).getBundleData();
						saveMetaDataFor(data, out);
					}
				}
			} finally {
				out.close();
			}
			fileManager.lookup(LocationManager.BUNDLE_DATA_FILE, true); //the BundleData file may not have been created at this point.  
			fileManager.update(new String[] {LocationManager.BUNDLE_DATA_FILE}, new String[] {metadata.getName()});
		} catch (IOException e) {
			frameworkLog.log(new FrameworkEvent(FrameworkEvent.ERROR, context.getBundle(), e));
			return;
		}
	}

	public BundleWatcher getBundleWatcher() {
		return StatsManager.getDefault();
	}

	protected BundleContext getContext() {
		return context;
	}

	public void frameworkStopping(BundleContext aContext) {
		super.frameworkStopping(aContext);
		stopper = new BundleStopper();
		stopper.stopBundles();
	}

	private boolean isFatalException(Throwable error) {
		if (error instanceof VirtualMachineError) {
			return true;
		}
		if (error instanceof ThreadDeath) {
			return true;
		}
		return false;
	}

	public void handleRuntimeError(Throwable error) {
		try {
			// check the prop each time this happens (should NEVER happen!)
			exitOnError = Boolean.valueOf(System.getProperty(PROP_EXITONERROR, "true")).booleanValue(); //$NON-NLS-1$
			String message = EclipseAdaptorMsg.formatter.getString("ECLIPSE_ADAPTOR_RUNTIME_ERROR"); //$NON-NLS-1$
			if (exitOnError && isFatalException(error))
				message += ' ' + EclipseAdaptorMsg.formatter.getString("ECLIPSE_ADAPTOR_EXITING"); //$NON-NLS-1$
			FrameworkLogEntry logEntry = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, error, null);
			frameworkLog.log(logEntry);
		} catch (Throwable t) {
			// we may be in a currupted state and must be able to handle any
			// errors (ie OutOfMemoryError)
			// that may occur when handling the first error; this is REALLY the
			// last resort.
			try {
				error.printStackTrace();
				t.printStackTrace();
			} catch (Throwable t1) {
				// if we fail that then we are beyond help.
			}
		} finally {
			// do the exit outside the try block just incase another runtime
			// error was thrown while logging
			if (exitOnError && isFatalException(error))
				System.exit(13);
		}
	}

	protected void setLog(FrameworkLog log) {
		frameworkLog = log;
	}

	public BundleStopper getBundleStopper() {
		return stopper;
	}

	private FileManager initFileManager(File baseDir, String lockMode) {
		FileManager fManager = new FileManager(baseDir, lockMode);
		if (!baseDir.exists())
			baseDir.mkdirs();
		try {
			fManager.open(true);
		} catch (IOException ex) {
			if (Debug.DEBUG && Debug.DEBUG_GENERAL) {
				Debug.println("Error reading framework metadata: " + ex.getMessage()); //$NON-NLS-1$
				Debug.printStackTrace(ex);
			}
		}
		return fManager;
	}
}

Back to the top