KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > iapi > tools > i18n > LocalizedResource


1 /*
2
3    Derby - Class org.apache.derby.iapi.tools.i18n.LocalizedResource
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to You under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21 package org.apache.derby.iapi.tools.i18n;
22
23 import java.io.InputStream JavaDoc;
24 import java.io.OutputStream JavaDoc;
25 import java.io.UnsupportedEncodingException JavaDoc;
26
27 import java.util.ResourceBundle JavaDoc;
28 import java.util.Date JavaDoc;
29 import java.util.Locale JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31
32 import java.text.MessageFormat JavaDoc;
33 import java.text.NumberFormat JavaDoc;
34 import java.text.DecimalFormat JavaDoc;
35 import java.text.DateFormat JavaDoc;
36 import java.text.ParseException JavaDoc;
37 import java.text.FieldPosition JavaDoc;
38
39 import java.sql.Timestamp JavaDoc;
40 import java.sql.ResultSet JavaDoc;
41 import java.sql.ResultSetMetaData JavaDoc;
42 import java.sql.SQLException JavaDoc;
43 import java.sql.Types JavaDoc;
44
45
46 public final class LocalizedResource implements java.security.PrivilegedAction JavaDoc {
47
48     private static final boolean HAVE_BIG_DECIMAL;
49     
50     static {
51         boolean haveBigDecimal;
52         try {
53             Class.forName("java.math.BigDecimal");
54             haveBigDecimal = true;
55         } catch (Throwable JavaDoc t) {
56             haveBigDecimal = false;
57         }
58         HAVE_BIG_DECIMAL = haveBigDecimal;
59     }
60     
61     private ResourceBundle JavaDoc res;
62     private Locale JavaDoc locale;
63     private String JavaDoc encode;
64     private final static String JavaDoc MESSAGE_FILE = "org.apache.derby.loc.toolsmessages";
65     private final static String JavaDoc ENV_CODESET = "derby.ui.codeset";
66     private final static String JavaDoc ENV_LOCALE = "derby.ui.locale";
67     private String JavaDoc messageFileName;
68     private String JavaDoc resourceKey;
69     private LocalizedOutput out;
70     private LocalizedInput in;
71     private boolean enableLocalized;
72     private boolean unicodeEscape;
73     private static LocalizedResource local;
74     private int dateSize;
75     private int timeSize;
76     private int timestampSize;
77     private DateFormat JavaDoc formatDate;
78     private DateFormat JavaDoc formatTime;
79     private DateFormat JavaDoc formatTimestamp;
80     private NumberFormat JavaDoc formatNumber;
81     private DecimalFormat JavaDoc formatDecimal;
82     public LocalizedResource(){
83         init();
84     }
85     public LocalizedResource(String JavaDoc encStr, String JavaDoc locStr, String JavaDoc msgF){
86         init(encStr,locStr,msgF);
87     }
88     public static LocalizedResource getInstance(){
89         if (local == null){
90             local = new LocalizedResource();
91         }
92         return local;
93     }
94     public void init(){
95         init(null,null,null);
96     }
97     public void init (String JavaDoc encStr, String JavaDoc locStr, String JavaDoc msgF){
98         if (encStr != null){
99             encode = encStr;
100         }
101         //then get encoding string from environment
102
if (encode == null) {
103             String JavaDoc eEncode = getEnvProperty(ENV_CODESET);
104             if ( eEncode != null ){
105                 encode = eEncode;
106             }
107         }
108         
109         // If null at this point then the default encoding
110
// will be always used.
111

112         //get locale string from the caller first
113
locale = getNewLocale(locStr);
114
115         //if null, get locale again from the environment variable
116
if (locale==null) {
117             String JavaDoc s = getEnvProperty(ENV_LOCALE);
118             locale = getNewLocale(s);
119         }
120         //get the default locale if forced
121
if (locale==null){
122             locale = Locale.getDefault();
123         }
124         if (msgF != null) {
125             messageFileName = msgF;
126         }
127         else {
128             messageFileName = MESSAGE_FILE;
129         }
130         //create default in/out
131
out = getNewOutput(System.out);
132         in = getNewInput(System.in);
133
134         //for faster code: get the format objs
135
if (enableLocalized && locale != null){
136             formatDecimal = (DecimalFormat JavaDoc)DecimalFormat.getInstance(locale);
137             formatNumber = NumberFormat.getInstance(locale);
138             formatDate = DateFormat.getDateInstance(DateFormat.LONG,locale);
139             formatTime = DateFormat.getTimeInstance(DateFormat.LONG,locale);
140             formatTimestamp = DateFormat.getDateTimeInstance(DateFormat.LONG,
141                                                     DateFormat.LONG, locale);
142         }
143         else {
144             formatDecimal = (DecimalFormat JavaDoc)DecimalFormat.getInstance();
145             formatNumber = NumberFormat.getInstance();
146             formatDate = DateFormat.getDateInstance(DateFormat.LONG);
147             formatTime = DateFormat.getTimeInstance(DateFormat.LONG);
148             formatTimestamp = DateFormat.getDateTimeInstance(DateFormat.LONG,
149                                                     DateFormat.LONG);
150         }
151         //initialize display sizes for columns
152
initMaxSizes2();
153     }
154     //get the message file resource according to the locale
155
//fall back to English message file if locale message file is not found
156
private void setResource(){
157         if (res != null){
158             return;
159         }
160         if ( locale == null || locale.toString().equals("none") ){
161             res = ResourceBundle.getBundle(MESSAGE_FILE);
162         }
163         else
164         try {
165             res = ResourceBundle.getBundle(messageFileName,locale);
166         }
167         catch(java.util.MissingResourceException JavaDoc e){
168             res = ResourceBundle.getBundle(messageFileName,Locale.ENGLISH);
169         }
170     }
171     private void initMaxSizes2(){
172         dateSize = 0;
173         timeSize = 0;
174         timestampSize = 0;
175
176         int len;
177
178         // check the date & timestamp max length
179
// 3900/01/28 !! original devloper thought they were getting 2000/01/28
180
Date JavaDoc d = new Date JavaDoc(60907276800000L);
181         Timestamp JavaDoc t = new Timestamp JavaDoc(d.getTime());
182         for(int month = 0 ; month <=11 ; month++, d.setTime(d.getTime() + (30L * 24L * 60L * 60L * 1000L))) {
183             len=getDateAsString(d).length();
184
185             if(len > dateSize ) {
186                 dateSize=len;
187             }
188
189             t.setTime(d.getTime() + ((((21L * 60L) + 59L) * 60L) + 59L));
190             len=getTimestampAsString(t).length();
191
192             if(len > timestampSize) {
193                 timestampSize=len;
194             }
195         }
196
197         // set the time max length
198
// minimum of 18 because the old buggy code always used 18
199
len = 18;
200         for (int hour = 0 ; hour < 24; hour++) {
201
202             long secs = (hour * 3600L) + (59 * 60L) + 59L;
203
204             long ms = secs * 1000L;
205
206             Date JavaDoc td = new Date JavaDoc(ms);
207
208             String JavaDoc fd = formatTime.format(td);
209
210             if (fd.length() > len)
211                 len = fd.length();
212         }
213         timeSize=len;
214
215     }
216
217     public LocalizedInput getNewInput(InputStream JavaDoc i) {
218         try {
219             if (encode != null)
220                 return new LocalizedInput(i,encode);
221         }
222         catch (UnsupportedEncodingException JavaDoc e){
223             
224         }
225         return new LocalizedInput(i);
226     }
227
228     public LocalizedInput getNewEncodedInput(InputStream JavaDoc i, String JavaDoc encoding) {
229         try {
230               return new LocalizedInput(i,encoding);
231         }
232         catch (UnsupportedEncodingException JavaDoc e){
233             
234         }
235         return new LocalizedInput(i);
236         }
237
238     public LocalizedOutput getNewOutput(OutputStream JavaDoc o){
239         try {
240             if (encode != null)
241                 return new LocalizedOutput(o,encode);
242         }
243         catch(UnsupportedEncodingException JavaDoc e){
244         }
245         return new LocalizedOutput(o);
246     }
247     /**
248      * Get a new LocalizedOutput with the given encoding.
249      * @throws UnsupportedEncodingException
250      */

251     public LocalizedOutput getNewEncodedOutput(OutputStream JavaDoc o,
252             String JavaDoc encoding) throws UnsupportedEncodingException JavaDoc{
253         return new LocalizedOutput(o, encoding);
254     }
255     public String JavaDoc getTextMessage(String JavaDoc key ) {
256         if ( res == null){
257             setResource();
258         }
259         String JavaDoc s = key;
260         try{
261             s = res.getString(key);
262         } catch (Exception JavaDoc e) {
263             s = key;
264         }
265         //System.out.println(local.toString());
266
//System.out.println("GetKey:"+key+"="+s);
267
return s;
268     }
269     public String JavaDoc getTextMessage(String JavaDoc key, Object JavaDoc o){
270             Object JavaDoc [] att=new Object JavaDoc[] {o};
271             return getTextMessage(key,att);
272     }
273     public String JavaDoc getTextMessage(String JavaDoc key, Object JavaDoc o1, Object JavaDoc o2){
274             Object JavaDoc [] att=new Object JavaDoc[] {o1,o2};
275             return getTextMessage(key,att);
276     }
277     public String JavaDoc getTextMessage(String JavaDoc key, Object JavaDoc o1, Object JavaDoc o2, Object JavaDoc o3){
278             Object JavaDoc [] att=new Object JavaDoc[] {o1,o2,o3};
279             return getTextMessage(key,att);
280     }
281     public String JavaDoc getTextMessage(String JavaDoc key, Object JavaDoc o1, Object JavaDoc o2, Object JavaDoc o3, Object JavaDoc o4){
282             Object JavaDoc [] att=new Object JavaDoc[] {o1,o2,o3,o4};
283             return getTextMessage(key,att);
284     }
285     private Locale JavaDoc getNewLocale(String JavaDoc locStr){
286             String JavaDoc l="", r="", v="";
287             StringTokenizer JavaDoc st;
288             if (locStr==null) {
289                 return null;
290             }
291             st=new StringTokenizer JavaDoc(locStr, "_");
292             try {
293                 l=st.nextToken();
294                 if(st.hasMoreTokens()==true)
295                     r=st.nextToken();
296                 if(st.hasMoreTokens()==true)
297                     v=st.nextToken();
298                 return new Locale JavaDoc(l,r,v);
299             } catch (Exception JavaDoc e) {
300                 return null;
301             }
302     }
303     public String JavaDoc getTextMessage(String JavaDoc key, Object JavaDoc [] objectArr) {
304         if (res == null){
305             setResource();
306         }
307             try{
308                 return MessageFormat.format(res.getString(key), objectArr);
309             } catch (Exception JavaDoc e) {
310                     String JavaDoc tmpFormat = key;
311                     for (int i=0; i<objectArr.length; i++)
312                         tmpFormat = tmpFormat + ", <{" + (i) + "}>";
313                     return MessageFormat.format(tmpFormat, objectArr);
314             }
315     }
316     public String JavaDoc getLocalizedString(ResultSet JavaDoc rs,
317                                         ResultSetMetaData JavaDoc rsm,
318                                         int columnNumber) throws SQLException JavaDoc{
319             if (!enableLocalized){
320                 return rs.getString(columnNumber);
321             }
322             int type = rsm.getColumnType(columnNumber);
323             if ( type == Types.DATE ) {
324                 return getDateAsString(rs.getDate(columnNumber));
325             }
326             else if ( type == Types.INTEGER || type == Types.SMALLINT ||
327                     type == Types.BIGINT || type == Types.TINYINT ) {
328                 return getNumberAsString(rs.getLong(columnNumber));
329             }
330             else if (type == Types.REAL || type == Types.FLOAT ||
331                     type == Types.DOUBLE ) {
332                 return getNumberAsString(rs.getDouble(columnNumber));
333             }
334             else if (HAVE_BIG_DECIMAL && (type == Types.NUMERIC || type == Types.DECIMAL)) {
335                 return getNumberAsString(rs.getBigDecimal(columnNumber,
336                                             rsm.getScale(columnNumber)));
337             }
338             else if (type == Types.TIME ) {
339                 return getTimeAsString(rs.getTime(columnNumber));
340             }
341             else if (type == Types.TIMESTAMP ) {
342                 return getTimestampAsString(rs.getTimestamp(columnNumber));
343             }
344             return rs.getString(columnNumber);
345         }
346
347     public String JavaDoc getDateAsString(Date JavaDoc d){
348         if (!enableLocalized){
349             return d.toString();
350         }
351         return formatDate.format(d);
352     }
353     public String JavaDoc getTimeAsString(Date JavaDoc t){
354         if (!enableLocalized){
355             return t.toString();
356         }
357         return formatTime.format(t, new StringBuffer JavaDoc(),
358                                       new java.text.FieldPosition JavaDoc(0)).toString();
359     }
360     public String JavaDoc getNumberAsString(int o){
361         if (enableLocalized){
362             return formatNumber.format(o);
363         }
364         else {
365             return String.valueOf(o);
366         }
367     }
368     public String JavaDoc getNumberAsString(long o){
369         if (enableLocalized){
370             return formatNumber.format(o);
371         }
372         else{
373             return String.valueOf(o);
374         }
375     }
376     public String JavaDoc getNumberAsString(Object JavaDoc o){
377         if (enableLocalized){
378             return formatNumber.format(o, new StringBuffer JavaDoc(),
379                                         new FieldPosition JavaDoc(0)).toString();
380         }
381         else {
382             return o.toString();
383         }
384     }
385     public String JavaDoc getNumberAsString(double o){
386         if (!enableLocalized) {
387             return String.valueOf(o);
388         }
389         return formatDecimal.format(o);
390     }
391     public String JavaDoc getTimestampAsString(Timestamp JavaDoc t){
392         if (!enableLocalized){
393             return t.toString();
394         }
395         return formatTime.format(t, new StringBuffer JavaDoc(),
396                                     new java.text.FieldPosition JavaDoc(0)).toString();
397     }
398     public int getColumnDisplaySize(ResultSetMetaData JavaDoc rsm,
399                                         int columnNumber) throws SQLException JavaDoc{
400           if (!enableLocalized){
401                 return rsm.getColumnDisplaySize(columnNumber);
402           }
403           int type = rsm.getColumnType(columnNumber);
404           if (type == Types.DATE)
405                     return dateSize;
406           if (type == Types.TIME)
407                     return timeSize;
408           if (type == Types.TIMESTAMP)
409                     return timestampSize;
410           return rsm.getColumnDisplaySize(columnNumber);
411     }
412     public String JavaDoc getStringFromDate(String JavaDoc dateStr)
413         throws ParseException JavaDoc{
414             if (!enableLocalized){
415                 return dateStr;
416             }
417             Date JavaDoc d = formatDate.parse(dateStr);
418             return new java.sql.Date JavaDoc(d.getTime()).toString();
419     }
420     public String JavaDoc getStringFromTime(String JavaDoc timeStr)
421         throws ParseException JavaDoc{
422             if (!enableLocalized){
423                 return timeStr;
424             }
425             Date JavaDoc t = formatTime.parse(timeStr);
426             return new java.sql.Time JavaDoc(t.getTime()).toString();
427     }
428     public String JavaDoc getStringFromValue(String JavaDoc val)
429         throws ParseException JavaDoc{
430             if (!enableLocalized){
431                 return val;
432             }
433             return formatNumber.parse(val).toString();
434     }
435     public String JavaDoc getStringFromTimestamp(String JavaDoc timestampStr)
436         throws ParseException JavaDoc{
437             if (!enableLocalized){
438                 return timestampStr;
439             }
440             Date JavaDoc ts = formatTimestamp.parse(timestampStr);
441             return new java.sql.Timestamp JavaDoc(ts.getTime()).toString();
442     }
443     public Locale JavaDoc getLocale(){
444             return locale;
445     }
446
447     private final synchronized String JavaDoc getEnvProperty(String JavaDoc key) {
448         String JavaDoc s;
449          try
450           {
451                 resourceKey = key;
452                 s = (String JavaDoc) java.security.AccessController.doPrivileged(this);
453         }
454         catch (SecurityException JavaDoc se) {
455             s = null;
456         }
457         //System.out.println("{"+resourceKey+"="+s+"}");
458
return s;
459     }
460     public final Object JavaDoc run() {
461         String JavaDoc s = System.getProperty(resourceKey);
462         return s;
463     }
464     public static boolean enableLocalization(boolean mode) {
465         getInstance().enableLocalized = mode;
466         //re-initialized locale
467
getInstance().init();
468         return mode;
469     }
470     public boolean isLocalized(){
471         return getInstance().enableLocalized;
472     }
473     public static String JavaDoc getMessage(String JavaDoc key){
474         return getInstance().getTextMessage(key);
475     }
476     public static String JavaDoc getMessage(String JavaDoc key, Object JavaDoc o1){
477         return getInstance().getTextMessage(key,o1);
478     }
479     public static String JavaDoc getMessage(String JavaDoc key, Object JavaDoc o1, Object JavaDoc o2){
480         return getInstance().getTextMessage(key,o1,o2);
481     }
482     public static String JavaDoc getMessage(String JavaDoc key, Object JavaDoc o1, Object JavaDoc o2, Object JavaDoc o3){
483         return getInstance().getTextMessage(key,o1,o2,o3);
484     }
485     public static String JavaDoc getMessage(String JavaDoc key, Object JavaDoc o1, Object JavaDoc o2, Object JavaDoc o3, Object JavaDoc o4){
486         return getInstance().getTextMessage(key,o1,o2,o3,o4);
487     }
488     public static LocalizedOutput OutputWriter(){
489         return getInstance().out;
490     }
491     public static LocalizedInput InputReader(){
492         return getInstance().in;
493     }
494     public static String JavaDoc getNumber(long o){
495         return getInstance().getNumberAsString(o);
496     }
497     public static String JavaDoc getNumber(int o){
498         return getInstance().getNumberAsString(o);
499     }
500     public static void setUnicodeEscape(boolean u){
501         getInstance().unicodeEscape = u;
502     }
503     public static boolean getUnicodeEscape(){
504         return getInstance().unicodeEscape;
505     }
506     public String JavaDoc toString(){
507         String JavaDoc s = "toString(){\n" +
508             "locale=" + (locale==null?"null":locale.toString()) + "\n" +
509             "encode=" + encode + "\n" +
510             "messageFile=" + messageFileName + "\n" +
511             "resourceKey=" + resourceKey + "\n" +
512             "enableLocalized=" + enableLocalized + " \n" +
513             "unicodeEscape=" + unicodeEscape + "\n" +
514             "dateSize=" + dateSize + "\n" +
515             "timeSize=" + timeSize + "\n" +
516             "timestampSize="+timestampSize+ "\n}";
517             return s;
518     }
519 }
520
Popular Tags