KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > update > internal > core > InstallConfiguration


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.update.internal.core;
12
13 import java.io.File JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.net.MalformedURLException JavaDoc;
16 import java.net.URL JavaDoc;
17 import java.util.ArrayList JavaDoc;
18 import java.util.Arrays JavaDoc;
19 import java.util.Collection JavaDoc;
20 import java.util.Date JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.HashSet JavaDoc;
23 import java.util.Hashtable JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.Map JavaDoc;
26 import java.util.Set JavaDoc;
27
28 import org.eclipse.core.runtime.CoreException;
29 import org.eclipse.core.runtime.FileLocator;
30 import org.eclipse.core.runtime.IProgressMonitor;
31 import org.eclipse.core.runtime.IStatus;
32 import org.eclipse.core.runtime.Platform;
33 import org.eclipse.core.runtime.Status;
34 import org.eclipse.osgi.util.NLS;
35 import org.eclipse.update.configuration.IActivity;
36 import org.eclipse.update.configuration.IConfiguredSite;
37 import org.eclipse.update.configuration.IInstallConfiguration;
38 import org.eclipse.update.configuration.IInstallConfigurationChangedListener;
39 import org.eclipse.update.configuration.IProblemHandler;
40 import org.eclipse.update.configurator.ConfiguratorUtils;
41 import org.eclipse.update.configurator.IPlatformConfiguration;
42 import org.eclipse.update.core.FeatureContentProvider;
43 import org.eclipse.update.core.IFeature;
44 import org.eclipse.update.core.IFeatureReference;
45 import org.eclipse.update.core.IPluginEntry;
46 import org.eclipse.update.core.ISite;
47 import org.eclipse.update.core.ISiteContentProvider;
48 import org.eclipse.update.core.ISiteFeatureReference;
49 import org.eclipse.update.core.Site;
50 import org.eclipse.update.core.SiteManager;
51 import org.eclipse.update.core.Utilities;
52 import org.eclipse.update.core.VersionedIdentifier;
53 import org.eclipse.update.core.model.SiteModel;
54 import org.eclipse.update.internal.configurator.ConfigurationActivator;
55 import org.eclipse.update.internal.configurator.FeatureEntry;
56 import org.eclipse.update.internal.configurator.PlatformConfiguration;
57 import org.eclipse.update.internal.configurator.PluginEntry;
58 import org.eclipse.update.internal.configurator.SiteEntry;
59 import org.eclipse.update.internal.model.ConfigurationActivityModel;
60 import org.eclipse.update.internal.model.ConfiguredSiteModel;
61 import org.eclipse.update.internal.model.InstallConfigurationModel;
62 import org.osgi.framework.Bundle;
63
64 /**
65  * Manages ConfiguredSites
66  *
67  */

68
69 public class InstallConfiguration extends InstallConfigurationModel implements IInstallConfiguration {
70     private static boolean isWindows = System.getProperty("os.name").startsWith("Win"); //$NON-NLS-1$ //$NON-NLS-2$
71
private ListenersList listeners = new ListenersList();
72
73     /*
74      * default constructor.
75      */

76     public InstallConfiguration() {
77     }
78
79     /*
80      * Copy constructor
81      * @since 3.0
82      */

83     public InstallConfiguration(IInstallConfiguration config) throws MalformedURLException JavaDoc, CoreException {
84         this(config, null, null);
85     }
86     
87     /*
88      * copy constructor
89      */

90     public InstallConfiguration(IInstallConfiguration config, URL JavaDoc newLocation, String JavaDoc label) throws CoreException, MalformedURLException JavaDoc {
91         // set current date and timeline as caller can call setDate if the
92
// date on the URL string has to be the same
93
Date JavaDoc now = new Date JavaDoc();
94         setCreationDate(now);
95         setCurrent(false);
96         
97         if (newLocation == null) {
98             String JavaDoc newFileName = UpdateManagerUtils.getLocalRandomIdentifier(LocalSite.CONFIG_FILE, now);
99             newLocation = UpdateManagerUtils.getURL(((LocalSite)SiteManager.getLocalSite()).getLocationURL(), newFileName, null);
100         }
101         setLocationURLString(newLocation.toExternalForm());
102         
103         if (label == null)
104             label = Utilities.format(now);
105         setLabel(label);
106
107         // do not copy list of listeners nor activities
108
// make a copy of the siteConfiguration object
109
if (config != null) {
110             IConfiguredSite[] csites = config.getConfiguredSites();
111             if (csites != null) {
112                 for (int i = 0; i < csites.length; i++) {
113                     ConfiguredSite configSite = new ConfiguredSite(csites[i]);
114                     addConfigurationSiteModel(configSite);
115                 }
116             }
117         }
118
119         resolve(newLocation, null);
120         // no need to parse file, all data are initialized
121
initialized = true;
122     }
123     
124
125     /*
126      * Returns the list of configured sites or an empty array
127      */

128     public IConfiguredSite[] getConfiguredSites() {
129         ConfiguredSiteModel[] result = getConfigurationSitesModel();
130         if (result.length == 0)
131             return new IConfiguredSite[0];
132         else
133             return (IConfiguredSite[]) result;
134     }
135
136     /*
137      * Returns the default site policy
138      */

139     private int getDefaultPolicy() {
140         return PlatformConfiguration.getDefaultPolicy();
141     }
142
143     /**
144      * Creates a Configuration Site and a new Site
145      * The policy is from <code> org.eclipse.core.boot.IPlatformConfiguration</code>
146      */

147     public IConfiguredSite createConfiguredSite(File JavaDoc file) throws CoreException {
148
149         if (!file.getName().equals("eclipse")) { //$NON-NLS-1$
150
file = new File JavaDoc(file, "eclipse"); //$NON-NLS-1$
151
file.mkdirs();
152         }
153         
154         if (isDuplicateSite(file))
155             throw Utilities.newCoreException(NLS.bind(Messages.InstallConfiguration_location_exists, (new String JavaDoc[] { file.getPath() })),null);
156         ISite site = InternalSiteManager.createSite(file);
157
158         //create a config site around the site
159
// even if the site == null
160
BaseSiteLocalFactory factory = new BaseSiteLocalFactory();
161         ConfiguredSite configSite = (ConfiguredSite) factory.createConfigurationSiteModel((SiteModel) site, getDefaultPolicy());
162
163         if (configSite.isNativelyLinked()) {
164             throw Utilities.newCoreException(Messages.InstallConfiguration_AlreadyNativelyLinked, null);
165         }
166         
167         if (configSite.isProductSite()) {
168             throw Utilities.newCoreException(Messages.InstallConfiguration_AlreadyProductSite, null);
169         }
170         
171         if (site != null) {
172             configSite.setPlatformURLString(site.getURL().toExternalForm());
173
174             // obtain the list of plugins
175
IPlatformConfiguration runtimeConfiguration = ConfiguratorUtils.getCurrentPlatformConfiguration();
176             ConfigurationPolicy configurationPolicy = configSite.getConfigurationPolicy();
177             String JavaDoc[] pluginPath = new String JavaDoc[0];
178             if (configurationPolicy.getPolicy() == IPlatformConfiguration.ISitePolicy.USER_INCLUDE)
179                 pluginPath = configurationPolicy.getPluginPath(site);
180
181             // create new Site in configuration
182
IPlatformConfiguration.ISitePolicy sitePolicy = runtimeConfiguration.createSitePolicy(configurationPolicy.getPolicy(), pluginPath);
183
184             // change runtime
185
IPlatformConfiguration.ISiteEntry siteEntry = runtimeConfiguration.createSiteEntry(site.getURL(), sitePolicy);
186             runtimeConfiguration.configureSite(siteEntry);
187
188             // if the privatre marker doesn't already exist create it
189
configSite.createPrivateSiteMarker();
190             ((SiteModel)site).setConfiguredSiteModel(configSite);
191         }
192         // configure all features as enable
193
configure(configSite);
194         
195         return configSite;
196     }
197
198     /**
199      * Creates a Configuration Site and a new Site as a private link site
200      * The policy is from <code> org.eclipse.core.boot.IPlatformConfiguration</code>
201      */

202     public IConfiguredSite createLinkedConfiguredSite(File JavaDoc file) throws CoreException {
203         return createConfiguredSite(file);
204 // if (isDuplicateSite(file))
205
// throw Utilities.newCoreException(UpdateUtils.getFormattedMessage("InstallConfiguration.location.exists", file.getPath()),null);
206
//
207
// ISite site = InternalSiteManager.createSite(file);
208
//
209
// //create a config site around the site
210
// // even if the site == null
211
// BaseSiteLocalFactory factory = new BaseSiteLocalFactory();
212
// ConfiguredSite configSite = (ConfiguredSite) factory.createConfigurationSiteModel((SiteModel) site, getDefaultPolicy());
213
//
214
// if (!configSite.isExtensionSite()) {
215
// String msg = Policy.bind("InstallConfiguration.NotAnExtensionSite");
216
// throw Utilities.newCoreException(msg, null);
217
// }
218
//
219
// if (configSite.isNativelyLinked()) {
220
// throw Utilities.newCoreException("InstallConfiguration.AlreadyNativelyLinked", null);
221
// }
222
//
223
// if (site != null) {
224
// configSite.setPlatformURLString(site.getURL().toExternalForm());
225
//
226
// // obtain the list of plugins
227
// IPlatformConfiguration runtimeConfiguration = ConfiguratorUtils.getCurrentPlatformConfiguration();
228
// ConfigurationPolicy configurationPolicy = configSite.getConfigurationPolicy();
229
// String[] pluginPath = new String[0];
230
// if (configurationPolicy.getPolicy() == IPlatformConfiguration.ISitePolicy.USER_INCLUDE)
231
// pluginPath = configurationPolicy.getPluginPath(site);
232
//
233
// // create new Site in configuration
234
// IPlatformConfiguration.ISitePolicy sitePolicy = runtimeConfiguration.createSitePolicy(configurationPolicy.getPolicy(), pluginPath);
235
//
236
// // change runtime
237
// IPlatformConfiguration.ISiteEntry siteEntry = runtimeConfiguration.createSiteEntry(site.getURL(), sitePolicy);
238
// runtimeConfiguration.configureSite(siteEntry);
239
//
240
// }
241
//
242
// // configure all features as enable
243
// configure(configSite);
244
//
245
// return configSite;
246
}
247
248     /*
249      *Configure all features as Enable Check we only enable highest version
250      */

251     private void configure(ConfiguredSite linkedSite) throws CoreException {
252         ISite site = linkedSite.getSite();
253         ISiteFeatureReference[] newFeaturesRef = site.getFeatureReferences();
254
255         for (int i = 0; i < newFeaturesRef.length; i++) {
256             // TRACE
257
if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_RECONCILER) {
258                 String JavaDoc reconciliationType = "enable (optimistic)"; //$NON-NLS-1$
259
UpdateCore.debug("New Linked Site:New Feature: " + newFeaturesRef[i].getURL() + " as " + reconciliationType); //$NON-NLS-1$ //$NON-NLS-2$
260
}
261             ConfigurationPolicy policy = linkedSite.getConfigurationPolicy();
262             policy.configure(newFeaturesRef[i], true, false);
263         }
264         SiteReconciler.checkConfiguredFeatures(linkedSite);
265     }
266
267     /*
268      *
269      */

270     public void addConfiguredSite(IConfiguredSite site) {
271         if (!isCurrent() && isReadOnly())
272             return;
273
274         ConfigurationActivity activity = new ConfigurationActivity(IActivity.ACTION_SITE_INSTALL);
275         activity.setLabel(site.getSite().getURL().toExternalForm());
276         activity.setDate(new Date JavaDoc());
277         ConfiguredSiteModel configSiteModel = (ConfiguredSiteModel) site;
278         addConfigurationSiteModel(configSiteModel);
279         configSiteModel.setInstallConfigurationModel(this);
280
281         // notify listeners
282
Object JavaDoc[] configurationListeners = listeners.getListeners();
283         for (int i = 0; i < configurationListeners.length; i++) {
284             IInstallConfigurationChangedListener listener = ((IInstallConfigurationChangedListener) configurationListeners[i]);
285             listener.installSiteAdded(site);
286         }
287
288         // everything done ok
289
activity.setStatus(IActivity.STATUS_OK);
290         this.addActivity(activity);
291     }
292
293     /**
294      * Method addActivity.
295      * @param activity
296      */

297     public void addActivity(IActivity activity) {
298         addActivityModel((ConfigurationActivityModel)activity);
299     }
300
301     /*
302      *
303      */

304     public void removeConfiguredSite(IConfiguredSite site) {
305         if (!isCurrent() && isReadOnly())
306             return;
307
308         if (removeConfigurationSiteModel((ConfiguredSiteModel) site)) {
309             // notify listeners
310
Object JavaDoc[] configurationListeners = listeners.getListeners();
311             for (int i = 0; i < configurationListeners.length; i++) {
312                 IInstallConfigurationChangedListener listener = ((IInstallConfigurationChangedListener) configurationListeners[i]);
313                 listener.installSiteRemoved(site);
314             }
315             
316             //activity
317
ConfigurationActivity activity = new ConfigurationActivity(IActivity.ACTION_SITE_REMOVE);
318             activity.setLabel(site.getSite().getURL().toExternalForm());
319             activity.setDate(new Date JavaDoc());
320             activity.setStatus(IActivity.STATUS_OK);
321             this.addActivity(activity);
322         }
323     }
324
325     /*
326      * @see IInstallConfiguration#addInstallConfigurationChangedListener(IInstallConfigurationChangedListener)
327      */

328     public void addInstallConfigurationChangedListener(IInstallConfigurationChangedListener listener) {
329         synchronized (listeners) {
330             listeners.add(listener);
331         }
332     }
333
334     /*
335      * @see IInstallConfiguration#removeInstallConfigurationChangedListener(IInstallConfigurationChangedListener)
336      */

337     public void removeInstallConfigurationChangedListener(IInstallConfigurationChangedListener listener) {
338         synchronized (listeners) {
339             listeners.remove(listener);
340         }
341     }
342
343
344     /*
345      * Deletes the configuration from its URL/location
346      */

347     public void remove() {
348         // save the configuration
349
if ("file".equalsIgnoreCase(getURL().getProtocol())) { //$NON-NLS-1$
350
// the location points to a file
351
File JavaDoc file = new File JavaDoc(getURL().getFile());
352             UpdateManagerUtils.removeFromFileSystem(file);
353         }
354     }
355
356     /**
357      * Saves the configuration into its URL/location
358      * and changes the platform configuration.
359      * The runtime site entries from platform.xml are updated as required
360      * (cannot recreate these because must preserve other runtime state) [18520]
361      * @return true if restart is needed
362      */

363     public boolean save() throws CoreException {
364         
365         // Write info into platform for the next runtime
366
IPlatformConfiguration runtimeConfiguration = ConfiguratorUtils.getCurrentPlatformConfiguration();
367         ConfiguredSiteModel[] configurationSites = getConfigurationSitesModel();
368
369         // clean configured Entries from platform runtime
370
IPlatformConfiguration.IFeatureEntry[] configuredFeatureEntries = runtimeConfiguration.getConfiguredFeatureEntries();
371         for (int i = 0; i < configuredFeatureEntries.length; i++) {
372             runtimeConfiguration.unconfigureFeatureEntry(configuredFeatureEntries[i]);
373         }
374
375         // [19958] remember sites currently configured by runtime (use
376
// temp configuration object rather than a straight list to ensure
377
// correct lookup)
378
IPlatformConfiguration tempConfig = null;
379         try {
380             tempConfig = ConfiguratorUtils.getPlatformConfiguration(null);
381             IPlatformConfiguration.ISiteEntry[] tmpSites = runtimeConfiguration.getConfiguredSites();
382             for (int i = 0; i < tmpSites.length; i++) {
383                 tempConfig.configureSite(tmpSites[i]);
384             }
385         } catch (IOException JavaDoc e) {
386             // assume no currently configured sites
387
}
388
389         //check sites
390
checkSites(configurationSites, runtimeConfiguration);
391
392         // Save the plugin path, primary feature and platform
393
for (int i = 0; i < configurationSites.length; i++) {
394             ConfiguredSite cSite = ((ConfiguredSite) configurationSites[i]);
395             ConfigurationPolicy configurationPolicy = cSite.getConfigurationPolicy();
396
397             savePluginPath(cSite, runtimeConfiguration, tempConfig);
398
399             // IF primary feature URL or platform feature URL that we need to pass to runtime config
400
// is part of platform:base:, write it as platform:base: URL
401
IFeatureReference[] configuredFeaturesRef = configurationPolicy.getConfiguredFeatures();
402             for (int j = 0; j < configuredFeaturesRef.length; j++) {
403                 IFeature feature = null;
404                 try {
405                     feature = configuredFeaturesRef[j].getFeature(null);
406                 } catch (CoreException e) {
407                     UpdateCore.warn(null, e);
408                 }
409                 saveFeatureEntry(cSite, feature, runtimeConfiguration);
410             }
411         }
412
413         // [19958] remove any extra site entries from runtime configuration
414
// (site entries that no longer exist in this configuration)
415
if (tempConfig != null) {
416             IPlatformConfiguration.ISiteEntry[] tmpSites = tempConfig.getConfiguredSites();
417             for (int i = 0; i < tmpSites.length; i++) {
418                 runtimeConfiguration.unconfigureSite(tmpSites[i]);
419             }
420         }
421
422         try {
423             runtimeConfiguration.save();
424             // log configuration and activities
425
this.date = new Date JavaDoc(runtimeConfiguration.getChangeStamp());
426             if ("file".equalsIgnoreCase(getURL().getProtocol())) //$NON-NLS-1$
427
UpdateCore.log(this);
428             resetActivities();
429             return isRestartNeeded(runtimeConfiguration);
430         } catch (IOException JavaDoc e) {
431             CoreException exc = Utilities.newCoreException(NLS.bind(Messages.InstallConfiguration_UnableToSavePlatformConfiguration, (new String JavaDoc[] { runtimeConfiguration.getConfigurationLocation().toExternalForm() })), e);
432             UpdateCore.warn("",exc); //$NON-NLS-1$
433
}
434         return true;
435     }
436
437     /*
438      * Write the plugin path for each site
439      * Do not check if the site already existed before [16696].
440      * Reuse any runtime site objects in platform.cfg (to preserve state) [18520].
441      */

442     private void savePluginPath(ConfiguredSite cSite, IPlatformConfiguration runtimeConfiguration, IPlatformConfiguration tempConfig) // [19958]
443
throws CoreException {
444
445         ConfigurationPolicy configurationPolicy = cSite.getConfigurationPolicy();
446
447         // create a ISitePolicy (policy, pluginPath)
448
// for the site
449
String JavaDoc[] pluginPath = configurationPolicy.getPluginPath(cSite.getSite());
450         IPlatformConfiguration.ISitePolicy sitePolicy = runtimeConfiguration.createSitePolicy(configurationPolicy.getPolicy(), pluginPath);
451
452         // get the URL of the site that matches the one platform.cfg gave us
453
URL JavaDoc urlToCheck = null;
454         try {
455             urlToCheck = new URL JavaDoc(cSite.getPlatformURLString());
456         } catch (MalformedURLException JavaDoc e) {
457             throw Utilities.newCoreException(NLS.bind(Messages.InstallConfiguration_UnableToCreateURL, (new String JavaDoc[] { cSite.getPlatformURLString() })), e);
458         } catch (ClassCastException JavaDoc e) {
459             throw Utilities.newCoreException(Messages.InstallConfiguration_UnableToCast, e);
460         }
461
462         // update runtime configuration [18520]
463
// Note: we must not blindly replace the site entries because they
464
// contain additional runtime state that needs to be preserved.
465
IPlatformConfiguration.ISiteEntry siteEntry = runtimeConfiguration.findConfiguredSite(urlToCheck);
466         if (siteEntry == null)
467             siteEntry = runtimeConfiguration.createSiteEntry(urlToCheck, sitePolicy);
468         else {
469             siteEntry.setSitePolicy(sitePolicy);
470             ((SiteEntry)siteEntry).refreshPlugins();
471             if (tempConfig != null) // [19958] remove reused entries from list
472
tempConfig.unconfigureSite(siteEntry);
473         }
474         ((SiteEntry)siteEntry).setEnabled(cSite.isEnabled());
475         runtimeConfiguration.configureSite(siteEntry, true /*replace if exists*/);
476     }
477
478     /*
479      * Save the Feature entry
480      * The feature can be a primary feature and/or a platform feature
481      */

482     private void saveFeatureEntry(ConfiguredSite cSite, IFeature feature, IPlatformConfiguration runtimeConfiguration) throws CoreException {
483         if (feature == null)
484             return;
485
486         // get the URL of the plugin that corresponds to the feature (pluginid = featureid)
487
String JavaDoc id = feature.getVersionedIdentifier().getIdentifier();
488         IPluginEntry[] entries = feature.getPluginEntries();
489         URL JavaDoc url = null;
490         IPluginEntry featurePlugin = null;
491         for (int k = 0; k < entries.length; k++) {
492             if (id.equalsIgnoreCase(entries[k].getVersionedIdentifier().getIdentifier())) {
493                 url = getRuntimeConfigurationURL(entries[k], cSite);
494                 featurePlugin = entries[k];
495                 break;
496             }
497         }
498         String JavaDoc pluginVersion = null;
499         if (featurePlugin != null)
500             pluginVersion = featurePlugin.getVersionedIdentifier().getVersion().toString();
501
502         // Find the site
503
SiteEntry siteEntry = null;
504         try {
505             URL JavaDoc featureUrl = new URL JavaDoc(cSite.getPlatformURLString());
506             siteEntry = (SiteEntry)runtimeConfiguration.findConfiguredSite(featureUrl);
507         } catch (MalformedURLException JavaDoc e) {
508             throw Utilities.newCoreException(NLS.bind(Messages.InstallConfiguration_UnableToCreateURL, (new String JavaDoc[] { cSite.getPlatformURLString() })), e);
509         } catch (ClassCastException JavaDoc e) {
510             throw Utilities.newCoreException(Messages.InstallConfiguration_UnableToCast, e);
511         }
512
513         // if the URL doesn't exist throw a CoreException
514
if (siteEntry == null) {
515             throw new CoreException(
516                     new Status(IStatus.ERROR, UpdateCore.getPlugin().getBundle().getSymbolicName(),
517                             NLS.bind(Messages.InstallConfiguration_unableToFindSite, (new String JavaDoc[] { cSite.getSite().getURL().toExternalForm(), runtimeConfiguration.getConfigurationLocation().toExternalForm() }))));
518         }
519
520         // write the primary features
521
if (feature.isPrimary()) {
522             // get any fragments for the feature plugin
523
ArrayList JavaDoc list = new ArrayList JavaDoc();
524             if (url != null)
525                 list.add(url);
526             if (featurePlugin != null) {
527                 URL JavaDoc[] fragments = getRuntimeFragmentURLs(featurePlugin);
528                 list.addAll(Arrays.asList(fragments));
529             }
530             URL JavaDoc[] roots = (URL JavaDoc[]) list.toArray(new URL JavaDoc[0]);
531             String JavaDoc pluginIdentifier = feature.getPrimaryPluginID();
532
533             // save information in runtime platform state
534
String JavaDoc version = feature.getVersionedIdentifier().getVersion().toString();
535             String JavaDoc application = feature.getApplication();
536             FeatureEntry featureEntry = (FeatureEntry)runtimeConfiguration.createFeatureEntry(id, version, pluginIdentifier, pluginVersion, true, application, roots);
537             featureEntry.setURL(getFeatureRelativeURL(feature));
538             siteEntry.addFeatureEntry(featureEntry);
539         } else {
540             // write non-primary feature entries
541
String JavaDoc version = feature.getVersionedIdentifier().getVersion().toString();
542             String JavaDoc pluginIdentifier = feature.getPrimaryPluginID();
543             FeatureEntry featureEntry = (FeatureEntry)runtimeConfiguration.createFeatureEntry(id, version, pluginIdentifier, pluginVersion, false, null, null);
544             featureEntry.setURL(getFeatureRelativeURL(feature));
545             siteEntry.addFeatureEntry(featureEntry);
546         }
547
548         // write the platform features (features that contain special platform plugins)
549
IPluginEntry[] platformPlugins = getPlatformPlugins(feature, runtimeConfiguration);
550         for (int k = 0; k < platformPlugins.length; k++) {
551             id = platformPlugins[k].getVersionedIdentifier().getIdentifier();
552             url = getRuntimeConfigurationURL(platformPlugins[k], cSite);
553             if (url != null) {
554                 runtimeConfiguration.setBootstrapPluginLocation(id, url);
555             }
556         }
557     }
558
559     /*
560      * Log if we are about to create a site that didn't exist before
561      * in platform.cfg [16696].
562      */

563     private void checkSites(ConfiguredSiteModel[] configurationSites, IPlatformConfiguration runtimeConfiguration) throws CoreException {
564
565         // check all the sites we are about to write already existed
566
// they should have existed either because they were created by
567
// updateManager or because we read them from platform.cfg
568
for (int i = 0; i < configurationSites.length; i++) {
569             // get the URL of the site that matches the one platform.cfg gave us
570
URL JavaDoc urlToCheck = null;
571             try {
572                 urlToCheck = new URL JavaDoc(configurationSites[i].getPlatformURLString());
573             } catch (MalformedURLException JavaDoc e) {
574                 UpdateCore.warn(NLS.bind(Messages.InstallConfiguration_UnableToCreateURL, (new String JavaDoc[] { configurationSites[i].getPlatformURLString() })), e);
575             } catch (ClassCastException JavaDoc e) {
576                 UpdateCore.warn(Messages.InstallConfiguration_UnableToCast, e);
577             }
578
579             // if the URL doesn't exits log it
580
IPlatformConfiguration.ISiteEntry siteEntry = runtimeConfiguration.findConfiguredSite(urlToCheck);
581             if (siteEntry == null) {
582                 UpdateCore.warn(NLS.bind(Messages.InstallConfiguration_unableToFindSite, (new String JavaDoc[] { urlToCheck.toExternalForm(), runtimeConfiguration.getConfigurationLocation().toExternalForm() })));
583             }
584         }
585     }
586
587
588     /*
589      * reverts this configuration to the match the new one
590      *
591      * Compare the oldSites with the currentOne. the old state is the state we want to revert to.
592      *
593      * If a site was in old state, but not in the currentOne, keep it in the hash.
594      * If a site is in the currentOne but was not in the old state, unconfigure all features and add it in the hash
595      * If a site was in baoth state, calculate the 'delta' and re-set it in the hash map
596      *
597      * At the end, set the configured site from the new sites hash map
598      *
599      */

600     public void revertTo(IInstallConfiguration configuration, IProgressMonitor monitor, IProblemHandler handler) throws CoreException, InterruptedException JavaDoc {
601
602         IConfiguredSite[] oldConfigSites = configuration.getConfiguredSites();
603         IConfiguredSite[] nowConfigSites = this.getConfiguredSites();
604
605         // create a hashtable of the *old* and *new* sites
606
Map JavaDoc oldSitesMap = new Hashtable JavaDoc(0);
607         Map JavaDoc newSitesMap = new Hashtable JavaDoc(0);
608         for (int i = 0; i < oldConfigSites.length; i++) {
609             IConfiguredSite element = oldConfigSites[i];
610             oldSitesMap.put(element.getSite().getURL().toExternalForm(), element);
611             newSitesMap.put(element.getSite().getURL().toExternalForm(), element);
612         }
613         // create list of all the sites that map the *old* sites
614
// we want the intersection between the old sites and the current sites
615
if (nowConfigSites != null) {
616             String JavaDoc key = null;
617
618             for (int i = 0; i < nowConfigSites.length; i++) {
619                 key = nowConfigSites[i].getSite().getURL().toExternalForm();
620                 IConfiguredSite oldSite = (IConfiguredSite) oldSitesMap.get(key);
621                 if (oldSite != null) {
622                     // the Site existed before, calculate the delta between its current state and the
623
// state we are reverting to and put it back into the map
624
((ConfiguredSite) nowConfigSites[i]).revertTo(oldSite, monitor, handler);
625                 } else {
626                     // the site didn't exist in the InstallConfiguration we are reverting to
627
// unconfigure everything from this site so it is still present
628
ISiteFeatureReference[] featuresToUnconfigure = nowConfigSites[i].getSite().getFeatureReferences();
629                     for (int j = 0; j < featuresToUnconfigure.length; j++) {
630                         IFeature featureToUnconfigure = null;
631                         try {
632                             featureToUnconfigure = featuresToUnconfigure[j].getFeature(null);
633                         } catch (CoreException e) {
634                             UpdateCore.warn(null, e);
635                         }
636                         if (featureToUnconfigure != null)
637                             nowConfigSites[i].unconfigure(featureToUnconfigure);
638                     }
639                 }
640                 newSitesMap.put(key,nowConfigSites[i]);
641             }
642
643             // the new configuration has the exact same sites as the old configuration
644
// the old configuration in the Map are either as-is because they don't exist
645
// in the current one, or they are the delta from the current one to the old one
646
Collection JavaDoc sites = newSitesMap.values();
647             if (sites != null && !sites.isEmpty()) {
648                 ConfiguredSiteModel[] sitesModel = new ConfiguredSiteModel[sites.size()];
649                 sites.toArray(sitesModel);
650                 setConfigurationSiteModel(sitesModel);
651             }
652         }
653     }
654
655     /*
656      * @see IInstallConfiguration#getActivities()
657      */

658     public IActivity[] getActivities() {
659         if (getActivityModel().length == 0)
660             return new IActivity[0];
661         return (IActivity[]) getActivityModel();
662     }
663
664     /*
665      * returns the list of platform plugins of the feature or an empty list
666      * if the feature doesn't contain any platform plugins
667      */

668     private IPluginEntry[] getPlatformPlugins(IFeature feature, IPlatformConfiguration runtimeConfiguration) {
669         Map JavaDoc featurePlatformPlugins = new HashMap JavaDoc();
670         String JavaDoc[] platformPluginID = runtimeConfiguration.getBootstrapPluginIdentifiers();
671         IPluginEntry[] featurePlugins = feature.getPluginEntries();
672
673         for (int i = 0; i < platformPluginID.length; i++) {
674             String JavaDoc featurePluginId = null;
675             for (int j = 0; j < featurePlugins.length; j++) {
676                 featurePluginId = featurePlugins[j].getVersionedIdentifier().getIdentifier();
677                 if (platformPluginID[i].equals(featurePluginId)) {
678                     featurePlatformPlugins.put(platformPluginID[i], featurePlugins[j]);
679                 }
680             }
681         }
682
683         Collection JavaDoc values = featurePlatformPlugins.values();
684         if (values == null || values.size() == 0)
685             return new IPluginEntry[0];
686
687         IPluginEntry[] result = new IPluginEntry[values.size()];
688         Iterator JavaDoc iter = values.iterator();
689         int index = 0;
690         while (iter.hasNext()) {
691             result[index] = ((IPluginEntry) iter.next());
692             index++;
693         }
694         return result;
695     }
696
697     /*
698      * returns the URL of the pluginEntry on the site
699      * Transform the URL to use platform: protocol if needed
700      * return null if the URL to write is not valid
701      */

702     private URL JavaDoc getRuntimeConfigurationURL(IPluginEntry entry, ConfiguredSite cSite) throws CoreException {
703
704         String JavaDoc rootString = cSite.getPlatformURLString();
705         String JavaDoc pluginPathID = getPathID(entry);
706         try {
707             ISiteContentProvider siteContentProvider = cSite.getSite().getSiteContentProvider();
708             URL JavaDoc pluginEntryfullURL = siteContentProvider.getArchiveReference(pluginPathID);
709
710             //
711
if (!rootString.startsWith("platform")) { //$NON-NLS-1$
712
// DEBUG:
713
if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_CONFIGURATION)
714                     UpdateCore.debug("getRuntimeConfiguration Plugin Entry Full URL:" + pluginEntryfullURL + " Platform String:" + rootString + " [NON PLATFORM URL]."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
715
return pluginEntryfullURL;
716             }
717
718             //URL pluginEntryRootURL = Platform.resolve(new URL(rootString));
719
// Do not resolve [16507], just use platform:base/ as a root
720
// rootString = platform:base
721
// pluginRoot = /home/a
722
// pluginFull = /home/a/c/boot.jar
723
// relative = platform:/base/c/boot.jar
724
URL JavaDoc pluginEntryRootURL = cSite.getSite().getURL();
725             String JavaDoc relativeString = UpdateManagerUtils.getURLAsString(pluginEntryRootURL, pluginEntryfullURL);
726             URL JavaDoc result = new URL JavaDoc(new URL JavaDoc(rootString), relativeString);
727
728             // DEBUG:
729
if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_CONFIGURATION)
730                 UpdateCore.debug("getRuntimeConfiguration plugin Entry Full URL:" + pluginEntryfullURL + " Platform String:" + rootString + " Site URL:" + pluginEntryRootURL + " Relative:" + relativeString); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
731

732             // verify we are about to write a valid file URL
733
// check with fullURL as it is not resolved to platform:base/
734
if (pluginEntryfullURL != null) {
735                 if ("file".equals(pluginEntryfullURL.getProtocol())) { //$NON-NLS-1$
736
String JavaDoc fileString = pluginEntryfullURL.getFile();
737                     if (!new File JavaDoc(fileString).exists()) {
738                         UpdateCore.warn("The URL:" + result + " doesn't point to a valid platform plugin.The URL will not be written in the platform configuration", new Exception JavaDoc()); //$NON-NLS-1$ //$NON-NLS-2$
739
return null;
740                     }
741                 }
742             }
743
744             return result;
745         } catch (IOException JavaDoc e) {
746             throw Utilities.newCoreException(NLS.bind(Messages.InstallConfiguration_UnableToCreateURL, (new String JavaDoc[] { rootString })), e);
747         }
748     }
749
750     /*
751      * Return URLs for any fragments that are associated with the specified plugin entry
752      */

753     private URL JavaDoc[] getRuntimeFragmentURLs(IPluginEntry entry) throws CoreException {
754
755         // get the identifier associated with the entry
756
VersionedIdentifier vid = entry.getVersionedIdentifier();
757
758         // get the plugin descriptor from the registry
759
Bundle bundle = Platform.getBundle(vid.getIdentifier());
760         ArrayList JavaDoc list = new ArrayList JavaDoc();
761         if (bundle != null && bundle.getState() != Bundle.UNINSTALLED && bundle.getState() != Bundle.INSTALLED) {
762             FragmentEntry[] fragments = UpdateManagerUtils.getFragments(bundle);
763             for (int i = 0; fragments != null && i < fragments.length; i++) {
764                 String JavaDoc location = fragments[i].getLocation();
765                 try {
766                     URL JavaDoc locationURL = new URL JavaDoc(location);
767                     locationURL = FileLocator.toFileURL(FileLocator.resolve(locationURL));
768                     list.add(asInstallRelativeURL(locationURL));
769                 } catch (IOException JavaDoc e) {
770                     // skip bad fragments
771
}
772             }
773         }
774         return (URL JavaDoc[]) list.toArray(new URL JavaDoc[0]);
775     }
776
777     /**
778      * Returns the path identifier for a plugin entry.
779      * <code>plugins/&lt;pluginId>_&lt;pluginVersion>.jar</code>
780      * @return the path identifier
781      */

782     private String JavaDoc getPathID(IPluginEntry entry) {
783         return Site.DEFAULT_PLUGIN_PATH + entry.getVersionedIdentifier().toString() + FeatureContentProvider.JAR_EXTENSION;
784     }
785
786     /**
787      * Try to recast URL as platform:/base/
788      */

789     private URL JavaDoc asInstallRelativeURL(URL JavaDoc url) {
790         // get location of install
791
URL JavaDoc install = ConfiguratorUtils.getInstallURL();
792
793         // try to determine if supplied URL can be recast as install-relative
794
if (install.getProtocol().equals(url.getProtocol())) {
795             if (install.getProtocol().equals("file")) { //$NON-NLS-1$
796
String JavaDoc installS = new File JavaDoc(install.getFile()).getAbsolutePath().replace(File.separatorChar, '/');
797                 if (!installS.endsWith("/")) //$NON-NLS-1$
798
installS += "/"; //$NON-NLS-1$
799
String JavaDoc urlS = new File JavaDoc(url.getFile()).getAbsolutePath().replace(File.separatorChar, '/');
800                 if (!urlS.endsWith("/")) //$NON-NLS-1$
801
urlS += "/"; //$NON-NLS-1$
802
int ix = installS.lastIndexOf("/"); //$NON-NLS-1$
803
if (ix != -1) {
804                     installS = installS.substring(0, ix + 1);
805                     if (urlS.startsWith(installS)) {
806                         try {
807                             return new URL JavaDoc("platform:/base/" + urlS.substring(installS.length())); //$NON-NLS-1$
808
} catch (MalformedURLException JavaDoc e) {
809                         }
810                     }
811                 }
812             }
813         }
814         return url;
815     }
816     
817     private boolean isDuplicateSite(File JavaDoc siteDirectory) {
818         IConfiguredSite[] sites = getConfiguredSites();
819         URL JavaDoc fileURL;
820         try {
821             fileURL = siteDirectory.toURL();
822         } catch (MalformedURLException JavaDoc e) {
823             return false;
824         }
825         for (int i = 0; i < sites.length; i++) {
826             URL JavaDoc url = sites[i].getSite().getURL();
827             if (UpdateManagerUtils.sameURL(fileURL, url))
828                 return true;
829         }
830         return false;
831     }
832     
833     /*
834      * Returns the feature url relative to the site.
835      */

836     private String JavaDoc getFeatureRelativeURL(IFeature feature) {
837         String JavaDoc url = feature.getURL().toExternalForm();
838         String JavaDoc siteURL = feature.getSite().getURL().toExternalForm();
839         // TODO fix this. toURL() returns file:/d:/eclipse/etc... wheareas the
840
// platform.asLocalURL() returns file:d:/eclipse/etc... (no leading / )
841
// if (url.startsWith("file:/") && Platform.getOS().equals("win32"))
842
// url = "file:" + url.substring(6);
843

844         if (url.startsWith(siteURL))
845             return url.substring(siteURL.length());
846         else
847             return url;
848     }
849     
850     /**
851      * @return true if restart is needed
852      */

853     private boolean isRestartNeeded(IPlatformConfiguration runtimeConfig) {
854
855         // First, create a map for faster lookups
856
Set JavaDoc newPluginsSet = null;
857         if (runtimeConfig instanceof PlatformConfiguration) {
858             newPluginsSet = ((PlatformConfiguration)runtimeConfig).getPluginPaths();
859             // On windows, we will be doing case insensitive search as well, so lower it now
860
if (isWindows) {
861                 String JavaDoc[] newPluginsSetArray = (String JavaDoc[])newPluginsSet.toArray( new String JavaDoc[newPluginsSet.size()]);
862                 for (int i = 0; i < newPluginsSetArray.length; i++) {
863                     newPluginsSet.add(newPluginsSetArray[i].toLowerCase());
864                 }
865             }
866         } else {
867             URL JavaDoc[] newBundlePaths = runtimeConfig.getPluginPath();
868             newPluginsSet = new HashSet JavaDoc(newBundlePaths.length);
869             for (int i=0; i<newBundlePaths.length; i++) {
870                 
871                 String JavaDoc pluginLocation = newBundlePaths[i].getFile();
872                 newPluginsSet.add(pluginLocation);
873                 // On windows, we will be doing case insensitive search as well, so lower it now
874
if (isWindows)
875                     newPluginsSet.add(pluginLocation.toLowerCase());
876             }
877         }
878         
879         
880         
881         Bundle[] oldBundles = UpdateCore.getPlugin().getBundleContext().getBundles();
882
883         int offset = ConfigurationActivator.UPDATE_PREFIX.length();
884         for (int i=0; i<oldBundles.length; i++) {
885             if (oldBundles[i].getBundleId() == 0)
886                 continue; // skip the system bundle
887
String JavaDoc oldBundleLocation = oldBundles[i].getLocation();
888             // Don't worry about bundles we did not install
889
if (!oldBundleLocation.startsWith(ConfigurationActivator.UPDATE_PREFIX))
890                 continue;
891             oldBundleLocation = oldBundleLocation.substring(offset);
892             
893             if (newPluginsSet.contains(oldBundleLocation))
894                 continue;
895             if (isWindows && newPluginsSet.contains(oldBundleLocation.toLowerCase()))
896                 continue;
897             
898             if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_CONFIGURATION)
899                 UpdateCore.debug("Bundle " + oldBundleLocation + " has been removed"); //$NON-NLS-1$ //$NON-NLS-2$
900
return true;
901         }
902         
903         if (runtimeConfig instanceof PlatformConfiguration) {
904             return areThereNewVersionOfOldPlugins( ((PlatformConfiguration)runtimeConfig).getPlugins(), oldBundles);
905         }
906
907         return false;
908     }
909     
910     /**
911      * The method should only be called if all old plug-ins exist in the new
912      * configuration. Determines if a new version was added to any plugin ID, so
913      * more versions are enabled for any given plug-in id then in old
914      * configuration.
915      *
916      * @param newConfigurationPlugins
917      * @param oldConfigurationBundles
918      * @return
919      */

920     private boolean areThereNewVersionOfOldPlugins(PluginEntry[] newConfigurationPlugins, Bundle[] oldConfigurationBundles) {
921
922         
923         for ( int i = 0; i < oldConfigurationBundles.length; i++) {
924             if (oldConfigurationBundles[i].getBundleId() == 0)
925                 continue; // skip the system bundle
926
if ( getNumberOfPlugins(oldConfigurationBundles[i].getSymbolicName(), oldConfigurationBundles) != getNumberOfPlugins(oldConfigurationBundles[i].getSymbolicName(), newConfigurationPlugins)) {
927                 return true;
928             }
929         }
930         return false;
931     }
932
933     private int getNumberOfPlugins(String JavaDoc symbolicName, PluginEntry[] newConfigurationPlugins) {
934         
935         int numberOfPlugins = 0;
936         
937         for ( int i = 0; i < newConfigurationPlugins.length; i++) {
938             if ( symbolicName.equals(newConfigurationPlugins[i].getPluginIdentifier())) {
939                 numberOfPlugins++;
940             }
941         }
942         
943         return numberOfPlugins;
944     }
945
946     private int getNumberOfPlugins(String JavaDoc symbolicName, Bundle[] oldConfigurationBundles) {
947
948         int numberOfPlugins = 0;
949         
950         for ( int i = 0; i < oldConfigurationBundles.length; i++) {
951             if ( symbolicName.equals(oldConfigurationBundles[i].getSymbolicName())) {
952                 numberOfPlugins++;
953             }
954         }
955         
956         return numberOfPlugins;
957     }
958
959     /* (non-Javadoc)
960      * @see java.lang.Object#equals(java.lang.Object)
961      */

962     public boolean equals(Object JavaDoc obj) {
963         if (this == obj)
964             return true;
965         if (!(obj instanceof InstallConfiguration))
966             return false;
967         
968         InstallConfiguration config = (InstallConfiguration)obj;
969     
970         return getCreationDate().equals(config.getCreationDate()) &&
971                 getLabel().equals(config.getLabel()) &&
972                 getLocationURLString().equals(config.getLocationURLString());
973     }
974 }
975
Popular Tags