KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > update > internal > operations > UpdateUtils


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  * James D Miles (IBM Corp.) - bug 191368, Policy URL doesn't support UTF-8 characters
11  *******************************************************************************/

12 package org.eclipse.update.internal.operations;
13
14 import java.lang.reflect.*;
15 import java.net.*;
16 import java.util.ArrayList JavaDoc;
17 import java.util.Vector JavaDoc;
18
19 import org.eclipse.core.runtime.*;
20 import org.eclipse.update.configuration.*;
21 import org.eclipse.update.core.*;
22 import org.eclipse.update.core.model.*;
23 import org.eclipse.update.internal.core.*;
24 import org.eclipse.update.internal.core.URLEncoder;
25 import org.eclipse.update.internal.search.*;
26 import org.eclipse.update.operations.*;
27 import org.eclipse.update.search.*;
28
29
30 /**
31  * Helper class for performing update related tasks, queries, etc.
32  * All the methods are static and this class should be a singleton.
33  */

34 public class UpdateUtils {
35     public static final String JavaDoc P_UPDATE_POLICY_URL = "updatePolicyURL"; //$NON-NLS-1$
36

37     /**
38      * Private constructor
39      */

40     private UpdateUtils() {
41     }
42     
43
44     public static String JavaDoc getPluginId() {
45         return UpdateCore.getPlugin().getBundle().getSymbolicName();
46     }
47
48
49     public static void logException(Throwable JavaDoc e) {
50         
51         if (e instanceof InvocationTargetException) {
52             e = ((InvocationTargetException) e).getTargetException();
53         }
54
55         IStatus status = null;
56         if (e instanceof CoreException) {
57             status = ((CoreException) e).getStatus();
58         } else {
59             String JavaDoc message = e.getMessage();
60             if (message == null)
61                 message = e.toString();
62             status = new Status(IStatus.ERROR, getPluginId(), IStatus.OK, message, e);
63         }
64         log(status);
65     }
66
67     public static void log(IStatus status) {
68         if (status.getSeverity() != IStatus.INFO) {
69             UpdateCore.getPlugin().getLog().log(status);
70         }
71     }
72
73     public static IFeature[] searchSite(String JavaDoc featureId, IConfiguredSite site, boolean onlyConfigured) throws CoreException {
74         IFeatureReference[] references = null;
75
76         if (onlyConfigured)
77             references = site.getConfiguredFeatures();
78         else
79             references = site.getSite().getFeatureReferences();
80         Vector JavaDoc result = new Vector JavaDoc();
81
82         for (int i = 0; i < references.length; i++) {
83             IFeature feature = references[i].getFeature(null);
84             String JavaDoc id = feature.getVersionedIdentifier().getIdentifier();
85             if (featureId.equals(id)) {
86                 result.add(feature);
87             }
88         }
89         return (IFeature[]) result.toArray(new IFeature[result.size()]);
90     }
91
92     public static IFeature[] getInstalledFeatures(IFeature feature) {
93         return getInstalledFeatures(feature, true);
94     }
95
96     /**
97      *
98      * @param feature
99      * @param onlyConfigured
100      * @return IFeature[] with features matching feature ID
101      */

102     public static IFeature[] getInstalledFeatures(IFeature feature, boolean onlyConfigured) {
103         return getInstalledFeatures(feature.getVersionedIdentifier(), onlyConfigured);
104     }
105     /**
106      * @param vid
107      * @param onlyConfigured
108      * @return IFeature[] with features matching feature ID
109      */

110     public static IFeature[] getInstalledFeatures(VersionedIdentifier vid, boolean onlyConfigured) {
111         Vector JavaDoc features = new Vector JavaDoc();
112         try {
113             ILocalSite localSite = SiteManager.getLocalSite();
114             IInstallConfiguration config = localSite.getCurrentConfiguration();
115             IConfiguredSite[] isites = config.getConfiguredSites();
116             String JavaDoc id = vid.getIdentifier();
117
118             for (int i = 0; i < isites.length; i++) {
119                 IConfiguredSite isite = isites[i];
120                 IFeature[] result = UpdateUtils.searchSite(id, isite, onlyConfigured);
121                 for (int j = 0; j < result.length; j++) {
122                     IFeature installedFeature = result[j];
123                     features.add(installedFeature);
124                 }
125             }
126         } catch (CoreException e) {
127             UpdateUtils.logException(e);
128         }
129         return (IFeature[]) features.toArray(new IFeature[features.size()]);
130     }
131     
132     /**
133      * @param patch
134      * @return IFeature or null
135      */

136     public static IFeature getPatchedFeature(IFeature patch) {
137         IImport[] imports = patch.getImports();
138         for (int i = 0; i < imports.length; i++) {
139             IImport iimport = imports[i];
140             if (iimport.isPatch()) {
141                 VersionedIdentifier patchedVid = iimport
142                         .getVersionedIdentifier();
143                 // features with matching id
144
IFeature[] features = getInstalledFeatures(patchedVid, false);
145                 for (int f = 0; f < features.length; f++) {
146                     // check if version match
147
if (patchedVid.equals(features[f].getVersionedIdentifier())) {
148                         return features[f];
149                     }
150                 }
151             }
152         }
153         return null;
154     }
155
156     public static boolean isPatch(IFeature candidate) {
157         IImport[] imports = candidate.getImports();
158
159         for (int i = 0; i < imports.length; i++) {
160             IImport iimport = imports[i];
161             if (iimport.isPatch()) return true;
162         }
163         return false;
164     }
165
166     public static boolean isPatch(IFeature target, IFeature candidate) {
167         VersionedIdentifier vid = target.getVersionedIdentifier();
168         IImport[] imports = candidate.getImports();
169
170         for (int i = 0; i < imports.length; i++) {
171             IImport iimport = imports[i];
172             if (iimport.isPatch()) {
173                 VersionedIdentifier ivid = iimport.getVersionedIdentifier();
174                 if (vid.equals(ivid)) {
175                     // Bingo.
176
return true;
177                 }
178             }
179         }
180         return false;
181     }
182
183     public static IInstallConfiguration getBackupConfigurationFor(IFeature feature) {
184         VersionedIdentifier vid = feature.getVersionedIdentifier();
185         String JavaDoc key = "@" + vid.getIdentifier() + "_" + vid.getVersion(); //$NON-NLS-1$ //$NON-NLS-2$
186
try {
187             ILocalSite lsite = SiteManager.getLocalSite();
188             IInstallConfiguration[] configs = lsite.getPreservedConfigurations();
189             for (int i = 0; i < configs.length; i++) {
190                 IInstallConfiguration config = configs[i];
191                 if (config.getLabel().startsWith(key))
192                     return config;
193             }
194         } catch (CoreException e) {
195         }
196         return null;
197     }
198     
199     
200     public static boolean hasLicense(IFeature feature) {
201         IURLEntry info = feature.getLicense();
202         if (info == null)
203             return false;
204         String JavaDoc licenseTxt = info.getAnnotation();
205         if (licenseTxt == null)
206             return false;
207         return licenseTxt.trim().length() > 0;
208     }
209     public static boolean hasOptionalFeatures(IFeatureReference fref) {
210         try {
211             return hasOptionalFeatures(fref.getFeature(null));
212         } catch (CoreException e) {
213             return false;
214         }
215     }
216     public static boolean hasOptionalFeatures(IFeature feature) {
217         try {
218             IIncludedFeatureReference[] irefs = feature.getIncludedFeatureReferences();
219             for (int i = 0; i < irefs.length; i++) {
220                 IIncludedFeatureReference iref = irefs[i];
221                 if (iref.isOptional())
222                     return true;
223                 // see if it has optional children
224
IFeature child = getIncludedFeature( feature, iref);
225                 if (hasOptionalFeatures(child))
226                     return true;
227             }
228         } catch (CoreException e) {
229         }
230         return false;
231     }
232
233     public static IFeature getLocalFeature(
234         IConfiguredSite csite,
235         IFeature feature)
236         throws CoreException {
237         IFeatureReference[] refs = csite.getConfiguredFeatures();
238         for (int i = 0; i < refs.length; i++) {
239             IFeatureReference ref = refs[i];
240             VersionedIdentifier refVid = ref.getVersionedIdentifier();
241             if (feature.getVersionedIdentifier().equals(refVid))
242                 return ref.getFeature(null);
243         }
244         return null;
245     }
246     
247     public static IConfiguredSite getConfigSite(
248         IFeature feature,
249         IInstallConfiguration config)
250         throws CoreException {
251         IConfiguredSite[] configSites = config.getConfiguredSites();
252         for (int i = 0; i < configSites.length; i++) {
253             IConfiguredSite site = configSites[i];
254             if (site.getSite().equals(feature.getSite())) {
255                 return site;
256             }
257         }
258         return null;
259     }
260     
261     public static IConfiguredSite getDefaultTargetSite(
262         IInstallConfiguration config,
263         IInstallFeatureOperation pendingChange) {
264         return getDefaultTargetSite(config, pendingChange, true);
265     }
266
267     public static IConfiguredSite getDefaultTargetSite(
268         IInstallConfiguration config,
269         IInstallFeatureOperation pendingChange,
270         boolean checkAffinityFeature) {
271         IFeature oldFeature = pendingChange.getOldFeature();
272         IFeature newFeature = pendingChange.getFeature();
273         if (oldFeature != null) {
274             // We should install into the same site as
275
// the old feature
276
try {
277                 return getConfigSite(oldFeature, config);
278             } catch (CoreException e) {
279                 logException(e);
280                 return null;
281             }
282         }
283
284         // This is a new install. Check if there is
285
// a disabled feature with the same ID
286
String JavaDoc newFeatureID =
287             newFeature.getVersionedIdentifier().getIdentifier();
288         IConfiguredSite sameSite = getSiteWithFeature(config, newFeatureID);
289         if (sameSite != null) {
290             return sameSite;
291         }
292
293         if (checkAffinityFeature) {
294             return getAffinitySite(config, newFeature);
295         }
296         return null;
297     }
298     
299     public static IConfiguredSite getAffinitySite(
300         IInstallConfiguration config,
301         IFeature newFeature) {
302         // check if the affinity feature is installed
303
String JavaDoc affinityID = newFeature.getAffinityFeature();
304         if (affinityID != null) {
305             IConfiguredSite affinitySite =
306                 getSiteWithFeature(config, affinityID);
307             if (affinitySite != null)
308                 return affinitySite;
309         } else {
310             // if this is a patch, collocate with the feature
311
IFeature patchedFeature = getPatchedFeature(newFeature);
312             if (patchedFeature != null)
313                 return getSiteWithFeature(config, patchedFeature.getVersionedIdentifier().getIdentifier());
314         }
315         return null;
316     }
317
318     public static IConfiguredSite getSiteWithFeature(
319         IInstallConfiguration config,
320         String JavaDoc featureID) {
321         if (featureID == null)
322             return null;
323         IConfiguredSite[] sites = config.getConfiguredSites();
324         for (int i = 0; i < sites.length; i++) {
325             IConfiguredSite site = sites[i];
326             IFeatureReference[] refs = site.getFeatureReferences();
327             for (int j = 0; j < refs.length; j++) {
328                 IFeatureReference ref = refs[j];
329                 try {
330                     IFeature feature = ref.getFeature(null);
331                     if (featureID
332                         .equals(
333                             feature
334                                 .getVersionedIdentifier()
335                                 .getIdentifier())) {
336                         // found it
337
return site;
338                     }
339                 } catch (CoreException e) {
340                     logException(e);
341                 }
342             }
343         }
344         return null;
345     }
346     
347     public static void collectOldFeatures(
348         IFeature feature,
349         IConfiguredSite targetSite,
350         ArrayList JavaDoc result)
351         throws CoreException {
352         IIncludedFeatureReference[] included =
353             feature.getIncludedFeatureReferences();
354         for (int i = 0; i < included.length; i++) {
355             IIncludedFeatureReference iref = included[i];
356
357             IFeature ifeature;
358
359             try {
360                 ifeature = iref.getFeature(null);
361             } catch (CoreException e) {
362                 if (iref.isOptional())
363                     continue;
364                 throw e;
365             }
366             // find other features and unconfigure
367
String JavaDoc id = iref.getVersionedIdentifier().getIdentifier();
368             IFeature[] sameIds = UpdateUtils.searchSite(id, targetSite, true);
369             for (int j = 0; j < sameIds.length; j++) {
370                 IFeature sameId = sameIds[j];
371                 // Ignore self.
372
if (sameId.equals(ifeature))
373                     continue;
374                 result.add(sameId);
375             }
376             collectOldFeatures(ifeature, targetSite, result);
377         }
378     }
379
380 //
381
// public static IInstallConfiguration createInstallConfiguration() throws CoreException{
382
// try {
383
// ILocalSite localSite = SiteManager.getLocalSite();
384
// IInstallConfiguration config =
385
// localSite.cloneCurrentConfiguration();
386
// config.setLabel(Utilities.format(config.getCreationDate()));
387
// return config;
388
// } catch (CoreException e) {
389
// // Let callers handle logging
390
// //logException(e);
391
// throw e;
392
// }
393
// }
394

395     public static UpdateSearchRequest createNewUpdatesRequest(IFeature [] features) {
396         return createNewUpdatesRequest(features, true);
397     }
398     
399     public static UpdateSearchRequest createNewUpdatesRequest(IFeature [] features, boolean automatic) {
400         UpdateSearchScope scope = new UpdateSearchScope();
401         scope.setUpdateMapURL(UpdateUtils.getUpdateMapURL());
402         UpdatesSearchCategory category = new UpdatesSearchCategory(automatic);
403         if (features!=null)
404             category.setFeatures(features);
405         UpdateSearchRequest searchRequest = new UpdateSearchRequest(category, scope);
406         searchRequest.addFilter(new EnvironmentFilter());
407         searchRequest.addFilter(new BackLevelFilter());
408         return searchRequest;
409     }
410
411     public static boolean isNestedChild(IInstallConfiguration config, IFeature feature) {
412         IConfiguredSite[] csites = config.getConfiguredSites();
413         try {
414             for (int i = 0; csites != null && i < csites.length; i++) {
415                 IFeatureReference[] refs = csites[i].getConfiguredFeatures();
416                 for (int j = 0; refs != null && j < refs.length; j++) {
417                     IFeature parent = refs[j].getFeature(null);
418                     IFeatureReference[] children =
419                         parent.getIncludedFeatureReferences();
420                     for (int k = 0;
421                         children != null && k < children.length;
422                         k++) {
423                         IFeature child = children[k].getFeature(null);
424                         if (feature.equals(child))
425                             return true;
426                     }
427                 }
428             }
429         } catch (CoreException e) {
430             // will return false
431
}
432         return false;
433     }
434     
435     
436     public static boolean hasObsoletePatches(IFeature feature) {
437         // Check all the included features that
438
// are unconfigured, and see if their patch
439
// references are better than the original.
440
try {
441             IFeatureReference[] irefs = feature.getIncludedFeatureReferences();
442             for (int i = 0; i < irefs.length; i++) {
443                 IFeatureReference iref = irefs[i];
444                 IFeature ifeature = iref.getFeature(null);
445                 IConfiguredSite csite = ifeature.getSite().getCurrentConfiguredSite();
446                 if (!csite.isConfigured(ifeature)) {
447                     if (!isPatchHappy(ifeature))
448                         return false;
449                 }
450             }
451         } catch (CoreException e) {
452             return false;
453         }
454         // All checks went well
455
return true;
456     }
457     
458     public static boolean isPatchHappy(IFeature feature) throws CoreException {
459         // If this is a patch and it includes
460
// another patch and the included patch
461
// is disabled but the feature it was declared
462
// to patch is now newer (and is presumed to
463
// contain the now disabled patch), and
464
// the newer patched feature is enabled,
465
// a 'leap of faith' assumption can be
466
// made:
467

468         // Although the included patch is disabled,
469
// the feature it was designed to patch
470
// is now newer and most likely contains
471
// the equivalent fix and more. Consequently,
472
// we can claim that the status and the error
473
// icon overlay are misleading because
474
// all the right plug-ins are configured.
475
IImport[] imports = feature.getImports();
476         IImport patchReference = null;
477         for (int i = 0; i < imports.length; i++) {
478             IImport iimport = imports[i];
479             if (iimport.isPatch()) {
480                 patchReference = iimport;
481                 break;
482             }
483         }
484         if (patchReference == null)
485             return false;
486         VersionedIdentifier refVid = patchReference.getVersionedIdentifier();
487
488         // Find the patched feature and
489
IConfiguredSite csite = feature.getSite().getCurrentConfiguredSite();
490         if (csite == null)
491             return false;
492
493         IFeatureReference[] crefs = csite.getConfiguredFeatures();
494         for (int i = 0; i < crefs.length; i++) {
495             IFeatureReference cref = crefs[i];
496             VersionedIdentifier cvid = cref.getVersionedIdentifier();
497             if (cvid.getIdentifier().equals(refVid.getIdentifier())) {
498                 // This is the one.
499
if (cvid.getVersion().isGreaterThan(refVid.getVersion())) {
500                     // Bingo: we found the referenced feature
501
// and its version is greater -
502
// we can assume that it contains better code
503
// than the patch that referenced the
504
// older version.
505
return true;
506                 }
507             }
508         }
509         return false;
510     }
511
512     public static URL getUpdateMapURL() {
513         Preferences pref = UpdateCore.getPlugin().getPluginPreferences();
514         String JavaDoc mapFile = pref.getString(UpdateUtils.P_UPDATE_POLICY_URL);
515         if (mapFile!=null && mapFile.length()>0) {
516             try {
517                 URL url = new URL(mapFile);
518                 URL resolvedURL = URLEncoder.encode(url);
519                 return resolvedURL;
520             }
521             catch (MalformedURLException e) {
522                 UpdateUtils.logException(e);
523             }
524         }
525         return null;
526     }
527     
528     /*
529      * Load the update map using the map URL found in the scope.
530      */

531     public static IStatus loadUpdatePolicy(UpdatePolicy map, URL url, IProgressMonitor monitor) throws CoreException {
532         monitor.subTask(Messages.UpdateSearchRequest_loadingPolicy);
533         try {
534             map.load(url, monitor);
535             monitor.worked(1);
536         }
537         catch (CoreException e) {
538             IStatus status = e.getStatus();
539             if (status == null
540                 || status.getCode() != ISite.SITE_ACCESS_EXCEPTION)
541                 throw e;
542             monitor.worked(1);
543             return status;
544         }
545         return null;
546     }
547
548     public static void downloadFeatureContent(
549         IConfiguredSite targetSite,
550         IFeature feature,
551         IFeatureReference[] optionalChildren, // null when feature has no optional features
552
IProgressMonitor progress)
553         throws InstallAbortedException, CoreException {
554         
555         //DEBUG
556
if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_INSTALL) {
557             UpdateCore.debug(
558                 "Downloading...:" + feature.getURL().toExternalForm()); //$NON-NLS-1$
559
}
560
561         // Get source feature provider and verifier.
562
// Initialize target variables.
563
final IFeatureContentProvider provider =
564             feature.getFeatureContentProvider();
565         IPluginEntry[] targetSitePluginEntries = null;
566
567         // determine list of plugins to install
568
// find the intersection between the plugin entries already contained
569
// on the target site, and plugin entries packaged in source feature
570
IPluginEntry[] sourceFeaturePluginEntries = feature.getPluginEntries();
571
572         boolean featureAlreadyInstalled = false;
573         if (targetSite == null)
574             targetSite = getSiteWithFeature(SiteManager.getLocalSite()
575                     .getCurrentConfiguration(), ((Feature) feature)
576                     .getFeatureIdentifier());
577         if (targetSite == null) {
578             if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_INSTALL) {
579                 UpdateCore.debug("The site to install in is null"); //$NON-NLS-1$
580
}
581
582             targetSitePluginEntries = new IPluginEntry[0];
583         } else {
584             targetSitePluginEntries = targetSite.getSite().getPluginEntries();
585             featureAlreadyInstalled = UpdateUtils.getLocalFeature(targetSite,feature) != null;
586         }
587         IPluginEntry[] pluginsToInstall =
588             UpdateManagerUtils.diff(
589                 sourceFeaturePluginEntries,
590                 targetSitePluginEntries);
591         INonPluginEntry[] nonPluginsToInstall = feature.getNonPluginEntries();
592         
593         IFeatureReference[] children = feature.getIncludedFeatureReferences();
594         if (optionalChildren != null) {
595             children =
596                 UpdateManagerUtils.optionalChildrenToInstall(
597                     children,
598                     optionalChildren);
599         }
600
601         // make sure we have an InstallMonitor
602
InstallMonitor monitor;
603         if (progress == null)
604             monitor = new InstallMonitor(new NullProgressMonitor());
605         else if (progress instanceof InstallMonitor)
606             monitor = (InstallMonitor) progress;
607         else
608             monitor = new InstallMonitor(progress);
609
610         try {
611             // determine number of monitor tasks
612
// 1 task1 for the feature jar (download)
613
// + n tasks for plugin entries (download for each)
614
// + m tasks per non-plugin data entry (download for each)
615
// TODO custom install handler + 1 task for custom non-plugin entry handling (1 for all combined)
616
// + 3*x tasks for children features (3 subtasks per install)
617
int taskCount =
618                     1
619                     + pluginsToInstall.length
620                     + nonPluginsToInstall.length
621 // + 1
622
+ 3 * children.length;
623             monitor.beginTask("", taskCount); //$NON-NLS-1$
624

625             // Download feature archive(s)
626
provider.getFeatureEntryArchiveReferences(monitor);
627             monitorWork(monitor,1);
628             
629             // Download plugin archives
630
for (int i = 0; i < pluginsToInstall.length; i++) {
631                 provider.getPluginEntryArchiveReferences(pluginsToInstall[i], monitor);
632                 monitorWork(monitor,1);
633             }
634             
635             
636
637             // Download non-plugin archives. Verification handled by optional install handler
638
// Note: do not download non-plugin archives for installed features
639
if (nonPluginsToInstall.length > 0) {
640                 // Setup optional install handler
641
InstallHandlerProxy handler = null;
642                 if (feature.getInstallHandlerEntry()!=null)
643                     handler = new InstallHandlerProxy(
644                         IInstallHandler.HANDLER_ACTION_INSTALL,
645                         feature,
646                         feature.getInstallHandlerEntry(),
647                         monitor);
648                 
649                 if (!featureAlreadyInstalled)
650                     for (int i = 0; i < nonPluginsToInstall.length; i++) {
651                         if (handler==null || handler.acceptNonPluginData(nonPluginsToInstall[i]))
652                             provider.getNonPluginEntryArchiveReferences(
653                                 nonPluginsToInstall[i], monitor);
654                         monitorWork(monitor, 1);
655                     }
656                 else
657                     monitorWork(monitor, nonPluginsToInstall.length);
658             }
659            
660             // Download child features
661
for (int i = 0; i < children.length; i++) {
662                 IFeature childFeature = null;
663                 try {
664                     childFeature = children[i].getFeature(null);
665                 } catch (CoreException e) {
666                     UpdateCore.warn(null, e);
667                 }
668                 if (childFeature != null) {
669                     SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 3);
670                     downloadFeatureContent(targetSite, childFeature, optionalChildren, subMonitor);
671                 }
672             }
673         } finally {
674             if (monitor != null)
675                 monitor.done();
676         }
677     }
678     
679     private static void monitorWork(IProgressMonitor monitor, int tick)
680     throws CoreException {
681     if (monitor != null) {
682         monitor.worked(tick);
683         if (monitor.isCanceled()) {
684             String JavaDoc msg = "download cancelled";//Policy.bind("Feature.InstallationCancelled"); //$NON-NLS-1$
685
throw new InstallAbortedException(msg, null);
686         }
687     }
688 }
689     public static IFeature getIncludedFeature(IFeature feature, IFeatureReference iref) throws CoreException {
690         IFeature ifeature = null;
691         if (feature.getSite() instanceof ExtendedSite) {
692             ifeature = ((ExtendedSite)feature.getSite()).getLiteFeature(iref.getVersionedIdentifier());
693         }
694         if (ifeature == null) {
695             ifeature = iref.getFeature(new NullProgressMonitor());
696         }
697         return ifeature;
698     }
699 }
700
Popular Tags