KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 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
14 import java.io.File JavaDoc;
15 import java.io.FileInputStream JavaDoc;
16 import java.io.FileOutputStream JavaDoc;
17 import java.io.IOException JavaDoc;
18 import java.io.InputStream JavaDoc;
19 import java.io.OutputStream JavaDoc;
20 import java.io.OutputStreamWriter JavaDoc;
21 import java.net.MalformedURLException JavaDoc;
22 import java.net.URL JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Arrays JavaDoc;
25 import java.util.Date JavaDoc;
26 import java.util.HashSet JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.MissingResourceException JavaDoc;
30 import java.util.PropertyResourceBundle JavaDoc;
31 import java.util.Set JavaDoc;
32 import org.eclipse.core.runtime.CoreException;
33 import org.eclipse.core.runtime.FileLocator;
34 import org.eclipse.core.runtime.IProgressMonitor;
35 import org.eclipse.core.runtime.IStatus;
36 import org.eclipse.core.runtime.MultiStatus;
37 import org.eclipse.core.runtime.Platform;
38 import org.eclipse.osgi.util.NLS;
39 import org.eclipse.update.configuration.IActivity;
40 import org.eclipse.update.configuration.IConfiguredSite;
41 import org.eclipse.update.configuration.IConfiguredSiteChangedListener;
42 import org.eclipse.update.configuration.IInstallConfiguration;
43 import org.eclipse.update.configuration.IProblemHandler;
44 import org.eclipse.update.configurator.ConfiguratorUtils;
45 import org.eclipse.update.configurator.IPlatformConfiguration;
46 import org.eclipse.update.core.IFeature;
47 import org.eclipse.update.core.IFeatureReference;
48 import org.eclipse.update.core.IIncludedFeatureReference;
49 import org.eclipse.update.core.IPluginEntry;
50 import org.eclipse.update.core.ISite;
51 import org.eclipse.update.core.ISiteFeatureReference;
52 import org.eclipse.update.core.IVerificationListener;
53 import org.eclipse.update.core.SiteManager;
54 import org.eclipse.update.core.Utilities;
55 import org.eclipse.update.core.VersionedIdentifier;
56 import org.eclipse.update.core.model.InstallAbortedException;
57 import org.eclipse.update.internal.model.ConfiguredSiteModel;
58 import org.eclipse.update.internal.operations.UpdateUtils;
59
60 /**
61  * A Configured site manages the Configured and unconfigured features of a Site
62  */

63 public class ConfiguredSite extends ConfiguredSiteModel implements IConfiguredSite {
64
65     private static final String JavaDoc PRODUCT_SITE_MARKER = ".eclipseproduct"; //$NON-NLS-1$
66
private static final String JavaDoc EXTENSION_SITE_MARKER = ".eclipseextension"; //$NON-NLS-1$
67

68     // listeners
69
private ListenersList listeners = new ListenersList();
70
71     // verification status
72
private IStatus verifyStatus;
73
74     // transient: true if the site was just created so we can remove it
75
private transient boolean justCreated = false;
76
77     /*
78      * Default Constructor
79      */

80     public ConfiguredSite() {
81     }
82
83     /*
84      * Copy Constructor
85      * As of now, configSite can only be of type ConfiguredSite
86      */

87     public ConfiguredSite(IConfiguredSite configSite) {
88         ConfiguredSite cSite = (ConfiguredSite) configSite;
89         setSiteModel(cSite.getSiteModel());
90         setConfigurationPolicyModel(new ConfigurationPolicy(cSite.getConfigurationPolicy()));
91         setUpdatable(cSite.isUpdatable());
92         setEnabled(cSite.isEnabled());
93         setPreviousPluginPath(cSite.getPreviousPluginPath());
94         setPlatformURLString(cSite.getPlatformURLString());
95     }
96
97     /*
98      * Adds a listener
99      */

100     public void addConfiguredSiteChangedListener(IConfiguredSiteChangedListener listener) {
101         synchronized (listeners) {
102             listeners.add(listener);
103         }
104     }
105
106     /*
107      * Removes a listener
108      */

109     public void removeConfiguredSiteChangedListener(IConfiguredSiteChangedListener listener) {
110         synchronized (listeners) {
111             listeners.remove(listener);
112         }
113     }
114
115     /*
116      * @see IConfiguredSite#install(IFeature,IVerificationListener, IProgressMonitor)
117      */

118     public IFeatureReference install(IFeature feature, IVerificationListener verificationListener, IProgressMonitor monitor) throws InstallAbortedException, CoreException {
119         return install(feature, null, verificationListener, monitor);
120     }
121
122     /*
123      * @see IConfiguredSite#install(IFeature, IFeatureReference, IVerificationListener, IProgressMonitor)
124      */

125     public IFeatureReference install(IFeature feature, IFeatureReference[] optionalFeatures, IVerificationListener verificationListener, IProgressMonitor monitor) throws InstallAbortedException, CoreException {
126
127         // change the status if justCreated
128
if (justCreated) justCreated=false;
129
130         // ConfigSite is read only
131
if (!isUpdatable()) {
132             String JavaDoc errorMessage = NLS.bind(Messages.ConfiguredSite_NonInstallableSite, (new String JavaDoc[] { getSite().getURL().toExternalForm() }));
133             IStatus status = verifyUpdatableStatus();
134             if (status != null)
135                 errorMessage += " " + status.getMessage(); //$NON-NLS-1$
136
throw Utilities.newCoreException(errorMessage, null);
137         }
138
139         // feature is null
140
if (feature == null) {
141             String JavaDoc errorMessage = Messages.ConfiguredSite_NullFeatureToInstall;
142             throw Utilities.newCoreException(errorMessage, null);
143         }
144
145         // feature reference to return
146
IFeatureReference installedFeatureRef;
147         IFeature installedFeature = null;
148
149         // create the Activity (INSTALL)
150
ConfigurationActivity activity = new ConfigurationActivity(IActivity.ACTION_FEATURE_INSTALL);
151         activity.setLabel(feature.getVersionedIdentifier().toString());
152         activity.setDate(new Date JavaDoc());
153
154         try {
155             installedFeatureRef = getSite().install(feature, optionalFeatures, verificationListener, monitor);
156
157             if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_INSTALL) {
158                 UpdateCore.debug("Sucessfully installed: " + installedFeatureRef.getURL().toExternalForm()); //$NON-NLS-1$
159
}
160
161             if (installedFeatureRef != null) {
162                 try {
163                     installedFeature = installedFeatureRef.getFeature(null);
164                 } catch (CoreException e) {
165                     UpdateCore.warn(null, e);
166                 }
167             }
168
169             // everything done ok
170
activity.setStatus(IActivity.STATUS_OK);
171
172             // notify listeners
173
Object JavaDoc[] siteListeners = listeners.getListeners();
174             for (int i = 0; i < siteListeners.length; i++) {
175                 if (installedFeature != null) {
176                     IConfiguredSiteChangedListener listener = ((IConfiguredSiteChangedListener) siteListeners[i]);
177                     listener.featureInstalled(installedFeature);
178                 }
179             }
180         } catch (CoreException e) {
181             // not ok, set Activity status
182
activity.setStatus(IActivity.STATUS_NOK);
183             throw e;
184         } finally {
185             IInstallConfiguration current = SiteManager.getLocalSite().getCurrentConfiguration();
186             ((InstallConfiguration) current).addActivity(activity);
187         }
188         // call the configure task
189
if (installedFeature != null)
190             configure(installedFeature, optionalFeatures, true);
191         /*callInstallHandler*/
192
193         return installedFeatureRef;
194     }
195
196     /*
197      * @see IConfiguredSite#remove(IFeature, IProgressMonitor)
198      */

199     public void remove(IFeature feature, IProgressMonitor monitor) throws CoreException {
200
201         // ConfigSite is read only
202
if (!isUpdatable()) {
203             String JavaDoc errorMessage = NLS.bind(Messages.ConfiguredSite_NonUninstallableSite, (new String JavaDoc[] { getSite().getURL().toExternalForm() }));
204             throw Utilities.newCoreException(errorMessage, null);
205         }
206
207         // create the Activity
208
ConfigurationActivity activity = new ConfigurationActivity(IActivity.ACTION_FEATURE_REMOVE);
209         activity.setLabel(feature.getVersionedIdentifier().toString());
210         activity.setDate(new Date JavaDoc());
211
212         try {
213             IFeatureReference referenceToRemove = null;
214             ISiteFeatureReference[] featureRef = getSite().getFeatureReferences();
215             ISiteFeatureReference ref = getSite().getFeatureReference(feature);
216             for (int i = 0; i < featureRef.length; i++) {
217                 if (featureRef[i].equals(ref)) {
218                     referenceToRemove = featureRef[i];
219                     break;
220                 }
221             }
222
223             // we found a feature reference on the site matching the feature
224
if (referenceToRemove != null) {
225                 // Check if feature is unconfigured before we remove it
226
// our UI will check.
227
// For non-UI application, throw error is feature is configured
228
if (getConfigurationPolicy().isConfigured(referenceToRemove)) {
229                     IFeature featureToRemove = referenceToRemove.getFeature(null);
230                     String JavaDoc featureLabel = (featureToRemove == null) ? null : featureToRemove.getLabel();
231                     throw Utilities.newCoreException(NLS.bind(Messages.ConfiguredSite_UnableToRemoveConfiguredFeature, (new String JavaDoc[] { featureLabel })), null);
232                 }
233             } else {
234                 throw Utilities.newCoreException(NLS.bind(Messages.ConfiguredSite_UnableToFindFeature, (new String JavaDoc[] { feature.getURL().toString() })),
235                 null);
236             }
237
238             // remove the feature
239
getSite().remove(feature, monitor);
240             getConfigurationPolicy().removeFeatureReference(referenceToRemove);
241             // everything done ok
242
activity.setStatus(IActivity.STATUS_OK);
243             // notify listeners
244
Object JavaDoc[] siteListeners = listeners.getListeners();
245             for (int i = 0; i < siteListeners.length; i++) {
246                 ((IConfiguredSiteChangedListener) siteListeners[i]).featureRemoved(feature);
247             }
248         } catch (CoreException e) {
249             activity.setStatus(IActivity.STATUS_NOK);
250             throw e;
251         } finally {
252             IInstallConfiguration current = SiteManager.getLocalSite().getCurrentConfiguration();
253             ((InstallConfiguration) current).addActivity(activity);
254         }
255     }
256
257     /*
258      * @see IConfiguredSite#configure(IFeature)
259      */

260     public void configure(IFeature feature) throws CoreException {
261         configure(feature, null, true /*callInstallHandler*/
262         );
263     }
264
265     /*
266      *
267      */

268     private void configure(IFeature feature, IFeatureReference[] optionalFeatures, boolean callInstallHandler) throws CoreException {
269
270         if (feature == null) {
271             UpdateCore.warn("Attempting to configure a null feature in site:" + getSite().getURL().toExternalForm()); //$NON-NLS-1$
272
return;
273         }
274
275         ConfigurationPolicy configPolicy = getConfigurationPolicy();
276         if (configPolicy == null)
277             return;
278
279         // bottom up approach, same configuredSite
280
IIncludedFeatureReference[] childrenRef = feature.getIncludedFeatureReferences();
281         if (optionalFeatures != null) {
282             childrenRef = childrenToConfigure(childrenRef, optionalFeatures);
283         }
284
285         for (int i = 0; i < childrenRef.length; i++) {
286             try {
287                 IFeature child = childrenRef[i].getFeature(null);
288                 configure(child, optionalFeatures, callInstallHandler);
289             } catch (CoreException e) {
290                 // if not an optional feature, throw exception
291
if (!childrenRef[i].isOptional())
292                     UpdateCore.warn("Unable to configure child feature: " + childrenRef[i] + " " + e); //$NON-NLS-1$ //$NON-NLS-2$
293
throw e;
294             }
295         }
296
297         // configure root feature
298
IFeatureReference featureReference = getSite().getFeatureReference(feature);
299         configPolicy.configure(featureReference, callInstallHandler, true);
300
301         // notify listeners
302
Object JavaDoc[] siteListeners = listeners.getListeners();
303         for (int i = 0; i < siteListeners.length; i++) {
304             ((IConfiguredSiteChangedListener) siteListeners[i]).featureConfigured(feature);
305         }
306     }
307
308     /*
309      * Return the optional children to configure
310      *
311      * @param children all the nested features
312      * @param optionalfeatures optional features to install
313      * @return IFeatureReference[]
314      */

315     private IIncludedFeatureReference[] childrenToConfigure(IIncludedFeatureReference[] children, IFeatureReference[] optionalfeatures) {
316
317         List JavaDoc childrenToInstall = new ArrayList JavaDoc();
318         for (int i = 0; i < children.length; i++) {
319             IIncludedFeatureReference optionalFeatureToConfigure = children[i];
320             if (!optionalFeatureToConfigure.isOptional()) {
321                 childrenToInstall.add(optionalFeatureToConfigure);
322             } else {
323                 for (int j = 0; j < optionalfeatures.length; j++) {
324                     // must compare feature as optionalFeatures are from the install site
325
// where children are on the local site
326
try {
327                         IFeature installedChildren = optionalfeatures[j].getFeature(null);
328                         if (installedChildren.equals(optionalFeatureToConfigure.getFeature(null))) {
329                             childrenToInstall.add(optionalFeatureToConfigure);
330                             break;
331                         }
332                     } catch (CoreException e) {
333                         UpdateCore.warn("", e); //$NON-NLS-1$
334
}
335                 }
336             }
337         }
338
339         IIncludedFeatureReference[] result = new IIncludedFeatureReference[childrenToInstall.size()];
340         if (childrenToInstall.size() > 0) {
341             childrenToInstall.toArray(result);
342         }
343
344         return result;
345     }
346
347     /*
348      * @see IConfiguredSite#unconfigure(IFeature)
349      */

350     public boolean unconfigure(IFeature feature) throws CoreException {
351         // the first call sould disable without checking for enable parent
352
return unconfigure(feature, true, false);
353     }
354
355     private boolean unconfigure(IFeature feature, boolean includePatches, boolean verifyEnableParent) throws CoreException {
356         IFeatureReference featureReference = getSite().getFeatureReference(feature);
357
358         if (featureReference == null) {
359             UpdateCore.warn("Unable to retrieve Feature Reference for feature" + feature); //$NON-NLS-1$
360
return false;
361         }
362
363         ConfigurationPolicy configPolicy = getConfigurationPolicy();
364         if (configPolicy == null)
365             return false;
366
367         // verify no enable parent
368
if (verifyEnableParent && !validateNoConfiguredParents(feature)) {
369             UpdateCore.warn("The feature " + feature.getVersionedIdentifier() + " to disable is needed by another enable feature"); //$NON-NLS-1$ //$NON-NLS-2$
370
return false;
371         }
372
373         boolean sucessfullyUnconfigured = false;
374         try {
375             sucessfullyUnconfigured = configPolicy.unconfigure(featureReference, true, true);
376         } catch (CoreException e) {
377             URL JavaDoc url = featureReference.getURL();
378             String JavaDoc urlString = (url != null) ? url.toExternalForm() : "<no feature reference url>"; //$NON-NLS-1$
379
UpdateCore.warn("Unable to unconfigure" + urlString, e); //$NON-NLS-1$
380
throw e;
381         }
382         if (sucessfullyUnconfigured) {
383             // 2.0.2: unconfigure patches that reference this feature.
384
// A patch is a feature that contains an import
385
// statement with patch="true" and an id/version
386
// that matches an already installed and configured
387
// feature. When patched feature is unconfigured,
388
// all the patches that reference it must be
389
// unconfigured as well
390
// (in contrast, patched features can be
391
// configured without the patches).
392
if (includePatches)
393                 unconfigurePatches(feature);
394
395             // top down approach, same configuredSite
396
IIncludedFeatureReference[] childrenRef = feature.getIncludedFeatureReferences();
397             for (int i = 0; i < childrenRef.length; i++) {
398                 try {
399                     IFeature child = childrenRef[i].getFeature(null); // disable the exact feature
400
unconfigure(child, includePatches, true); // check for parent as we should be the only parent.
401
} catch (CoreException e) {
402                     // skip any bad children
403
UpdateCore.warn("Unable to unconfigure child feature: " + childrenRef[i] + " " + e); //$NON-NLS-1$ //$NON-NLS-2$
404
}
405             }
406
407             // notify listeners
408
Object JavaDoc[] siteListeners = listeners.getListeners();
409             for (int i = 0; i < siteListeners.length; i++) {
410                 IConfiguredSiteChangedListener listener = ((IConfiguredSiteChangedListener) siteListeners[i]);
411                 listener.featureUnconfigured(feature);
412             }
413
414             return true;
415         } else {
416             URL JavaDoc url = featureReference.getURL();
417             String JavaDoc urlString = (url != null) ? url.toExternalForm() : "<no feature reference url>"; //$NON-NLS-1$
418
UpdateCore.warn("Unable to unconfigure:" + urlString); //$NON-NLS-1$
419
return false;
420         }
421     }
422
423     /*
424      * Look for features that have an import reference
425      * that points to this feature and where patch=true.
426      * Unconfigure all the matching patches, but
427      * do not do the same lookup for them
428      * because patches cannot have patches themselves.
429      */

430
431     private void unconfigurePatches(IFeature feature) {
432         IFeatureReference[] frefs = getConfiguredFeatures();
433         for (int i = 0; i < frefs.length; i++) {
434             IFeatureReference fref = frefs[i];
435             try {
436                 IFeature candidate = fref.getFeature(null);
437                 if (candidate.equals(feature))
438                     continue;
439
440                 if (UpdateUtils.isPatch(feature, candidate))
441                     unconfigure(candidate, false, false);
442             } catch (CoreException e) {
443                 UpdateCore.warn("", e); //$NON-NLS-1$
444
}
445         }
446     }
447
448     /*
449      * @see IConfiguredSite#getConfiguredFeatures()
450      */

451     public IFeatureReference[] getConfiguredFeatures() {
452         if (isEnabled())
453             return getRawConfiguredFeatures();
454         else
455             return new ISiteFeatureReference[0];
456     }
457
458     /*
459      * @see IConfiguredSite#getConfiguredFeatures()
460      */

461     private IFeatureReference[] getRawConfiguredFeatures() {
462         ConfigurationPolicy configPolicy = getConfigurationPolicy();
463         if (configPolicy == null)
464             return new ISiteFeatureReference[0];
465
466         return configPolicy.getConfiguredFeatures();
467     }
468
469     /*
470      * adds configured and unconfigured feature references
471      */

472     public IFeatureReference[] getFeatureReferences() {
473
474         ConfigurationPolicy configPolicy = getConfigurationPolicy();
475         if (configPolicy == null)
476             return new ISiteFeatureReference[0];
477
478         IFeatureReference[] configuredFeatures = getConfiguredFeatures();
479         int confLen = configuredFeatures.length;
480         IFeatureReference[] unconfiguredFeatures = configPolicy.getUnconfiguredFeatures();
481         int unconfLen = unconfiguredFeatures.length;
482
483         IFeatureReference[] result = new IFeatureReference[confLen + unconfLen];
484         if (confLen > 0) {
485             System.arraycopy(configuredFeatures, 0, result, 0, confLen);
486         }
487         if (unconfLen > 0) {
488             System.arraycopy(unconfiguredFeatures, 0, result, confLen, unconfLen);
489         }
490
491         return result;
492     }
493
494     /*
495      * Configure and unconfigure appropriate feature to
496      * become 'like' currentConfiguration which is the configuration
497      * the user wants to revert to.
498      *
499      * All features from currentConfiguration should be configured
500      */

501     public void revertTo(IConfiguredSite oldConfiguration, IProgressMonitor monitor, IProblemHandler handler) throws CoreException, InterruptedException JavaDoc {
502
503         ConfiguredSite oldConfiguredSite = (ConfiguredSite) oldConfiguration;
504
505         // retrieve the feature that were configured
506
IFeatureReference[] configuredFeatures = oldConfiguredSite.validConfiguredFeatures(handler);
507
508         for (int i = 0; i < configuredFeatures.length; i++) {
509             getConfigurationPolicy().configure(configuredFeatures[i], true, true);
510         }
511
512         // calculate all the features we have to unconfigure from the current state to this state
513
// in the history.
514
List JavaDoc featureToUnconfigure = oldConfiguredSite.calculateUnconfiguredFeatures(configuredFeatures);
515
516         // for each unconfigured feature check if it still exists
517
// if so add as unconfigured
518
Iterator JavaDoc iter = featureToUnconfigure.iterator();
519         while (iter.hasNext()) {
520             IFeatureReference element = (IFeatureReference) iter.next();
521             try {
522                 // do not log activity
523
getConfigurationPolicy().unconfigure(element, true, true);
524             } catch (CoreException e) {
525                 // log no feature to unconfigure
526
String JavaDoc url = element.getURL().toString();
527                 ISite site = element.getSite();
528                 String JavaDoc siteString = (site != null) ? site.getURL().toExternalForm() : Messages.ConfiguredSite_NoSite;
529                 UpdateCore.warn(NLS.bind(Messages.ConfiguredSite_CannotFindFeatureToUnconfigure, (new String JavaDoc[] { url, siteString })), e);
530             }
531         }
532         //} // end USER_EXCLUDE
533
}
534
535     /*
536      * We have to keep our configured feature
537      * check if they are all valid
538      * Return the valid configured features
539      */

540     private IFeatureReference[] validConfiguredFeatures(IProblemHandler handler) throws InterruptedException JavaDoc {
541
542         IFeatureReference[] configuredFeatures = getConfiguredFeatures();
543         if (configuredFeatures != null) {
544             for (int i = 0; i < configuredFeatures.length; i++) {
545                 IFeature feature = null;
546
547                 // attempt to access the feature
548
try {
549                     feature = configuredFeatures[i].getFeature(null);
550                 } catch (CoreException e) {
551                     // notify we cannot find the feature
552
UpdateCore.warn(null, e);
553                     String JavaDoc featureString = configuredFeatures[i].getURL().toExternalForm();
554                     if (!handler.reportProblem(NLS.bind(Messages.ConfiguredSite_CannotFindFeatureToConfigure, (new String JavaDoc[] { featureString })))) {
555                         throw new InterruptedException JavaDoc();
556                     }
557                 }
558
559                 // verify all the plugins still exist
560
if (feature != null) {
561                     // get plugin identifier
562
List JavaDoc sitePluginIdentifiers = new ArrayList JavaDoc();
563                     ISite site = feature.getSite();
564                     IPluginEntry[] sitePluginEntries = null;
565
566                     if (site != null) {
567                         sitePluginEntries = site.getPluginEntries();
568                         for (int index = 0; index < sitePluginEntries.length; index++) {
569                             IPluginEntry entry = sitePluginEntries[index];
570                             sitePluginIdentifiers.add(entry.getVersionedIdentifier());
571                         }
572                     }
573
574                     if (sitePluginEntries.length > 0) {
575                         IPluginEntry[] featurePluginEntries = feature.getPluginEntries();
576                         for (int index = 0; index < featurePluginEntries.length; index++) {
577                             IPluginEntry currentFeaturePluginEntry = featurePluginEntries[index];
578                             if (!contains(currentFeaturePluginEntry.getVersionedIdentifier(), sitePluginIdentifiers)) {
579                                 // the plugin defined by the feature
580
// doesn't seem to exist on the site
581
String JavaDoc msg = "Error verifying existence of plugin:" + currentFeaturePluginEntry.getVersionedIdentifier().toString(); //$NON-NLS-1$
582
UpdateCore.log(msg, new Exception JavaDoc());
583
584                                 String JavaDoc siteString = (site != null) ? site.getURL().toExternalForm() : Messages.ConfiguredSite_NoSite;
585                                 String JavaDoc errorLabel = NLS.bind(Messages.ConfiguredSite_CannotFindPluginEntry, (new String JavaDoc[] { currentFeaturePluginEntry.getVersionedIdentifier().toString(), siteString }));
586                                 if (handler == null) {
587                                     throw new InterruptedException JavaDoc(errorLabel);
588                                 }
589                                 if (!handler.reportProblem(errorLabel)) {
590                                     throw new InterruptedException JavaDoc();
591                                 }
592                             } // end if not found in site
593
} // end for
594
}
595                 }
596             } // end for configured feature
597
}
598         return configuredFeatures;
599     }
600
601     /*
602      * We are in the process of calculating the delta between what was configured in the current
603      * configuration that is not configured now
604      *
605      * we have to figure out what feature have been unconfigured for the whole
606      * history between current and us...
607      *
608      * is it as simple as get all configured, and unconfigured,
609      * the do the delta with what should be configured
610      *
611      */

612     private List JavaDoc calculateUnconfiguredFeatures(IFeatureReference[] configuredFeatures) throws CoreException {
613
614         Set JavaDoc featureToUnconfigureSet = new HashSet JavaDoc();
615
616         // loop for all history
617
// try to see if the configured site existed
618
// if it does, get the unconfigured features
619
// and the configured one
620
IInstallConfiguration[] history = SiteManager.getLocalSite().getConfigurationHistory();
621
622         for (int i = 0; i < history.length; i++) {
623             IInstallConfiguration element = history[i];
624             IConfiguredSite[] configSites = element.getConfiguredSites();
625             for (int j = 0; j < configSites.length; j++) {
626                 ConfiguredSite configSite = (ConfiguredSite) configSites[j];
627                 if (configSite.getSite().equals(getSite())) {
628                     featureToUnconfigureSet.addAll(Arrays.asList(configSite.getConfigurationPolicy().getUnconfiguredFeatures()));
629                     featureToUnconfigureSet.addAll(Arrays.asList(configSite.getConfigurationPolicy().getConfiguredFeatures()));
630                 }
631             }
632         }
633
634         // remove the unconfigured feature we found that are now to be configured
635
// (they may have been unconfigured in the past, but the revert makes them configured)
636
List JavaDoc featureToUnconfigureList = remove(configuredFeatures, featureToUnconfigureSet);
637
638         return featureToUnconfigureList;
639     }
640
641     /*
642      * Utilities: Remove an array of feature references
643      * from a list
644      */

645     private List JavaDoc remove(IFeatureReference[] featureRefs, Set JavaDoc set) {
646         List JavaDoc result = new ArrayList JavaDoc();
647
648         if (set == null)
649             return result;
650
651         // if an element of the list is NOT found in the array,
652
// add it to the result list
653
Iterator JavaDoc iter = set.iterator();
654         while (iter.hasNext()) {
655             IFeatureReference element = (IFeatureReference) iter.next();
656             boolean found = false;
657             for (int i = 0; i < featureRefs.length; i++) {
658                 if (element.equals(featureRefs[i])) {
659                     found = true;
660                 }
661             }
662
663             if (!found)
664                 result.add(element);
665         }
666         return result;
667     }
668
669     /*
670      * I have issues when running list.contain(versionedIdentifier)
671      * The code runs the Object.equals instead of the VersionedIdentifier.equals
672      */

673     private boolean contains(VersionedIdentifier id, List JavaDoc list) {
674         boolean found = false;
675         if (list != null && !list.isEmpty()) {
676             Iterator JavaDoc iter = list.iterator();
677             while (iter.hasNext() && !found) {
678                 VersionedIdentifier element = (VersionedIdentifier) iter.next();
679                 if (element.equals(id)) {
680                     found = true;
681                 }
682             }
683         }
684         return found;
685     }
686
687     /*
688      *
689      */

690     public ConfigurationPolicy getConfigurationPolicy() {
691         return (ConfigurationPolicy) getConfigurationPolicyModel();
692     }
693
694     /*
695      *
696      */

697     public ISite getSite() {
698         return (ISite) getSiteModel();
699     }
700
701     /*
702      *
703      */

704     public IInstallConfiguration getInstallConfiguration() {
705         return (IInstallConfiguration) getInstallConfigurationModel();
706     }
707
708     /*
709      *
710      */

711     public IStatus getBrokenStatus(IFeature feature) {
712
713         IStatus featureStatus = createStatus(IStatus.OK, IFeature.STATUS_HAPPY, "", null); //$NON-NLS-1$
714

715         // check the Plugins of all the features
716
// every plugin of the feature must be on the site
717
IPluginEntry[] siteEntries = getSite().getPluginEntries();
718         IPluginEntry[] featuresEntries = feature.getPluginEntries();
719         IPluginEntry[] result = UpdateManagerUtils.diff(featuresEntries, siteEntries);
720         if (result != null && (result.length != 0)) {
721             String JavaDoc msg = Messages.SiteLocal_FeatureUnHappy;
722             MultiStatus multi = new MultiStatus(featureStatus.getPlugin(), IFeature.STATUS_UNHAPPY, msg, null);
723
724             for (int k = 0; k < result.length; k++) {
725                 VersionedIdentifier id = result[k].getVersionedIdentifier();
726                 Object JavaDoc[] values = new String JavaDoc[] { "", "" }; //$NON-NLS-1$ //$NON-NLS-2$
727
if (id != null) {
728                     values = new Object JavaDoc[] { id.getIdentifier(), id.getVersion()};
729                 }
730                 String JavaDoc msg1 = NLS.bind(Messages.ConfiguredSite_MissingPluginsBrokenFeature, values);
731                 UpdateCore.warn(msg1);
732                 IStatus status = createStatus(IStatus.ERROR, IFeature.STATUS_UNHAPPY, msg1, null);
733                 multi.add(status);
734             }
735             return multi;
736         }
737
738         // check os, arch, and ws
739

740         String JavaDoc msg = Messages.SiteLocal_FeatureHappy;
741         return createStatus(IStatus.OK, IFeature.STATUS_HAPPY, msg, null);
742     }
743
744     /*
745      *
746      */

747     public boolean isConfigured(IFeature feature) {
748         if (!isEnabled())
749             return false;
750
751         if (getConfigurationPolicy() == null)
752             return false;
753         IFeatureReference featureReference = getSite().getFeatureReference(feature);
754         if (featureReference == null) {
755             if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_WARNINGS)
756                 UpdateCore.warn("Unable to retrieve featureReference for feature:" + feature); //$NON-NLS-1$
757
return false;
758         }
759         return getConfigurationPolicy().isConfigured(featureReference);
760     }
761
762     /**
763      * @see Object#toString()
764      */

765     public String JavaDoc toString() {
766         if (getSite() == null)
767             return "No Site"; //$NON-NLS-1$
768
if (getSite().getURL() == null)
769             return "No URL"; //$NON-NLS-1$
770
return getSite().getURL().toExternalForm();
771     }
772
773     /**
774      * @see IConfiguredSite#verifyUpdatableStatus()
775      */

776     public IStatus verifyUpdatableStatus() {
777
778         if (verifyStatus != null)
779             return verifyStatus;
780
781         URL JavaDoc siteURL = getSite().getURL();
782         if (siteURL == null) {
783             verifyStatus = createStatus(IStatus.ERROR, Messages.ConfiguredSite_SiteURLNull, null);
784             return verifyStatus;
785         }
786
787         if (!"file".equalsIgnoreCase(siteURL.getProtocol())) { //$NON-NLS-1$
788
verifyStatus = createStatus(IStatus.ERROR, Messages.ConfiguredSite_NonLocalSite, null);
789             return verifyStatus;
790         }
791
792         String JavaDoc siteLocation = siteURL.getFile();
793         File JavaDoc file = new File JavaDoc(siteLocation);
794
795         // get the product name of the private marker
796
// if there is no private marker, check if the site is contained in another site
797
// if there is a marker and this is a different product, return false
798
// otherwise don't check if we are contained in another site
799
String JavaDoc productName = getProductName(file);
800         if (productName != null) {
801             if (!productName.equals(getProductIdentifier("id", getProductFile()))) { //$NON-NLS-1$
802
verifyStatus = createStatus(IStatus.ERROR, NLS.bind(Messages.ConfiguredSite_NotSameProductId, (new String JavaDoc[] { productName })), null);
803                 return verifyStatus;
804             }
805         } else {
806             File JavaDoc container = getSiteContaining(file);
807             // allow the install location to pass even though it looks like this
808
// site is contained in another site
809
if (container != null && !siteLocation.equals(Platform.getInstallLocation().getURL().getFile())) {
810                 verifyStatus = createStatus(IStatus.ERROR, NLS.bind(Messages.ConfiguredSite_ContainedInAnotherSite, (new String JavaDoc[] { container.getAbsolutePath() })), null);
811                 return verifyStatus;
812             }
813         }
814
815         if (!canWrite(file)) {
816             verifyStatus = createStatus(IStatus.ERROR, Messages.ConfiguredSite_ReadOnlySite, null);
817             return verifyStatus;
818         }
819
820         verifyStatus = createStatus(IStatus.OK, "", null); //$NON-NLS-1$
821
setUpdatable(true);
822         return verifyStatus;
823     }
824
825     /*
826      * Verify we can write on the file system
827      */

828     public static boolean canWrite(File JavaDoc file) {
829         if (file.canWrite() == false)
830             return false;
831
832         if (!file.isDirectory())
833             return false;
834
835         File JavaDoc fileTest = null;
836         try {
837             // we use the .dll suffix to properly test on Vista virtual directories
838
// on Vista you are not allowed to write executable files on virtual directories like "Program Files"
839
fileTest = File.createTempFile("writtableArea", ".dll", file); //$NON-NLS-1$ //$NON-NLS-2$
840
} catch (IOException JavaDoc e) {
841             //If an exception occured while trying to create the file, it means that it is not writtable
842
return false;
843         } finally {
844             if (fileTest != null)
845                 fileTest.delete();
846         }
847         return true;
848     }
849
850     /*
851      * Check if the directory contains a marker
852      * if not ask all directory children to check
853      * if one validates the condition, returns the marker
854      */

855     private static File JavaDoc getSiteContaining(File JavaDoc file) {
856
857         if (file == null)
858             return null;
859
860         UpdateCore.warn("IsContained: Checking for markers at:" + file); //$NON-NLS-1$
861
if (file.exists() && file.isDirectory()) {
862             File JavaDoc productFile = new File JavaDoc(file, PRODUCT_SITE_MARKER);
863             File JavaDoc extensionFile = new File JavaDoc(file, EXTENSION_SITE_MARKER);
864             if (productFile.exists() || extensionFile.exists())
865                 return file;
866 // // do not check if a marker exists in the current but start from the parent
867
// // the current is analyze by getProductname()
868
// if (file.getParentFile() != null) {
869
// File privateFile = new File(file.getParentFile(), PRIVATE_SITE_MARKER);
870
// if (privateFile.exists())
871
// return file.getParentFile();
872
// }
873
}
874         return getSiteContaining(file.getParentFile());
875     }
876
877     /*
878      * Returns the name of the product if the identifier of the private Site markup is not
879      * the same as the identifier of the product the workbench was started with.
880      * If the product is the same, return null.
881      */

882     private static String JavaDoc getProductName(File JavaDoc file) {
883
884         if (file == null)
885             return null;
886
887         File JavaDoc markerFile = new File JavaDoc(file, EXTENSION_SITE_MARKER );
888         if (!markerFile.exists()) {
889             return null;
890         }
891
892         File JavaDoc productFile = getProductFile();
893         String JavaDoc productId = null;
894         String JavaDoc privateId = null;
895         if (productFile != null) {
896             productId = getProductIdentifier("id", productFile); //$NON-NLS-1$
897
privateId = getProductIdentifier("id", markerFile); //$NON-NLS-1$
898
if (productId == null) {
899                 UpdateCore.warn("Product ID is null at:" + productFile); //$NON-NLS-1$
900
return null;
901             }
902             if (!productId.equalsIgnoreCase(privateId)) {
903                 UpdateCore.warn("Product id at" + productFile + " Different than:" + markerFile); //$NON-NLS-1$ //$NON-NLS-2$
904
String JavaDoc name = getProductIdentifier("name", markerFile); //$NON-NLS-1$
905
String JavaDoc version = getProductIdentifier("version", markerFile); //$NON-NLS-1$
906
String JavaDoc markerID = (name == null) ? version : name + ":" + version; //$NON-NLS-1$
907
if (markerID == null)
908                     markerID = ""; //$NON-NLS-1$
909
return markerID;
910             } else {
911                 return privateId;
912             }
913         } else {
914             UpdateCore.warn("Product Marker doesn't exist:" + productFile); //$NON-NLS-1$
915
}
916
917         return null;
918     }
919
920     /*
921      * Returns the identifier of the product from the property file
922      */

923     private static String JavaDoc getProductIdentifier(String JavaDoc identifier, File JavaDoc propertyFile) {
924         String JavaDoc result = null;
925         if (identifier == null)
926             return result;
927         InputStream JavaDoc in = null;
928         try {
929             in = new FileInputStream JavaDoc(propertyFile);
930             PropertyResourceBundle JavaDoc bundle = new PropertyResourceBundle JavaDoc(in);
931             result = bundle.getString(identifier);
932         } catch (IOException JavaDoc e) {
933             if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_INSTALL)
934                 UpdateCore.debug("Exception reading property file:" + propertyFile); //$NON-NLS-1$
935
} catch (MissingResourceException JavaDoc e) {
936             if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_INSTALL)
937                 UpdateCore.debug("Exception reading '" + identifier + "' from property file:" + propertyFile); //$NON-NLS-1$ //$NON-NLS-2$
938
} finally {
939             if (in == null)
940                 try {
941                     in.close();
942                 } catch (IOException JavaDoc e1) {
943                 }
944         }
945         return result;
946     }
947
948     /*
949      * Returns the identifier of the product from the property file
950      */

951     private static File JavaDoc getProductFile() {
952
953         String JavaDoc productInstallDirectory = ConfiguratorUtils.getInstallURL().getFile();
954         if (productInstallDirectory != null) {
955             File JavaDoc productFile = new File JavaDoc(productInstallDirectory, PRODUCT_SITE_MARKER);
956             if (productFile.exists()) {
957                 return productFile;
958             } else {
959                 UpdateCore.warn("Product marker doesn't exist:" + productFile); //$NON-NLS-1$
960
}
961         } else {
962             UpdateCore.warn("Cannot retrieve install URL from BootLoader"); //$NON-NLS-1$
963
}
964         return null;
965     }
966
967     /*
968      *
969      */

970     /*package*/
971     boolean createPrivateSiteMarker() {
972         URL JavaDoc siteURL = getSite().getURL();
973         if (siteURL == null) {
974             UpdateCore.warn("Unable to create marker. The Site url is null."); //$NON-NLS-1$
975
return false;
976         }
977
978         if (!"file".equalsIgnoreCase(siteURL.getProtocol())) { //$NON-NLS-1$
979
UpdateCore.warn("Unable to create private marker. The Site is not on the local file system."); //$NON-NLS-1$
980
return false;
981         }
982
983         String JavaDoc siteLocation = siteURL.getFile();
984         File JavaDoc productFile = getProductFile();
985         boolean success = false;
986         if (productFile != null) {
987             String JavaDoc productId = getProductIdentifier("id", productFile); //$NON-NLS-1$
988
String JavaDoc productName = getProductIdentifier("name", productFile); //$NON-NLS-1$
989
String JavaDoc productVer = getProductIdentifier("version", productFile); //$NON-NLS-1$
990
if (productId != null) {
991                 File JavaDoc file = new File JavaDoc(siteLocation, EXTENSION_SITE_MARKER);
992                 if (!file.exists()) {
993                     OutputStream JavaDoc out = null;
994                     OutputStreamWriter JavaDoc outWriter = null;
995                     try {
996                         out = new FileOutputStream JavaDoc(file);
997                         outWriter = new OutputStreamWriter JavaDoc(out, "UTF8"); //$NON-NLS-1$
998
outWriter.write("id=" + productId+"\n"); //$NON-NLS-1$ //$NON-NLS-2$
999
if (productName != null)
1000                            outWriter.write("name=" + productName+"\n"); //$NON-NLS-1$ //$NON-NLS-2$
1001
if (productVer != null)
1002                            outWriter.write("version=" + productVer+"\n"); //$NON-NLS-1$ //$NON-NLS-2$
1003
success = true;
1004                        justCreated = true;
1005                    } catch (Exception JavaDoc e) {
1006                        UpdateCore.warn("Unable to create private Marker at:" + file, e); //$NON-NLS-1$
1007
} finally {
1008                        try {
1009                            if (outWriter != null)
1010                                outWriter.close();
1011                        } catch (IOException JavaDoc e1) {
1012                        }
1013                        try {
1014                            if (out != null)
1015                                out.close();
1016                        } catch (IOException JavaDoc e2) {
1017                        }
1018                    }
1019                }
1020            }
1021        }
1022        return success;
1023    }
1024
1025
1026    /*
1027     * Returns true if the directory of the Site contains
1028     * .eclipseextension
1029     */

1030    public boolean isExtensionSite() {
1031        return containsMarker(EXTENSION_SITE_MARKER);
1032    }
1033
1034    /*
1035     * Returns true if the directory of the Site contains
1036     * .eclipseextension
1037     */

1038    public boolean isProductSite() {
1039        return containsMarker(PRODUCT_SITE_MARKER);
1040    }
1041
1042    /*
1043     * Returns true if the directory of the Site contains
1044     * .eclipseextension
1045     */

1046    public boolean isPrivateSite() {
1047        return isExtensionSite();
1048    }
1049
1050    /*
1051     *
1052     */

1053    private boolean containsMarker(String JavaDoc marker) {
1054        ISite site = getSite();
1055        if (site == null) {
1056            UpdateCore.warn("Contains Markers:The site is null"); //$NON-NLS-1$
1057
return false;
1058        }
1059
1060        URL JavaDoc url = site.getURL();
1061        if (url == null) {
1062            UpdateCore.warn("Contains Markers:Site URL is null"); //$NON-NLS-1$
1063
return false;
1064        }
1065        if (!"file".equalsIgnoreCase(url.getProtocol())) { //$NON-NLS-1$
1066
UpdateCore.warn("Contains Markers:Non file protocol"); //$NON-NLS-1$
1067
return false;
1068        }
1069        File JavaDoc file = new File JavaDoc(url.getFile());
1070        if (!file.exists()) {
1071            UpdateCore.warn("Contains Markers:The site doesn't exist:" + file); //$NON-NLS-1$
1072
return false;
1073        }
1074        File JavaDoc extension = new File JavaDoc(file, marker);
1075        if (!extension.exists()) {
1076            UpdateCore.warn("Contains Markers:The extensionfile does not exist:" + extension); //$NON-NLS-1$
1077
return false;
1078        }
1079        return true;
1080    }
1081
1082    /*
1083     * Returns true if the Site is already natively linked
1084     */

1085    public boolean isNativelyLinked() throws CoreException {
1086        String JavaDoc platformString = getPlatformURLString();
1087        if (platformString == null) {
1088            UpdateCore.warn("Unable to retrieve platformString"); //$NON-NLS-1$
1089
return false;
1090        }
1091
1092        URL JavaDoc siteURL = null;
1093        try {
1094            // check if the site exists and is updatable
1095
// update configSite
1096
URL JavaDoc urlToCheck = new URL JavaDoc(platformString);
1097            IPlatformConfiguration runtimeConfig = ConfiguratorUtils.getCurrentPlatformConfiguration();
1098            IPlatformConfiguration.ISiteEntry entry = runtimeConfig.findConfiguredSite(urlToCheck);
1099            if (entry != null) {
1100                return entry.isNativelyLinked();
1101            } else {
1102                UpdateCore.warn("Unable to retrieve site:" + platformString + " from platform."); //$NON-NLS-1$ //$NON-NLS-2$
1103
}
1104
1105            // check by comparing URLs
1106
IPlatformConfiguration.ISiteEntry[] sites = runtimeConfig.getConfiguredSites();
1107            for (int i = 0; i < sites.length; i++) {
1108                siteURL = sites[i].getURL();
1109                URL JavaDoc resolvedURL = FileLocator.resolve(siteURL);
1110                if (UpdateManagerUtils.sameURL(resolvedURL, urlToCheck))
1111                    return true;
1112            }
1113        } catch (MalformedURLException JavaDoc e) {
1114            String JavaDoc msg = NLS.bind(Messages.ConfiguredSite_UnableResolveURL, (new String JavaDoc[] { platformString }));
1115            throw Utilities.newCoreException(msg, e);
1116        } catch (IOException JavaDoc e) {
1117            String JavaDoc msg = NLS.bind(Messages.ConfiguredSite_UnableToAccessSite, (new Object JavaDoc[] { siteURL }));
1118            throw Utilities.newCoreException(msg, e);
1119        }
1120
1121        return false;
1122    }
1123
1124    /*
1125    * we have to check that no configured/enable parent include this feature
1126    */

1127    private boolean validateNoConfiguredParents(IFeature feature) throws CoreException {
1128        if (feature == null) {
1129            UpdateCore.warn("ConfigurationPolicy: validate Feature is null"); //$NON-NLS-1$
1130
return true;
1131        }
1132
1133        IFeatureReference[] parents = UpdateManagerUtils.getParentFeatures(feature, getConfiguredFeatures(), false);
1134        return (parents.length == 0);
1135    }
1136
1137}
1138
Popular Tags