KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > core > TargetPlatform


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.pde.internal.core;
12
13 import java.io.File JavaDoc;
14 import java.io.FileInputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.net.MalformedURLException JavaDoc;
17 import java.net.URL JavaDoc;
18 import java.util.ArrayList JavaDoc;
19 import java.util.Dictionary JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.Hashtable JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Locale JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Properties JavaDoc;
26 import java.util.Set JavaDoc;
27 import java.util.StringTokenizer JavaDoc;
28 import java.util.TreeSet JavaDoc;
29
30 import org.eclipse.core.runtime.CoreException;
31 import org.eclipse.core.runtime.IPath;
32 import org.eclipse.core.runtime.IStatus;
33 import org.eclipse.core.runtime.Path;
34 import org.eclipse.core.runtime.Platform;
35 import org.eclipse.core.runtime.Status;
36 import org.eclipse.osgi.service.resolver.BundleDescription;
37 import org.eclipse.osgi.service.resolver.State;
38 import org.eclipse.osgi.util.ManifestElement;
39 import org.eclipse.pde.core.plugin.IPluginExtension;
40 import org.eclipse.pde.core.plugin.IPluginLibrary;
41 import org.eclipse.pde.core.plugin.IPluginModelBase;
42 import org.eclipse.pde.core.plugin.IPluginObject;
43 import org.eclipse.pde.internal.core.ifeature.IFeature;
44 import org.eclipse.pde.internal.core.ifeature.IFeatureModel;
45 import org.eclipse.pde.internal.core.util.CoreUtility;
46 import org.eclipse.update.configurator.ConfiguratorUtils;
47 import org.eclipse.update.configurator.IPlatformConfiguration;
48 import org.osgi.framework.BundleContext;
49 import org.osgi.framework.BundleException;
50 import org.osgi.framework.Constants;
51 import org.osgi.framework.InvalidSyntaxException;
52
53 public class TargetPlatform implements IEnvironmentVariables {
54     
55     private static String JavaDoc REFERENCE_PREFIX = "reference:"; //$NON-NLS-1$
56
private static String JavaDoc FILE_URL_PREFIX = "file:"; //$NON-NLS-1$
57

58     static class LocalSite {
59         private ArrayList JavaDoc plugins;
60         private IPath path;
61
62         public LocalSite(IPath path) {
63             if (path.getDevice() != null)
64                 this.path = path.setDevice(path.getDevice().toUpperCase(Locale.ENGLISH));
65             else
66                 this.path = path;
67             plugins = new ArrayList JavaDoc();
68         }
69
70         public IPath getPath() {
71             return path;
72         }
73
74         public URL JavaDoc getURL() throws MalformedURLException JavaDoc {
75             return new URL JavaDoc("file:" + path.removeTrailingSeparator()); //$NON-NLS-1$
76
}
77
78         public void add(IPluginModelBase model) {
79             plugins.add(model);
80         }
81
82         public String JavaDoc[] getRelativePluginList() {
83             String JavaDoc[] list = new String JavaDoc[plugins.size()];
84             for (int i = 0; i < plugins.size(); i++) {
85                 IPluginModelBase model = (IPluginModelBase) plugins.get(i);
86                 IPath location = new Path(model.getInstallLocation());
87                 // defect 37319
88
if (location.segmentCount() > 2)
89                     location = location.removeFirstSegments(location.segmentCount() - 2);
90                 //31489 - entry must be relative
91
list[i] = location.setDevice(null).makeRelative().toString();
92             }
93             return list;
94         }
95     }
96
97     private static Map JavaDoc fCachedLocations;
98     
99     public static Properties JavaDoc getConfigIniProperties() {
100         File JavaDoc iniFile = new File JavaDoc(ExternalModelManager.getEclipseHome().toOSString(), "configuration/config.ini"); //$NON-NLS-1$
101
if (!iniFile.exists())
102             return null;
103         Properties JavaDoc pini = new Properties JavaDoc();
104         try {
105             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(iniFile);
106             pini.load(fis);
107             fis.close();
108             return pini;
109         } catch (IOException JavaDoc e) {
110         }
111         return null;
112     }
113     
114     public static String JavaDoc getBundleList() {
115         Properties JavaDoc properties = getConfigIniProperties();
116         String JavaDoc osgiBundles = properties == null ? null : properties.getProperty("osgi.bundles"); //$NON-NLS-1$
117
if (osgiBundles == null) {
118             StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
119             if (getTargetVersion() > 3.1) {
120                 buffer.append("org.eclipse.equinox.common@2:start,"); //$NON-NLS-1$
121
buffer.append("org.eclipse.update.configurator@3:start,"); //$NON-NLS-1$
122
buffer.append("org.eclipse.core.runtime@start"); //$NON-NLS-1$
123
} else {
124                 buffer.append("org.eclipse.core.runtime@2:start,"); //$NON-NLS-1$
125
buffer.append("org.eclipse.update.configurator@3:start"); //$NON-NLS-1$
126
}
127             osgiBundles = buffer.toString();
128         } else {
129             osgiBundles = stripPathInformation(osgiBundles);
130         }
131         return osgiBundles;
132     }
133     
134     public static String JavaDoc stripPathInformation(String JavaDoc osgiBundles) {
135         osgiBundles = osgiBundles.replaceAll("\\s", ""); //$NON-NLS-1$ //$NON-NLS-2$
136
StringBuffer JavaDoc result = new StringBuffer JavaDoc();
137         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(osgiBundles, ","); //$NON-NLS-1$
138
while (tokenizer.hasMoreElements()) {
139             String JavaDoc token = tokenizer.nextToken();
140             int index = token.indexOf('@');
141             
142             // read up until the first @, if there
143
String JavaDoc bundle = index > 0 ? token.substring(0, index) : token;
144             
145             // strip [reference:][file:/] prefixes if any
146
if (bundle.startsWith(REFERENCE_PREFIX) && bundle.length() > REFERENCE_PREFIX.length())
147                 bundle = bundle.substring(REFERENCE_PREFIX.length());
148             if (bundle.startsWith(FILE_URL_PREFIX) && bundle.length() > FILE_URL_PREFIX.length())
149                 bundle = bundle.substring(FILE_URL_PREFIX.length());
150             
151             // if the path is relative, the last segment is the bundle symbolic name
152
// Otherwise, we need to retrieve the bundle symbolic name ourselves
153
IPath path = new Path(bundle);
154             String JavaDoc id = path.isAbsolute() ? getSymbolicName(bundle) : path.lastSegment();
155             if (result.length() > 0)
156                 result.append(","); //$NON-NLS-1$
157
result.append(id != null ? id : bundle);
158             if (index > -1)
159                 result.append(token.substring(index));
160         }
161         return result.toString();
162     }
163     
164     private static synchronized String JavaDoc getSymbolicName(String JavaDoc path) {
165         if (fCachedLocations == null)
166             fCachedLocations = new HashMap JavaDoc();
167         
168         File JavaDoc file = new File JavaDoc(path);
169         if (file.exists() && !fCachedLocations.containsKey(path)) {
170             try {
171                 Dictionary JavaDoc dictionary = MinimalState.loadManifest(file);
172                 String JavaDoc value = (String JavaDoc)dictionary.get(Constants.BUNDLE_SYMBOLICNAME);
173                 if (value != null) {
174                     ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, value);
175                     String JavaDoc id = elements.length > 0 ? elements[0].getValue() : null;
176                     if (id != null)
177                         fCachedLocations.put(path, elements[0].getValue());
178                 }
179             } catch (IOException JavaDoc e) {
180             } catch (BundleException e) {
181             }
182         }
183         return (String JavaDoc)fCachedLocations.get(path);
184     }
185
186     
187     public static void createPlatformConfigurationArea(
188         Map JavaDoc pluginMap,
189         File JavaDoc configDir,
190         String JavaDoc brandingPluginID)
191         throws CoreException {
192         try {
193             if (pluginMap.containsKey("org.eclipse.update.configurator")) //$NON-NLS-1$
194
savePlatformConfiguration(ConfiguratorUtils.getPlatformConfiguration(null),configDir, pluginMap, brandingPluginID);
195             checkPluginPropertiesConsistency(pluginMap, configDir);
196         } catch (CoreException e) {
197             // Rethrow
198
throw e;
199         } catch (Exception JavaDoc e) {
200             // Wrap everything else in a core exception.
201
String JavaDoc message = e.getMessage();
202             if (message==null || message.length() == 0)
203                 message = PDECoreMessages.TargetPlatform_exceptionThrown;
204             throw new CoreException(
205                 new Status(
206                     IStatus.ERROR,
207                     PDECore.getPluginId(),
208                     IStatus.ERROR,
209                     message,
210                     e));
211         }
212     }
213     
214     private static void checkPluginPropertiesConsistency(Map JavaDoc map, File JavaDoc configDir) {
215         File JavaDoc runtimeDir = new File JavaDoc(configDir, "org.eclipse.core.runtime"); //$NON-NLS-1$
216
if (runtimeDir.exists() && runtimeDir.isDirectory()) {
217             long timestamp = runtimeDir.lastModified();
218             Iterator JavaDoc iter = map.values().iterator();
219             while (iter.hasNext()) {
220                 if (hasChanged((IPluginModelBase)iter.next(), timestamp)) {
221                     CoreUtility.deleteContent(runtimeDir);
222                     break;
223                 }
224             }
225         }
226     }
227     
228     private static boolean hasChanged(IPluginModelBase model, long timestamp) {
229         if (model.getUnderlyingResource() != null) {
230             File JavaDoc[] files = new File JavaDoc(model.getInstallLocation()).listFiles();
231             for (int i = 0; i < files.length; i++) {
232                 if (files[i].isDirectory())
233                     continue;
234                 String JavaDoc name = files[i].getName();
235                 if (name.startsWith("plugin") && name.endsWith(".properties") //$NON-NLS-1$ //$NON-NLS-2$
236
&& files[i].lastModified() > timestamp) {
237                      return true;
238                 }
239             }
240         }
241         return false;
242     }
243
244     private static void savePlatformConfiguration(
245         IPlatformConfiguration platformConfiguration,
246         File JavaDoc configFile,
247         Map JavaDoc pluginMap,
248         String JavaDoc primaryFeatureId)
249         throws IOException JavaDoc, CoreException, MalformedURLException JavaDoc {
250         ArrayList JavaDoc sites = new ArrayList JavaDoc();
251
252         // Compute local sites
253
Iterator JavaDoc iter = pluginMap.values().iterator();
254         while(iter.hasNext()) {
255             IPluginModelBase model = (IPluginModelBase)iter.next();
256             IPath sitePath = getTransientSitePath(model);
257             addToSite(sitePath, model, sites);
258         }
259
260         createConfigurationEntries(platformConfiguration,sites);
261         if (primaryFeatureId != null)
262             createFeatureEntries(platformConfiguration, pluginMap, primaryFeatureId);
263         platformConfiguration.refresh();
264         platformConfiguration.save(new URL JavaDoc("file:" + configFile.getPath())); //$NON-NLS-1$
265
}
266
267     private static IPath getTransientSitePath(IPluginModelBase model) {
268         return new Path(model.getInstallLocation()).removeLastSegments(2);
269     }
270     
271     private static void addToSite(
272         IPath path,
273         IPluginModelBase model,
274         ArrayList JavaDoc sites) {
275         if (path.getDevice() != null)
276             path = path.setDevice(path.getDevice().toUpperCase(Locale.ENGLISH));
277         for (int i = 0; i < sites.size(); i++) {
278             LocalSite localSite = (LocalSite) sites.get(i);
279             if (localSite.getPath().equals(path)) {
280                 localSite.add(model);
281                 return;
282             }
283         }
284         // First time - add site
285
LocalSite localSite = new LocalSite(path);
286         localSite.add(model);
287         sites.add(localSite);
288     }
289
290     private static void createConfigurationEntries(
291         IPlatformConfiguration config,
292         ArrayList JavaDoc sites)
293         throws CoreException, MalformedURLException JavaDoc {
294
295         for (int i = 0; i < sites.size(); i++) {
296             LocalSite localSite = (LocalSite) sites.get(i);
297             String JavaDoc[] plugins = localSite.getRelativePluginList();
298
299             int policy = IPlatformConfiguration.ISitePolicy.USER_INCLUDE;
300             IPlatformConfiguration.ISitePolicy sitePolicy =
301                 config.createSitePolicy(policy, plugins);
302             IPlatformConfiguration.ISiteEntry siteEntry =
303                 config.createSiteEntry(localSite.getURL(), sitePolicy);
304             config.configureSite(siteEntry);
305         }
306         config.isTransient(true);
307     }
308
309
310     private static void createFeatureEntries(
311         IPlatformConfiguration config,
312         Map JavaDoc pluginMap,
313         String JavaDoc brandingPluginID)
314         throws MalformedURLException JavaDoc {
315
316         // We have primary feature Id.
317
IFeatureModel featureModel = PDECore.getDefault().getFeatureModelManager().findFeatureModel(brandingPluginID);
318         if (featureModel == null)
319             return;
320         
321         IFeature feature = featureModel.getFeature();
322         String JavaDoc featureVersion = feature.getVersion();
323         IPluginModelBase primaryPlugin = (IPluginModelBase)pluginMap.get(brandingPluginID);
324         if (primaryPlugin == null)
325             return;
326         
327         URL JavaDoc pluginURL = new URL JavaDoc("file:" + primaryPlugin.getInstallLocation()); //$NON-NLS-1$
328
URL JavaDoc[] root = new URL JavaDoc[] { pluginURL };
329         IPlatformConfiguration.IFeatureEntry featureEntry =
330             config.createFeatureEntry(
331                 brandingPluginID,
332                 featureVersion,
333                 brandingPluginID,
334                 primaryPlugin.getPluginBase().getVersion(),
335                 true,
336                 null,
337                 root);
338         config.configureFeatureEntry(featureEntry);
339     }
340
341     public static String JavaDoc getOS() {
342         String JavaDoc value = getProperty(OS);
343         return value.equals("") ? Platform.getOS() : value; //$NON-NLS-1$
344
}
345
346     public static String JavaDoc getWS() {
347         String JavaDoc value = getProperty(WS);
348         return value.equals("") ? Platform.getWS() : value; //$NON-NLS-1$
349
}
350
351     public static String JavaDoc getNL() {
352         String JavaDoc value = getProperty(NL);
353         return value.equals("") ? Platform.getNL() : value; //$NON-NLS-1$
354
}
355
356     public static String JavaDoc getOSArch() {
357         String JavaDoc value = getProperty(ARCH);
358         return value.equals("") ? Platform.getOSArch() : value; //$NON-NLS-1$
359
}
360
361     private static String JavaDoc getProperty(String JavaDoc key) {
362         return PDECore.getDefault().getPluginPreferences().getString(key);
363     }
364     
365     public static String JavaDoc[] getApplicationNames() {
366         TreeSet JavaDoc result = new TreeSet JavaDoc();
367         IPluginModelBase[] plugins = PDECore.getDefault().getModelManager().getPlugins();
368         for (int i = 0; i < plugins.length; i++) {
369             IPluginExtension[] extensions = plugins[i].getPluginBase().getExtensions();
370             for (int j = 0; j < extensions.length; j++) {
371                 String JavaDoc point = extensions[j].getPoint();
372                 if (point != null && point.equals("org.eclipse.core.runtime.applications")) { //$NON-NLS-1$
373
String JavaDoc id = extensions[j].getPluginBase().getId();
374                     if (id == null || id.trim().length() == 0 || id.startsWith("org.eclipse.pde.junit.runtime")) //$NON-NLS-1$
375
continue;
376                     if (extensions[j].getId() != null)
377                         result.add(id+ "." + extensions[j].getId()); //$NON-NLS-1$
378
}
379             }
380         }
381         return (String JavaDoc[])result.toArray(new String JavaDoc[result.size()]);
382     }
383     
384     public static TreeSet JavaDoc getProductNameSet() {
385         TreeSet JavaDoc result = new TreeSet JavaDoc();
386         IPluginModelBase[] plugins = PDECore.getDefault().getModelManager().getPlugins();
387         for (int i = 0; i < plugins.length; i++) {
388             IPluginExtension[] extensions = plugins[i].getPluginBase().getExtensions();
389             for (int j = 0; j < extensions.length; j++) {
390                 String JavaDoc point = extensions[j].getPoint();
391                 if (point != null && point.equals("org.eclipse.core.runtime.products")) {//$NON-NLS-1$
392
IPluginObject[] children = extensions[j].getChildren();
393                     if (children.length != 1)
394                         continue;
395                     if (!"product".equals(children[0].getName())) //$NON-NLS-1$
396
continue;
397                     String JavaDoc id = extensions[j].getPluginBase().getId();
398                     if (id == null || id.trim().length() == 0)
399                         continue;
400                     if (extensions[j].getId() != null)
401                         result.add(id+ "." + extensions[j].getId()); //$NON-NLS-1$
402
}
403             }
404         }
405         return result;
406     }
407     
408     public static String JavaDoc[] getProductNames() {
409         TreeSet JavaDoc result = getProductNameSet();
410         return (String JavaDoc[])result.toArray(new String JavaDoc[result.size()]);
411     }
412     
413     public static Dictionary JavaDoc getTargetEnvironment() {
414         Dictionary JavaDoc result = new Hashtable JavaDoc();
415         result.put ("osgi.os", TargetPlatform.getOS()); //$NON-NLS-1$
416
result.put ("osgi.ws", TargetPlatform.getWS()); //$NON-NLS-1$
417
result.put ("osgi.nl", TargetPlatform.getNL()); //$NON-NLS-1$
418
result.put ("osgi.arch", TargetPlatform.getOSArch()); //$NON-NLS-1$
419
result.put("osgi.resolveOptional", "true"); //$NON-NLS-1$ //$NON-NLS-2$
420
return result;
421     }
422
423     public static String JavaDoc getTargetVersionString() {
424         return PDECore.getDefault().getModelManager().getTargetVersion();
425     }
426     
427     public static double getTargetVersion() {
428         return Double.parseDouble(getTargetVersionString());
429     }
430     
431     public static PDEState getPDEState() {
432         return PDECore.getDefault().getModelManager().getState();
433     }
434
435     public static State getState() {
436         return getPDEState().getState();
437     }
438     
439     public static Map JavaDoc getPatchMap(PDEState state) {
440         HashMap JavaDoc properties = new HashMap JavaDoc();
441         PluginModelManager manager = PDECore.getDefault().getModelManager();
442         IPluginModelBase[] models = manager.getAllPlugins();
443         for (int i = 0; i < models.length; i++) {
444             BundleDescription desc = models[i].getBundleDescription();
445             if (desc == null)
446                 continue;
447             Long JavaDoc id = new Long JavaDoc(desc.getBundleId());
448             if (ClasspathUtilCore.hasExtensibleAPI(models[i])) {
449                 properties.put(id, ICoreConstants.EXTENSIBLE_API + ": true"); //$NON-NLS-1$
450
} else if (ClasspathUtilCore.isPatchFragment(models[i])) {
451                 properties.put(id, ICoreConstants.PATCH_FRAGMENT + ": true"); //$NON-NLS-1$
452
}
453         }
454         return properties;
455     }
456     
457     public static HashMap JavaDoc getBundleClasspaths(PDEState state) {
458         HashMap JavaDoc properties = new HashMap JavaDoc();
459         BundleDescription[] bundles = state.getState().getBundles();
460         for (int i = 0; i < bundles.length; i++) {
461             properties.put(new Long JavaDoc(bundles[i].getBundleId()), getValue(bundles[i], state));
462         }
463         return properties;
464     }
465     
466     private static String JavaDoc[] getValue(BundleDescription bundle, PDEState state) {
467         IPluginModelBase model = PDECore.getDefault().getModelManager().findModel(bundle);
468         String JavaDoc[] result = null;
469         if (model != null) {
470             IPluginLibrary[] libs = model.getPluginBase().getLibraries();
471             result = new String JavaDoc[libs.length];
472             for (int i = 0; i < libs.length; i++) {
473                 result[i] = libs[i].getName();
474             }
475         } else {
476             String JavaDoc[] libs = state.getLibraryNames(bundle.getBundleId());
477             result = new String JavaDoc[libs.length];
478             for (int i = 0; i < libs.length; i++) {
479                 result[i] = libs[i];
480             }
481         }
482         if (result.length == 0)
483             return new String JavaDoc[] {"."}; //$NON-NLS-1$
484
return result;
485     }
486     
487     public static String JavaDoc[] getFeaturePaths() {
488         IFeatureModel[] models = PDECore.getDefault().getFeatureModelManager().getModels();
489         ArrayList JavaDoc list = new ArrayList JavaDoc();
490         for (int i = 0; i < models.length; i++) {
491             String JavaDoc location = models[i].getInstallLocation();
492             if (location != null)
493                 list.add(location + IPath.SEPARATOR + "feature.xml"); //$NON-NLS-1$
494
}
495         return (String JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
496     }
497
498     /**
499      * Obtains product ID
500      *
501      * @return String or null
502      */

503     public static String JavaDoc getDefaultProduct() {
504         Properties JavaDoc config = getConfigIniProperties();
505         if (config != null) {
506             String JavaDoc product = (String JavaDoc) config.get("eclipse.product"); //$NON-NLS-1$
507
if (product != null && getProductNameSet().contains(product))
508                 return product;
509         }
510         Set JavaDoc set = getProductNameSet();
511         if (set.contains("org.eclipse.sdk.ide")) //$NON-NLS-1$
512
return "org.eclipse.sdk.ide"; //$NON-NLS-1$
513

514         return set.contains("org.eclipse.platform.ide") ? "org.eclipse.platform.ide" : null; //$NON-NLS-1$ //$NON-NLS-2$
515
}
516     
517     public static boolean isRuntimeRefactored1() {
518         PluginModelManager manager = PDECore.getDefault().getModelManager();
519         return manager.findEntry("org.eclipse.equinox.common") != null; //$NON-NLS-1$
520
}
521     
522     public static boolean isRuntimeRefactored2() {
523         PluginModelManager manager = PDECore.getDefault().getModelManager();
524         return manager.findEntry("org.eclipse.core.runtime.compatibility.registry") != null; //$NON-NLS-1$
525
}
526     
527     public static boolean matchesCurrentEnvironment(IPluginModelBase model) {
528         BundleContext context = PDECore.getDefault().getBundleContext();
529         Dictionary JavaDoc environment = getTargetEnvironment();
530         BundleDescription bundle = model.getBundleDescription();
531         String JavaDoc filterSpec = bundle != null ? bundle.getPlatformFilter() : null;
532         try {
533             return filterSpec == null|| context.createFilter(filterSpec).match(environment);
534         } catch (InvalidSyntaxException e) {
535             return false;
536         }
537     }
538     
539 }
540
Popular Tags