KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > emf > common > EMFPlugin


1 /**
2  * <copyright>
3  *
4  * Copyright (c) 2002-2005 IBM Corporation and others.
5  * All rights reserved. This program and the accompanying materials
6  * are made available under the terms of the Eclipse Public License v1.0
7  * which accompanies this distribution, and is available at
8  * http://www.eclipse.org/legal/epl-v10.html
9  *
10  * Contributors:
11  * IBM - Initial API and implementation
12  *
13  * </copyright>
14  *
15  * $Id: EMFPlugin.java,v 1.10 2005/06/15 12:50:35 emerks Exp $
16  */

17 package org.eclipse.emf.common;
18
19
20 import java.io.IOException JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.net.MalformedURLException JavaDoc;
23 import java.net.URL JavaDoc;
24 import java.text.MessageFormat JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.MissingResourceException JavaDoc;
28 import java.util.PropertyResourceBundle JavaDoc;
29 import java.util.ResourceBundle JavaDoc;
30
31 import org.eclipse.core.runtime.IStatus;
32 import org.eclipse.core.runtime.Platform;
33 import org.eclipse.core.runtime.Plugin;
34 import org.eclipse.core.runtime.Status;
35
36 import org.eclipse.emf.common.util.Logger;
37 import org.eclipse.emf.common.util.ResourceLocator;
38 import org.eclipse.emf.common.util.URI;
39 import org.eclipse.emf.common.util.WrappedException;
40
41
42 /**
43  * EMF must run
44  * within an Eclipse workbench,
45  * within a headless Eclipse workspace,
46  * or just stand-alone as part of some other application.
47  * To support this, all resource access (e.g., NL strings, images, and so on) is directed to the resource locator methods,
48  * which can redirect the service as appopriate to the runtime.
49  * During Eclipse invocation, the implementation delegates to a plugin implementation.
50  * During stand-alone invocation, no plugin initialization takes place,
51  * so the implementation delegates to a resource JAR on the CLASSPATH.
52  * The resource jar will typically <b>not</b> be on the CLASSPATH during Eclipse invocation.
53  * It will contain things like the icons and the .properties,
54  * which are available in a different way during Eclipse invocation.
55  * @see ResourceLocator
56  * @see Logger
57  */

58 public abstract class EMFPlugin implements ResourceLocator, Logger
59 {
60   public static final boolean IS_ECLIPSE_RUNNING;
61   static
62   {
63     boolean result = false;
64     try
65     {
66       result = Platform.isRunning();
67     }
68     catch (Throwable JavaDoc exception)
69     {
70     }
71     IS_ECLIPSE_RUNNING = result;
72   }
73
74   protected ResourceLocator [] delegateResourceLocators;
75   protected URL JavaDoc baseURL;
76   protected ResourceBundle JavaDoc untranslatedResourceBundle;
77   protected ResourceBundle JavaDoc resourceBundle;
78   protected Map JavaDoc strings = new HashMap JavaDoc();
79   protected Map JavaDoc untranslatedStrings = new HashMap JavaDoc();
80   protected boolean shouldTranslate = true;
81   protected Map JavaDoc images = new HashMap JavaDoc();
82
83   public EMFPlugin(ResourceLocator [] delegateResourceLocators)
84   {
85     this.delegateResourceLocators = delegateResourceLocators;
86   }
87
88   /**
89    * Returns an Eclipse plugin implementation of a resource locator.
90    * @return an Eclipse plugin implementation of a resource locator.
91    */

92   public abstract ResourceLocator getPluginResourceLocator();
93
94   /**
95    * Returns an Eclipse plugin implementation of a logger.
96    * @return an Eclipse plugin implementation of a logger.
97    */

98   public Logger getPluginLogger()
99   {
100     return (Logger)getPluginResourceLocator();
101   }
102
103   public String JavaDoc getSymbolicName()
104   {
105     if (getPluginResourceLocator() instanceof EclipsePlugin)
106     {
107       return ((EclipsePlugin)getPluginResourceLocator()).getSymbolicName();
108     }
109     else
110     {
111       throw new UnsupportedOperationException JavaDoc("Plugin ID not available " + this);
112     }
113   }
114
115   /*
116    * Javadoc copied from interface.
117    */

118   public URL JavaDoc getBaseURL()
119   {
120     if (baseURL == null)
121     {
122       if (getPluginResourceLocator() == null)
123       {
124         try
125         {
126           // Determine the base URL by looking for the plugin.properties file in the standard way.
127
//
128
Class JavaDoc theClass = getClass();
129           URL JavaDoc pluginPropertiesURL = theClass.getResource("plugin.properties");
130           if (pluginPropertiesURL == null)
131           {
132             // If that fails, determine the URL for the class itself.
133
// The URL will be of one of the following forms,
134
// so there are a few good places to consider looking for the plugin.properties.
135
//
136
// For a plugin.xml with runtime="common.jar":
137
// jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/common.jar!/org/eclipse/common/CommonPlugin.class
138
//
139
// For a plugin.xml with runtime="runtime/common.jar":
140
// jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/runtime/common.jar!/org/eclipse/common/CommonPlugin.class
141
//
142
// For a plugin.xml with runtime="." where the plugin is jarred:
143
// jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common.jar!/org/eclipse/common/CommonPlugin.class
144
//
145
// For a plugin.xml with runtime="." where the plugin is not jarred.
146
// file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/org/eclipse/emf/common/CommonPlugin.class
147
//
148
// Running in PDE with bin on classpath:
149
// file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/bin/org/eclipse/emf/common/CommonPlugin.class
150
//
151
String JavaDoc className = theClass.getName();
152             int index = className.lastIndexOf(".");
153             URL JavaDoc classURL = theClass.getResource((index == -1 ? className : className.substring(index + 1)) + ".class");
154             URI uri = URI.createURI(classURL.toString());
155             
156             // Trim off the segements corresponding to the package nesting.
157
//
158
int count = 1;
159             for (int i = 0; (i = className.indexOf('.', i)) != -1; ++i)
160             {
161               ++count;
162             }
163             uri = uri.trimSegments(count);
164             
165             // For an archive URI, check for the plugin.properties in the archive.
166
//
167
if (URI.isArchiveScheme(uri.scheme()))
168             {
169               try
170               {
171                 // If we can open an input stream, then the plugin.properties is there, and we have a good base URL.
172
//
173
InputStream JavaDoc inputStream = new URL JavaDoc(uri.appendSegment("plugin.properties").toString()).openStream();
174                 inputStream.close();
175                 baseURL = new URL JavaDoc(uri.toString());
176               }
177               catch (IOException JavaDoc exception)
178               {
179                 // If the plugin.properties isn't within the root of the archive,
180
// create a new URI for the folder location of the archive,
181
// so we can look in the folder that contains it.
182
//
183
uri = URI.createURI(uri.authority()).trimSegments(1);
184               }
185             }
186             
187             // If we didn't find the plugin.properties in the usual place nor in the archive...
188
//
189
if (baseURL == null)
190             {
191               // Trim off the "bin" or "runtime" segement.
192
//
193
String JavaDoc lastSegment = uri.lastSegment();
194               if ("bin".equals(lastSegment) || "runtime".equals(lastSegment))
195               {
196                 uri = uri.trimSegments(1);
197               }
198               uri = uri.appendSegment("plugin.properties");
199               try
200               {
201                 // If we can open an input stream, then the plugin.properties is in the folder, and we have a good base URL.
202
//
203
InputStream JavaDoc inputStream = new URL JavaDoc(uri.toString()).openStream();
204                 inputStream.close();
205                 baseURL = new URL JavaDoc(uri.trimSegments(1).toString() + "/");
206               }
207               catch (IOException JavaDoc exception)
208               {
209               }
210             }
211             
212             // If we still don't have a good base URL, complain about it.
213
//
214
if (baseURL == null)
215             {
216               String JavaDoc resourceName =
217                 index == -1 ?
218                   "plugin.properties" :
219                   className.substring(0, index + 1).replace('.','/') + "plugin.properties";
220               throw new MissingResourceException JavaDoc("Missing properties: " + resourceName, theClass.getName(), "plugin.properties");
221             }
222           }
223           else
224           {
225             baseURL = new URL JavaDoc(URI.createURI(pluginPropertiesURL.toString()).trimSegments(1).toString() + "/");
226           }
227         }
228         catch (IOException JavaDoc exception)
229         {
230           throw new WrappedException(exception);
231         }
232       }
233       else
234       {
235         baseURL = getPluginResourceLocator().getBaseURL();
236       }
237     }
238
239     return baseURL;
240   }
241
242   /*
243    * Javadoc copied from interface.
244    */

245   public Object JavaDoc getImage(String JavaDoc key)
246   {
247     Object JavaDoc result = (URL JavaDoc)images.get(key);
248     if (result == null)
249     {
250       if (getPluginResourceLocator() == null)
251       {
252         try
253         {
254           result = doGetImage(key);
255         }
256         catch (MalformedURLException JavaDoc exception)
257         {
258           throw new WrappedException(exception);
259         }
260         catch (IOException JavaDoc exception)
261         {
262           result = delegatedGetImage(key);
263         }
264       }
265       else
266       {
267         try
268         {
269           result = getPluginResourceLocator().getImage(key);
270         }
271         catch (MissingResourceException JavaDoc exception)
272         {
273           result = delegatedGetImage(key);
274         }
275       }
276
277       images.put(key, result);
278     }
279
280     return result;
281   }
282
283   /**
284    * Does the work of fetching the image associated with the key.
285    * It ensures that the image exists.
286    * @param key the key of the image to fetch.
287    * @exception IOException if an image doesn't exist.
288    * @return the description of the image associated with the key.
289    */

290   protected Object JavaDoc doGetImage(String JavaDoc key) throws IOException JavaDoc
291   {
292     URL JavaDoc url = new URL JavaDoc(getBaseURL() + "icons/" + key + ".gif");
293     InputStream JavaDoc inputStream = url.openStream();
294     inputStream.close();
295     return url;
296   }
297
298   /**
299    * Does the work of fetching the image associated with the key,
300    * when the image resource is not available locally.
301    * @param key the key of the image to fetch.
302    * @exception MissingResourceException if the image resource doesn't exist anywhere.
303    * @see #delegateResourceLocators
304    */

305   protected Object JavaDoc delegatedGetImage(String JavaDoc key) throws MissingResourceException JavaDoc
306   {
307     for (int i = 0; i < delegateResourceLocators.length; ++i)
308     {
309       try
310       {
311         return delegateResourceLocators[i].getImage(key);
312       }
313       catch (MissingResourceException JavaDoc exception)
314       {
315       }
316     }
317
318     throw
319       new MissingResourceException JavaDoc
320         (CommonPlugin.INSTANCE.getString("_UI_ImageResourceNotFound_exception", new Object JavaDoc [] { key }),
321          getClass().getName(),
322          key);
323   }
324
325   /**
326    * Indicates whether strings should be translated by default.
327    *
328    * @return <code>true</code> if strings should be translated by default; <code>false</code> otherwise.
329    */

330   public boolean shouldTranslate()
331   {
332     return shouldTranslate;
333   }
334
335   /**
336    * Sets whether strings should be translated by default.
337    *
338    * @param shouldTranslate whether strings should be translated by default.
339    */

340   public void setShouldTranslate(boolean shouldTranslate)
341   {
342     this.shouldTranslate = shouldTranslate;
343   }
344
345   /*
346    * Javadoc copied from interface.
347    */

348   public String JavaDoc getString(String JavaDoc key)
349   {
350     return getString(key, shouldTranslate());
351   }
352
353   /*
354    * Javadoc copied from interface.
355    */

356   public String JavaDoc getString(String JavaDoc key, boolean translate)
357   {
358     Map JavaDoc stringMap = translate ? strings : untranslatedStrings;
359     String JavaDoc result = (String JavaDoc)stringMap.get(key);
360     if (result == null)
361     {
362       try
363       {
364         if (getPluginResourceLocator() == null)
365         {
366           ResourceBundle JavaDoc bundle = translate ? resourceBundle : untranslatedResourceBundle;
367           if (bundle == null)
368           {
369             String JavaDoc packageName = getClass().getName();
370             int index = packageName.lastIndexOf(".");
371             if (index != -1)
372             {
373               packageName = packageName.substring(0, index);
374             }
375             if (translate)
376             {
377               try
378               {
379                 bundle = resourceBundle = ResourceBundle.getBundle(packageName + ".plugin");
380               }
381               catch (MissingResourceException JavaDoc exception)
382               {
383                 // If the bundle can't be found the normal way, try to find it as the base URL.
384
// If that also doesn't work, rethrow the original exception.
385
//
386
try
387                 {
388                   InputStream JavaDoc inputStream = new URL JavaDoc(getBaseURL().toString() + "plugin.properties").openStream();
389                   bundle = untranslatedResourceBundle = resourceBundle = new PropertyResourceBundle JavaDoc(inputStream);
390                   inputStream.close();
391                 }
392                 catch (IOException JavaDoc ioException)
393                 {
394                 }
395                 if (resourceBundle == null)
396                 {
397                   throw exception;
398                 }
399               }
400             }
401             else
402             {
403               String JavaDoc resourceName = getBaseURL().toString() + "plugin.properties";
404               try
405               {
406                 InputStream JavaDoc inputStream = new URL JavaDoc(resourceName).openStream();
407                 bundle = untranslatedResourceBundle = new PropertyResourceBundle JavaDoc(inputStream);
408                 inputStream.close();
409               }
410               catch (IOException JavaDoc ioException)
411               {
412                 throw new MissingResourceException JavaDoc("Missing properties: " + resourceName, getClass().getName(), "plugin.properties");
413               }
414             }
415           }
416           result = bundle.getString(key);
417         }
418         else
419         {
420           result = getPluginResourceLocator().getString(key, translate);
421         }
422       }
423       catch (MissingResourceException JavaDoc exception)
424       {
425         result = delegatedGetString(key, translate);
426       }
427   
428       stringMap.put(key, result);
429     }
430
431     return result;
432   }
433
434   /**
435    * Does the work of fetching the string associated with the key,
436    * when the string resource is not available locally.
437    * @param key the key of the string to fetch.
438    * @exception MissingResourceException if the string resource doesn't exist anywhere.
439    * @see #delegateResourceLocators
440    */

441   protected String JavaDoc delegatedGetString(String JavaDoc key, boolean translate)
442   {
443     for (int i = 0; i < delegateResourceLocators.length; ++i)
444     {
445       try
446       {
447         return delegateResourceLocators[i].getString(key, translate);
448       }
449       catch (MissingResourceException JavaDoc exception)
450       {
451       }
452     }
453
454     throw
455       new MissingResourceException JavaDoc
456         (MessageFormat.format("The string resource ''{0}'' could not be located", new Object JavaDoc [] { key }),
457          getClass().getName(),
458          key);
459   }
460
461   /*
462    * Javadoc copied from interface.
463    */

464   public String JavaDoc getString(String JavaDoc key, Object JavaDoc [] substitutions)
465   {
466     return getString(key, substitutions, shouldTranslate());
467   }
468   
469   /*
470    * Javadoc copied from interface.
471    */

472   public String JavaDoc getString(String JavaDoc key, Object JavaDoc [] substitutions, boolean translate)
473   {
474     return MessageFormat.format(getString(key, translate), substitutions);
475   }
476
477   /*
478    * Javadoc copied from interface.
479    */

480   public void log(Object JavaDoc logEntry)
481   {
482     Logger logger = getPluginLogger();
483     if (logger == null)
484     {
485       if (logEntry instanceof Throwable JavaDoc)
486       {
487         ((Throwable JavaDoc)logEntry).printStackTrace(System.err);
488       }
489       else
490       {
491         System.err.println(logEntry);
492       }
493     }
494     else
495     {
496       logger.log(logEntry);
497     }
498   }
499
500   /**
501    * The actual implementation of an Eclipse <b>Plugin</b>.
502    */

503   public static abstract class EclipsePlugin extends Plugin implements ResourceLocator, Logger
504   {
505     protected ResourceBundle JavaDoc resourceBundle;
506     protected ResourceBundle JavaDoc untranslatedResourceBundle;
507     
508     /**
509      * Creates an instance.
510      */

511     public EclipsePlugin()
512     {
513       super();
514     }
515
516     /**
517      * Creates an instance.
518      * @param descriptor the description of the plugin.
519      * @deprecated
520      */

521     public EclipsePlugin(org.eclipse.core.runtime.IPluginDescriptor descriptor)
522     {
523       super(descriptor);
524     }
525
526     /**
527      * Return the plugin ID.
528      */

529     public String JavaDoc getSymbolicName()
530     {
531       return getBundle().getSymbolicName();
532     }
533
534     /*
535      * Javadoc copied from interface.
536      */

537     public URL JavaDoc getBaseURL()
538     {
539       return getBundle().getEntry("/");
540     }
541
542     /*
543      * Javadoc copied from interface.
544      */

545     public Object JavaDoc getImage(String JavaDoc key)
546     {
547       try
548       {
549         return doGetImage(key);
550       }
551       catch (MalformedURLException JavaDoc exception)
552       {
553         throw new WrappedException(exception);
554       }
555       catch (IOException JavaDoc exception)
556       {
557         throw
558           new MissingResourceException JavaDoc
559             (CommonPlugin.INSTANCE.getString("_UI_StringResourceNotFound_exception", new Object JavaDoc [] { key }),
560              getClass().getName(),
561              key);
562       }
563     }
564
565     /**
566      * Does the work of fetching the image associated with the key.
567      * It ensures that the image exists.
568      * @param key the key of the image to fetch.
569      * @exception IOException if an image doesn't exist.
570      * @return the description of the image associated with the key.
571      */

572     protected Object JavaDoc doGetImage(String JavaDoc key) throws IOException JavaDoc
573     {
574       URL JavaDoc url = new URL JavaDoc(getBaseURL() + "icons/" + key + ".gif");
575       InputStream JavaDoc inputStream = url.openStream();
576       inputStream.close();
577       return url;
578     }
579
580     /*
581      * Javadoc copied from interface.
582      */

583     public String JavaDoc getString(String JavaDoc key)
584     {
585       return getString(key, true);
586     }
587     
588     /*
589      * Javadoc copied from interface.
590      */

591     public String JavaDoc getString(String JavaDoc key, boolean translate)
592     {
593       ResourceBundle JavaDoc bundle = translate ? resourceBundle : untranslatedResourceBundle;
594       if (bundle == null)
595       {
596         if (translate)
597         {
598            bundle = resourceBundle = Platform.getResourceBundle(getBundle());
599         }
600         else
601         {
602           String JavaDoc resourceName = getBaseURL().toString() + "plugin.properties";
603           try
604           {
605             InputStream JavaDoc inputStream = new URL JavaDoc(resourceName).openStream();
606             bundle = untranslatedResourceBundle = new PropertyResourceBundle JavaDoc(inputStream);
607             inputStream.close();
608           }
609           catch (IOException JavaDoc ioException)
610           {
611             throw new MissingResourceException JavaDoc("Missing properties: " + resourceName, getClass().getName(), "plugin.properties");
612           }
613         }
614       }
615       return bundle.getString(key);
616     }
617
618     /*
619      * Javadoc copied from interface.
620      */

621     public String JavaDoc getString(String JavaDoc key, Object JavaDoc [] substitutions)
622     {
623       return getString(key, substitutions, true);
624     }
625
626     /*
627      * Javadoc copied from interface.
628      */

629     public String JavaDoc getString(String JavaDoc key, Object JavaDoc [] substitutions, boolean translate)
630     {
631       return MessageFormat.format(getString(key, translate), substitutions);
632     }
633
634     /*
635      * Javadoc copied from interface.
636      */

637     public void log(Object JavaDoc logEntry)
638     {
639       IStatus status;
640       if (logEntry instanceof IStatus)
641       {
642         status = (IStatus)logEntry;
643         getLog().log(status);
644       }
645       else
646       {
647         if (logEntry == null)
648         {
649           logEntry = new RuntimeException JavaDoc(getString("_UI_NullLogEntry_exception")).fillInStackTrace();
650         }
651
652         if (logEntry instanceof Throwable JavaDoc)
653         {
654           Throwable JavaDoc throwable = (Throwable JavaDoc)logEntry;
655
656           // System.err.println("Logged throwable: --------------------");
657
// throwable.printStackTrace();
658

659           String JavaDoc message = throwable.getLocalizedMessage();
660           if (message == null)
661           {
662             message = "";
663           }
664
665           getLog().log(new Status(IStatus.WARNING, getBundle().getSymbolicName(), 0, message, throwable));
666         }
667         else
668         {
669           // System.err.println("Logged throwable: --------------------");
670
// throwable.printStackTrace();
671

672           getLog().log (new Status (IStatus.WARNING, getBundle().getSymbolicName(), 0, logEntry.toString(), null));
673         }
674       }
675     }
676   }
677 }
678
Popular Tags