KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > updater > Localization


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.updater;
21
22 import java.util.*;
23 import java.io.*;
24 import java.net.MalformedURLException JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.net.URLClassLoader JavaDoc;
27
28 class Localization {
29
30     private static final String JavaDoc FILE_SEPARATOR = System.getProperty ("file.separator"); // NOI18N
31
private static final String JavaDoc LOCALE_DIR = "modules" + FILE_SEPARATOR + "ext" + FILE_SEPARATOR + "locale"; // NOI18N
32
private static final String JavaDoc BUNDLE_NAME = "org/netbeans/updater/Bundle"; // NOI18N
33
private static final String JavaDoc BUNDLE_EXT = ".properties"; // NOI18N
34
private static final String JavaDoc UPDATER_JAR = "updater"; // NOI18N
35
private static final String JavaDoc UPDATER_JAR_EXT = ".jar"; // NOI18N
36

37     private static ClassLoader JavaDoc brandedLoader = null;
38     
39     private static String JavaDoc brandingToken = null;
40     
41     private static HashMap bundleCache = new HashMap();
42
43     public static String JavaDoc getBranding() {
44         if (brandingToken != null) {
45             init();
46         }
47         return brandingToken;
48     }
49     
50     public static String JavaDoc getBrandedString( String JavaDoc key ) {
51         init(); // When not initialized do so
52

53         // Let's try to find a bundle
54
for( LocaleIterator li = new LocaleIterator( Locale.getDefault() ); li.hasNext(); ) {
55             try {
56                 ResourceBundle bundle = findBrandedBundle( (String JavaDoc)li.next() );
57                 
58                 if ( bundle != null ) {
59                     // So we have the bundle, now we need the string
60
String JavaDoc brandedString = bundle.getString( key );
61                     if ( brandedString != null ) {
62                         return brandedString; // We even found the string
63
}
64                     // Continue
65
}
66             }
67             catch ( java.util.MissingResourceException JavaDoc e ) {
68                 // No string, no problem, let's try other one
69
}
70         }
71         return null;
72     }
73     
74     private static ResourceBundle findBrandedBundle( String JavaDoc loc ) {
75         
76         ResourceBundle bundle = (ResourceBundle)bundleCache.get( loc ); // Maybe is in cache
77
if ( bundle != null ) {
78             return bundle;
79         }
80         
81         // Was not in cache
82

83         
84         InputStream is = brandedLoader.getResourceAsStream( BUNDLE_NAME + loc + BUNDLE_EXT );
85         if (is != null) {
86             try {
87                 try {
88                     Properties p = new Properties();
89                     p.load(is);
90                     bundle= new PBundle( p, new Locale( "" ) );
91                     bundleCache.put( loc, bundle );
92                     return bundle;
93                 } finally {
94                     is.close();
95                 }
96             } catch (IOException e) {
97                 return null;
98             }
99         }
100                 
101         return null;
102     }
103     
104     
105     public static URL JavaDoc getBrandedResource( String JavaDoc base, String JavaDoc ext ) {
106         init(); // When not initialized do so
107

108         // Let's try all the possibilities
109
for( LocaleIterator li = new LocaleIterator( Locale.getDefault() ); li.hasNext(); ) {
110             URL JavaDoc url = brandedLoader.getResource( base + li.next() + ext );
111             if ( url != null ) {
112                 return url;
113             }
114         }
115         
116         return null;
117     }
118     
119     
120     public static InputStream getBrandedResourceAsStream( String JavaDoc base, String JavaDoc ext ) {
121         init(); // When not initialized do so
122

123         // Let's try all the possibilities
124
for( LocaleIterator li = new LocaleIterator( Locale.getDefault() ); li.hasNext(); ) {
125             InputStream is = brandedLoader.getResourceAsStream( base + li.next() + ext );
126             if ( is != null ) {
127                 return is;
128             }
129         }
130         
131         return null;
132     }
133     
134     public static void setBranding (String JavaDoc branding) {
135         brandingToken = branding;
136     }
137     
138     // Private methods ---------------------------------------------------------
139
private static synchronized void init() {
140         if (brandingToken == null) {
141             // Initialize the branding token
142
brandingToken = initBranding();
143         }
144         if (brandedLoader == null) {
145             
146             // Fallback to default class loader
147
brandedLoader = Localization.class.getClassLoader();
148             
149             // Try to find some localized jars and store the URLS
150
List locJarURLs = new ArrayList();
151                         
152             for( LocaleIterator li = new LocaleIterator( Locale.getDefault() ); li.hasNext(); ) {
153                 String JavaDoc localeName = li.next().toString ();
154                 // loop for clusters
155
Iterator it = UpdateTracking.clusters (true).iterator ();
156                 while (it.hasNext ()) {
157                     File cluster = (File)it.next ();
158                     File locJar = new File( cluster.getPath () + FILE_SEPARATOR + LOCALE_DIR + FILE_SEPARATOR + UPDATER_JAR + localeName + UPDATER_JAR_EXT );
159                     if ( locJar.exists() ) { // File exists
160
try {
161                             locJarURLs.add( locJar.toURI().toURL() ); // Convert to URL
162
}
163                         catch ( MalformedURLException JavaDoc e ) {
164                             // dont use and ignore
165
}
166                     }
167                 }
168             }
169             
170             if ( !locJarURLs.isEmpty() ) { // we've found some localization jars
171
// Make an array of URLs
172
URL JavaDoc urls[] = new URL JavaDoc[ locJarURLs.size() ];
173                 locJarURLs.toArray( urls );
174
175                 // Create the new classLoader
176
brandedLoader = new URLClassLoader JavaDoc( urls, brandedLoader );
177             }
178             
179         }
180     }
181     
182     /** Returns current branding
183      */

184     private static String JavaDoc initBranding() {
185         BufferedReader in = null;
186         String JavaDoc s = null;
187         try {
188             File brandf = new File (org.netbeans.updater.UpdateTracking.getPlatformDir(),
189                     "lib" + FILE_SEPARATOR + "branding"); // NOI18N
190
in = new BufferedReader(new FileReader(brandf));
191             if (in.ready()) {
192                 System.out.println("Warning - It's obsolete. Use --branding <branding> instead 'branding' file.");
193                 s = in.readLine();
194             }
195         }
196         catch (IOException e) {
197         }
198         finally {
199             if (in != null) try { in.close(); } catch (IOException e) { /* ignore */ };
200         }
201         return s;
202     }
203     
204     /**
205      * =============================================================================
206      * N O T I C E
207      * -----------------------------------------------------------------------------
208      * This class was copyied from NbBundle. The reason is that the updater must not
209      * use any NetBeans class in order to be able to update them.
210      * -----------------------------------------------------------------------------
211      *
212      * This class (enumeration) gives all localized sufixes using nextElement
213      * method. It goes through given Locale and continues through Locale.getDefault()
214      * Example 1:
215      * Locale.getDefault().toString() -> "_en_US"
216      * you call new LocaleIterator(new Locale("cs", "CZ"));
217      * ==> You will gets: "_cs_CZ", "_cs", "", "_en_US", "_en"
218      *
219      * Example 2:
220      * Locale.getDefault().toString() -> "_cs_CZ"
221      * you call new LocaleIterator(new Locale("cs", "CZ"));
222      * ==> You will gets: "_cs_CZ", "_cs", ""
223      *
224      * If there is a branding token in effect, you will get it too as an extra
225      * prefix, taking precedence, e.g. for the token "f4jce":
226      *
227      * "_f4jce_cs_CZ", "_f4jce_cs", "_f4jce", "_f4jce_en_US", "_f4jce_en", "_cs_CZ", "_cs", "", "_en_US", "_en"
228      *
229      * Branding tokens with underscores are broken apart naturally: so e.g.
230      * branding "f4j_ce" looks first for "f4j_ce" branding, then "f4j" branding, then none.
231      */

232     private static class LocaleIterator extends Object JavaDoc implements Iterator {
233         /** this flag means, if default locale is in progress */
234         private boolean defaultInProgress = false;
235
236         /** this flag means, if empty sufix was exported yet */
237         private boolean empty = false;
238
239         /** current locale, and initial locale */
240         private Locale locale, initLocale;
241
242         /** current sufix which will be returned in next calling nextElement */
243         private String JavaDoc current;
244
245         /** the branding string in use */
246         private String JavaDoc branding;
247
248         /** Creates new LocaleIterator for given locale.
249         * @param locale given Locale
250         */

251         public LocaleIterator (Locale locale) {
252             this.locale = this.initLocale = locale;
253             if (locale.equals(Locale.getDefault())) {
254                 defaultInProgress = true;
255             }
256             current = '_' + locale.toString();
257             if (brandingToken == null)
258                 branding = null;
259             else
260                 branding = "_" + brandingToken; // NOI18N
261
//System.err.println("Constructed: " + this);
262
}
263
264         /** @return next sufix.
265         * @exception NoSuchElementException if there is no more locale sufix.
266         */

267         public Object JavaDoc next () throws NoSuchElementException {
268             if (current == null)
269                 throw new NoSuchElementException();
270
271             final String JavaDoc ret;
272             if (branding == null) {
273                 ret = current;
274             } else {
275                 ret = branding + current;
276             }
277             int lastUnderbar = current.lastIndexOf('_');
278             if (lastUnderbar == 0) {
279                 if (empty)
280                     reset ();
281                 else {
282                     current = ""; // NOI18N
283
empty = true;
284                 }
285             }
286             else {
287                 if (lastUnderbar == -1) {
288                     if (defaultInProgress)
289                         reset ();
290                     else {
291                         // [PENDING] stuff with trying the default locale
292
// after the real one does not actually seem to work...
293
locale = Locale.getDefault();
294                         current = '_' + locale.toString();
295                         defaultInProgress = true;
296                     }
297                 }
298                 else {
299                     current = current.substring(0, lastUnderbar);
300                 }
301             }
302             //System.err.println("Returning: `" + ret + "' from: " + this);
303
return ret;
304         }
305
306         /** Finish a series.
307          * If there was a branding prefix, restart without that prefix
308          * (or with a shorter prefix); else finish.
309          */

310         private void reset () {
311             if (branding != null) {
312                 current = '_' + initLocale.toString ();
313                 int idx = branding.lastIndexOf ('_');
314                 if (idx == 0)
315                     branding = null;
316                 else
317                     branding = branding.substring (0, idx);
318                 empty = false;
319             } else {
320                 current = null;
321             }
322         }
323
324         /** Tests if there is any sufix.*/
325         public boolean hasNext () {
326             return (current != null);
327         }
328
329         public void remove () throws UnsupportedOperationException JavaDoc {
330             throw new UnsupportedOperationException JavaDoc ();
331         }
332
333     } // end of LocaleIterator
334

335     /**
336      * =============================================================================
337      * N O T I C E
338      * -----------------------------------------------------------------------------
339      * YASC - Yet Another Stolen Class
340      * -----------------------------------------------------------------------------
341      * A resource bundle based on <samp>.properties</samp> files (or any map).
342      */

343     private static final class PBundle extends ResourceBundle {
344         private final Map m; // Map<String,String>
345
private final Locale locale;
346         /**
347          * Create a new bundle based on a map.
348          * @param m a map from resources keys to values (typically both strings)
349          * @param locale the locale it represents <em>(informational)</em>
350          */

351         public PBundle(Map m, Locale locale) {
352             this.m = m;
353             this.locale = locale;
354         }
355         public Enumeration getKeys() {
356             return Collections.enumeration(m.keySet());
357         }
358         protected Object JavaDoc handleGetObject(String JavaDoc key) {
359             return m.get(key);
360         }
361         public Locale getLocale() {
362             return locale;
363         }
364     }
365     
366 }
Popular Tags