KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > update > internal > configurator > Utils


1 /*******************************************************************************
2  * Copyright (c) 2004, 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 176250, Configurator needs to handle more platform urls
11  *******************************************************************************/

12 package org.eclipse.update.internal.configurator;
13
14 import java.io.File JavaDoc;
15 import java.net.MalformedURLException JavaDoc;
16 import java.net.URL JavaDoc;
17 import java.util.Locale JavaDoc;
18 import java.util.MissingResourceException JavaDoc;
19 import java.util.ResourceBundle JavaDoc;
20 import java.util.StringTokenizer JavaDoc;
21
22 import org.eclipse.core.runtime.CoreException;
23 import org.eclipse.core.runtime.IPath;
24 import org.eclipse.core.runtime.IStatus;
25 import org.eclipse.core.runtime.MultiStatus;
26 import org.eclipse.core.runtime.Path;
27 import org.eclipse.core.runtime.Status;
28 import org.eclipse.osgi.framework.log.FrameworkLog;
29 import org.eclipse.osgi.framework.log.FrameworkLogEntry;
30 import org.eclipse.osgi.service.datalocation.Location;
31 import org.eclipse.osgi.service.resolver.PlatformAdmin;
32 import org.osgi.framework.Bundle;
33 import org.osgi.framework.BundleContext;
34 import org.osgi.framework.Filter;
35 import org.osgi.framework.InvalidSyntaxException;
36 import org.osgi.framework.ServiceReference;
37 import org.osgi.service.packageadmin.PackageAdmin;
38 import org.osgi.util.tracker.ServiceTracker;
39
40 public class Utils {
41     private static final String JavaDoc PROP_ARCH = "osgi.arch"; //$NON-NLS-1$
42
private static final String JavaDoc PROP_NL = "osgi.nl"; //$NON-NLS-1$
43
private static final String JavaDoc PROP_OS = "osgi.os"; //$NON-NLS-1$
44
private static final String JavaDoc PROP_WS = "osgi.ws"; //$NON-NLS-1$
45
private static final String JavaDoc PI_OSGI = "org.eclipse.osgi"; //$NON-NLS-1$
46
private static final String JavaDoc KEY_PREFIX = "%"; //$NON-NLS-1$
47
private static final String JavaDoc KEY_DOUBLE_PREFIX = "%%"; //$NON-NLS-1$
48
// os
49
public static boolean isWindows = System.getProperty("os.name").startsWith("Win"); //$NON-NLS-1$ //$NON-NLS-2$
50
static FrameworkLog log;
51     private static ServiceTracker bundleTracker;
52     private static ServiceTracker instanceLocation;
53     private static ServiceTracker configurationLocation;
54
55     public static void debug(String JavaDoc s) {
56         if (ConfigurationActivator.DEBUG)
57             System.out.println("PlatformConfig: " + s); //$NON-NLS-1$
58
}
59     
60     /**
61      * Creates a CoreException from some other exception.
62      * The type of the CoreException is <code>IStatus.ERROR</code>
63      * If the exception passed as a parameter is also a CoreException,
64      * the new CoreException will contain all the status of the passed
65      * CoreException.
66      *
67      * @see IStatus#ERROR
68      * @param s exception string
69      * @param e actual exception being reported
70      * @return a CoreException
71      * @since 2.0
72      */

73     public static CoreException newCoreException(String JavaDoc s, Throwable JavaDoc e) {
74
75         // check the case of a multistatus
76
IStatus status;
77         if (e instanceof CoreException) {
78             if (s == null)
79                 s = ""; //$NON-NLS-1$
80
status = new MultiStatus("org.eclipse.update.configurator", 0, s, e); //$NON-NLS-1$
81
IStatus childrenStatus = ((CoreException) e).getStatus();
82             ((MultiStatus) status).add(childrenStatus);
83             ((MultiStatus) status).addAll(childrenStatus);
84         } else {
85             StringBuffer JavaDoc completeString = new StringBuffer JavaDoc(""); //$NON-NLS-1$
86
if (s != null)
87                 completeString.append(s);
88             if (e != null) {
89                 completeString.append(" ["); //$NON-NLS-1$
90
String JavaDoc msg = e.getLocalizedMessage();
91                 completeString.append(msg!=null?msg:e.toString());
92                 completeString.append("]"); //$NON-NLS-1$
93
}
94             status = newStatus(completeString.toString(), e);
95         }
96         return new CoreException(status);
97     }
98
99     public static IStatus newStatus(String JavaDoc message, Throwable JavaDoc e) {
100         return new Status(IStatus.ERROR, "org.eclipse.update.configurator", IStatus.OK, message, e); //$NON-NLS-1$
101
}
102     
103     public static void log(String JavaDoc message) {
104         log(newStatus(message, null));
105     }
106     
107     public static void log(IStatus status) {
108         if (log != null) {
109             log.log(new FrameworkLogEntry(ConfigurationActivator.PI_CONFIGURATOR, status.getMessage(), 0, status.getException(), null));
110         } else {
111             System.out.println(status.getMessage());
112             if (status.getException() != null)
113                 status.getException().printStackTrace();
114         }
115     }
116     
117     /**
118      * Close the services that we were listening to.
119      */

120     /*package*/ static synchronized void shutdown() {
121         if (bundleTracker != null) {
122             bundleTracker.close();
123             bundleTracker = null;
124         }
125         if (instanceLocation != null) {
126             instanceLocation.close();
127             instanceLocation = null;
128         }
129         if (configurationLocation != null) {
130             configurationLocation.close();
131             configurationLocation = null;
132         }
133     }
134
135     /**
136      * Return a boolean value indicating whether or not we consider the
137      * platform to be running.
138      */

139     public static boolean isRunning() {
140         Bundle JavaDoc bundle = getBundle(PI_OSGI);
141         return bundle == null ? false : bundle.getState() == Bundle.ACTIVE;
142     }
143
144     /**
145      *
146      */

147     public static boolean isValidEnvironment(String JavaDoc os, String JavaDoc ws, String JavaDoc arch, String JavaDoc nl) {
148         if (os!=null && !isMatching(os, getOS())) return false;
149         if (ws!=null && !isMatching(ws, getWS())) return false;
150         if (arch!=null && !isMatching(arch, getArch())) return false;
151         if (nl!=null && !isMatchingLocale(nl, getNL())) return false;
152         return true;
153     }
154     
155     /**
156      * Return the current operating system value.
157      *
158      * @see EnvironmentInfo#getOS()
159      */

160     public static String JavaDoc getOS() {
161         return getContext().getProperty(PROP_OS);
162     }
163
164     /**
165      * Return the current windowing system value.
166      *
167      * @see EnvironmentInfo#getWS()
168      */

169     public static String JavaDoc getWS() {
170         return getContext().getProperty(PROP_WS);
171     }
172
173     /**
174      * Return the current system architecture value.
175      *
176      * @see EnvironmentInfo#getOSArch()
177      */

178     public static String JavaDoc getArch() {
179         return getContext().getProperty(PROP_ARCH);
180     }
181
182     /**
183      * Return the current NL value.
184      *
185      * @see EnvironmentInfo#getNL()
186      */

187     public static String JavaDoc getNL() {
188         return getContext().getProperty(PROP_NL);
189     }
190     
191     /**
192      * Returns a number that changes whenever the set of installed plug-ins
193      * changes. This can be used for invalidating caches that are based on
194      * the set of currently installed plug-ins. (e.g. extensions)
195      *
196      * @see PlatformAdmin#getState()
197      * @see State#getTimeStamp()
198      */

199     public static long getStateStamp() {
200         ServiceReference platformAdminReference = getContext().getServiceReference(PlatformAdmin.class.getName());
201         if (platformAdminReference == null)
202             return -1;
203         PlatformAdmin admin = (PlatformAdmin) getContext().getService(platformAdminReference);
204         return admin == null ? -1 : admin.getState(false).getTimeStamp();
205     }
206
207     /**
208      * Return the resolved bundle with the specified symbolic name.
209      *
210      * @see PackageAdmin#getBundles(String, String)
211      */

212     public static synchronized Bundle JavaDoc getBundle(String JavaDoc symbolicName) {
213         if (bundleTracker == null) {
214             bundleTracker = new ServiceTracker(getContext(), PackageAdmin.class.getName(), null);
215             bundleTracker.open();
216         }
217         PackageAdmin admin = (PackageAdmin) bundleTracker.getService();
218         if (admin == null)
219             return null;
220         Bundle JavaDoc[] bundles = admin.getBundles(symbolicName, null);
221         if (bundles == null)
222             return null;
223         //Return the first bundle that is not installed or uninstalled
224
for (int i = 0; i < bundles.length; i++) {
225             if ((bundles[i].getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED)) == 0) {
226                 return bundles[i];
227             }
228         }
229         return null;
230     }
231
232     /*
233      * Return the bundle context for this bundle.
234      */

235     private static BundleContext getContext() {
236         return ConfigurationActivator.getBundleContext();
237     }
238
239     /**
240      * Return the configuration location.
241      *
242      * @see Location
243      */

244     public static synchronized Location getConfigurationLocation() {
245         if (configurationLocation == null) {
246             Filter filter = null;
247             try {
248                 filter = getContext().createFilter(Location.CONFIGURATION_FILTER);
249             } catch (InvalidSyntaxException e) {
250                 // ignore this. It should never happen as we have tested the above format.
251
}
252             configurationLocation = new ServiceTracker(getContext(), filter, null);
253             configurationLocation.open();
254         }
255         return (Location) configurationLocation.getService();
256     }
257     
258     /**
259      *
260      */

261     private static boolean isMatching(String JavaDoc candidateValues, String JavaDoc siteValues) {
262         if (siteValues==null) return false;
263         if ("*".equalsIgnoreCase(candidateValues)) return true; //$NON-NLS-1$
264
siteValues = siteValues.toUpperCase();
265         StringTokenizer JavaDoc stok = new StringTokenizer JavaDoc(candidateValues, ","); //$NON-NLS-1$
266
while (stok.hasMoreTokens()) {
267             String JavaDoc token = stok.nextToken().toUpperCase();
268             if (siteValues.indexOf(token)!=-1) return true;
269         }
270         return false;
271     }
272     
273     /**
274      *
275      */

276     private static boolean isMatchingLocale(String JavaDoc candidateValues, String JavaDoc locale) {
277         if (locale==null) return false;
278         if ("*".equalsIgnoreCase(candidateValues)) return true; //$NON-NLS-1$
279

280         locale = locale.toUpperCase();
281         candidateValues = candidateValues.toUpperCase();
282         StringTokenizer JavaDoc stok = new StringTokenizer JavaDoc(candidateValues, ","); //$NON-NLS-1$
283
while (stok.hasMoreTokens()) {
284             String JavaDoc candidate = stok.nextToken();
285             if (locale.indexOf(candidate) == 0)
286                 return true;
287             if (candidate.indexOf(locale) == 0)
288                 return true;
289         }
290         return false;
291     }
292     
293     public static Locale JavaDoc getDefaultLocale() {
294         String JavaDoc nl = getNL();
295         // sanity test
296
if (nl == null)
297             return Locale.getDefault();
298         
299         // break the string into tokens to get the Locale object
300
StringTokenizer JavaDoc locales = new StringTokenizer JavaDoc(nl,"_"); //$NON-NLS-1$
301
if (locales.countTokens() == 1)
302             return new Locale JavaDoc(locales.nextToken(), ""); //$NON-NLS-1$
303
else if (locales.countTokens() == 2)
304             return new Locale JavaDoc(locales.nextToken(), locales.nextToken());
305         else if (locales.countTokens() == 3)
306             return new Locale JavaDoc(locales.nextToken(), locales.nextToken(), locales.nextToken());
307         else
308             return Locale.getDefault();
309     }
310     
311     
312     /**
313      * Returns a resource string corresponding to the given argument
314      * value and bundle.
315      * If the argument value specifies a resource key, the string
316      * is looked up in the given resource bundle. If the argument does not
317      * specify a valid key, the argument itself is returned as the
318      * resource string. The key lookup is performed against the
319      * specified resource bundle. If a resource string
320      * corresponding to the key is not found in the resource bundle
321      * the key value, or any default text following the key in the
322      * argument value is returned as the resource string.
323      * A key is identified as a string begining with the "%" character.
324      * Note that the "%" character is stripped off prior to lookup
325      * in the resource bundle.
326      * <p>
327      * For example, assume resource bundle plugin.properties contains
328      * name = Project Name
329      * <pre>
330      * resolveNLString(b,"Hello World") returns "Hello World"</li>
331      * resolveNLString(b,"%name") returns "Project Name"</li>
332      * resolveNLString(b,"%name Hello World") returns "Project Name"</li>
333      * resolveNLString(b,"%abcd Hello World") returns "Hello World"</li>
334      * resolveNLString(b,"%abcd") returns "%abcd"</li>
335      * resolveNLString(b,"%%name") returns "%name"</li>
336      * </pre>
337      * </p>
338      *
339      * @param resourceBundle resource bundle.
340      * @param string translatable string from model
341      * @return string, or <code>null</code>
342      * @since 2.0
343      */

344     public static String JavaDoc getResourceString(ResourceBundle JavaDoc resourceBundle, String JavaDoc string) {
345
346         if (string == null)
347             return null;
348
349         String JavaDoc s = string.trim();
350
351         if (s.equals("")) //$NON-NLS-1$
352
return string;
353
354         if (!s.startsWith(KEY_PREFIX))
355             return string;
356
357         if (s.startsWith(KEY_DOUBLE_PREFIX))
358             return s.substring(1);
359
360         int ix = s.indexOf(" "); //$NON-NLS-1$
361
String JavaDoc key = ix == -1 ? s : s.substring(0, ix);
362         String JavaDoc dflt = ix == -1 ? s : s.substring(ix + 1);
363
364         if (resourceBundle == null)
365             return dflt;
366
367         try {
368             return resourceBundle.getString(key.substring(1));
369         } catch (MissingResourceException JavaDoc e) {
370             return dflt;
371         }
372     }
373
374     public static boolean isAutomaticallyStartedBundle(String JavaDoc bundleURL) {
375         if (bundleURL.indexOf("org.eclipse.osgi") != -1) //$NON-NLS-1$
376
return true;
377         
378         String JavaDoc osgiBundles = ConfigurationActivator.getBundleContext().getProperty("osgi.bundles"); //$NON-NLS-1$
379
StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(osgiBundles, ","); //$NON-NLS-1$
380
while (st.hasMoreTokens()) {
381             String JavaDoc token = st.nextToken().trim();
382             int index = token.indexOf('@');
383             if (index != -1)
384                 token = token.substring(0,index);
385             if (token.startsWith("reference:file:")) { //$NON-NLS-1$
386
File JavaDoc f = new File JavaDoc(token.substring(15));
387                 if (bundleURL.indexOf(f.getName()) != -1)
388                     return true;
389             }
390             if (bundleURL.indexOf(token) != -1)
391                 return true;
392         }
393         return false;
394     }
395
396     /**
397      * Returns an absolute URL by combining a base absolute URL and another URL relative to the first one.
398      * If the relative URL protocol does not match the base URL protocol, or if the relative URL path is not relative,
399      * return it as is.
400      */

401     public static URL JavaDoc makeAbsolute(URL JavaDoc base, URL JavaDoc relativeLocation) {
402         if (!"file".equals(base.getProtocol())) //$NON-NLS-1$
403
// we only deal with file: URLs
404
return relativeLocation;
405         if (relativeLocation.getProtocol() != null && !relativeLocation.getProtocol().equals(base.getProtocol()))
406             // it is not relative, return as is (avoid creating garbage)
407
return relativeLocation;
408         IPath relativePath = new Path(relativeLocation.getPath());
409         if (relativePath.isAbsolute())
410             return relativeLocation;
411         try {
412             IPath absolutePath = new Path(base.getPath()).append(relativeLocation.getPath());
413             // File.toURL() is the best way to create a file: URL
414
return absolutePath.toFile().toURL();
415         } catch (MalformedURLException JavaDoc e) {
416             // cannot happen since we are building from two existing valid URLs
417
Utils.log(e.getLocalizedMessage());
418             return relativeLocation;
419         }
420     }
421
422     /**
423      * Returns a URL which is equivalent to the given URL relative to the
424      * specified base URL. Works only for file: URLs
425      */

426     public static URL JavaDoc makeRelative(URL JavaDoc base, URL JavaDoc location) {
427         if (base == null)
428             return location;
429         if (!"file".equals(base.getProtocol())) //$NON-NLS-1$
430
return location;
431         if (!base.getProtocol().equals(location.getProtocol()))
432             return location;
433         IPath locationPath = new Path(location.getPath());
434         if (!locationPath.isAbsolute())
435             return location;
436         IPath relativePath = makeRelative(new Path(base.getPath()), locationPath);
437         try {
438             return new URL JavaDoc(base.getProtocol(), base.getHost(), base.getPort(), relativePath.toString());
439         } catch (MalformedURLException JavaDoc e) {
440             String JavaDoc message = e.getMessage();
441             if (message == null)
442                 message = ""; //$NON-NLS-1$
443
Utils.log(Utils.newStatus(message, e));
444         }
445         return location;
446     }
447
448     /**
449      * Returns a path which is equivalent to the given location relative to the
450      * specified base path.
451      */

452     public static IPath makeRelative(IPath base, IPath location) {
453         if (location.getDevice() != null && !location.getDevice().equalsIgnoreCase(base.getDevice()))
454             return location;
455         int baseCount = base.segmentCount();
456         int count = base.matchingFirstSegments(location);
457         String JavaDoc temp = ""; //$NON-NLS-1$
458
for (int j = 0; j < baseCount - count; j++)
459             temp += "../"; //$NON-NLS-1$
460
return new Path(temp).append(location.removeFirstSegments(count));
461     }
462
463     /**
464      * Returns a string URL which is equivalent to the given absolute location
465      * made relative to the specified base path.
466      */

467     public static String JavaDoc makeRelative(URL JavaDoc base, String JavaDoc absolute) {
468         try {
469             return makeRelative(base, new URL JavaDoc(absolute)).toExternalForm();
470         } catch (MalformedURLException JavaDoc e) {
471             // returns the original string if is invalid
472
return absolute;
473         }
474     }
475
476     /**
477      * Ensures file: URLs on Windows have the right form (i.e. '/' as segment separator, drive letter in lower case, etc)
478      */

479     public static String JavaDoc canonicalizeURL(String JavaDoc url) {
480         if (!(isWindows && url.startsWith("file:"))) //$NON-NLS-1$
481
return url;
482         try {
483             String JavaDoc path = new URL JavaDoc(url).getPath();
484             // normalize to not have leading / so we can check the form
485
File JavaDoc file = new File JavaDoc(path);
486             path = file.toString().replace('\\', '/');
487             if (Character.isUpperCase(path.charAt(0))) {
488                 char[] chars = path.toCharArray();
489                 chars[0] = Character.toLowerCase(chars[0]);
490                 path = new String JavaDoc(chars);
491                 return new File JavaDoc(path).toURL().toExternalForm();
492             }
493         } catch (MalformedURLException JavaDoc e) {
494             // default to original url
495
}
496         return url;
497     }
498
499     /**
500      * Return the install location.
501      *
502      * @see Location
503      */

504     public static synchronized URL JavaDoc getInstallURL() {
505         if (instanceLocation == null) {
506             Filter filter = null;
507             try {
508                 filter = getContext().createFilter(Location.INSTALL_FILTER);
509             } catch (InvalidSyntaxException e) {
510                 // ignore this. It should never happen as we have tested the
511
// above format.
512
}
513             instanceLocation = new ServiceTracker(getContext(), filter, null);
514             instanceLocation.open();
515         }
516
517         Location location = (Location) instanceLocation.getService();
518
519         // it is pretty much impossible for the install location to be null. If it is, the
520
// system is in a bad way so throw and exception and get the heck outta here.
521
if (location == null)
522             throw new IllegalStateException JavaDoc("The installation location must not be null"); //$NON-NLS-1$
523

524         return location.getURL();
525     }
526
527 }
528
Popular Tags