KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > impl > tools > sysinfo > Main


1 /*
2
3    Derby - Class org.apache.derby.impl.tools.sysinfo.Main
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
22 package org.apache.derby.impl.tools.sysinfo;
23
24 import java.security.AccessController JavaDoc;
25 import java.security.PrivilegedAction JavaDoc;
26 import java.util.Locale JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.UnsupportedEncodingException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.util.Properties JavaDoc;
31 import java.io.BufferedReader JavaDoc;
32 import java.io.InputStreamReader JavaDoc;
33 import java.util.Locale JavaDoc;
34 import java.util.MissingResourceException JavaDoc;
35 import java.util.ResourceBundle JavaDoc;
36 import java.util.StringTokenizer JavaDoc;
37 import java.io.File JavaDoc;
38 import java.util.zip.ZipFile JavaDoc;
39 import java.io.IOException JavaDoc;
40 import java.util.zip.ZipEntry JavaDoc;
41 import java.io.FileInputStream JavaDoc;
42 import java.util.Vector JavaDoc;
43 import java.io.InputStream JavaDoc;
44 import java.lang.reflect.Method JavaDoc;
45 import java.net.URL JavaDoc;
46 import java.net.URLDecoder JavaDoc;
47 import java.security.ProtectionDomain JavaDoc;
48 import java.security.CodeSource JavaDoc;
49 import java.security.AccessController JavaDoc;
50
51 import org.apache.derby.iapi.services.info.PropertyNames;
52 import org.apache.derby.iapi.services.info.ProductVersionHolder;
53 import org.apache.derby.iapi.services.info.ProductGenusNames;
54 import org.apache.derby.iapi.error.StandardException;
55
56 import org.apache.derby.iapi.tools.i18n.*;
57
58
59 /**
60   <P>
61   Sysinfo reports values relevant to the current Derby configuration.
62
63   <P>
64   Sysinfo looks for properties files in org.apache.derby.info named after
65   the genus names in org.apache.derby.tools.sysinfo, and gets their location
66   using getResource. It also searches the classpath and attempts to load
67   the info properties files from the directory or jar locations on the
68   classpath, and eliminates any duplicated information. If no files
69   are found, or some other exception occurs, the
70   value returned will be that set for the key
71   SysInfo.failureTag, or be the value "<info unavailable>".
72
73   <P>
74   This class can be used to print out system information at the
75   command line by issuing the command:
76   <PRE>
77     java org.apache.derby.tools.sysinfo
78   </PRE>
79   Alternatively, you can use SysInfo within your program to display
80   Cloudscape information; a Cloudscape version string is returned by this Java code:
81   <PRE>
82     new Main().toString();
83   </PRE>
84
85  */

86
87
88 public final class Main {
89
90   /**
91     Application entry point for SysInfo. This will print out
92     the Cloudscape product information as well as a snapshot of
93     the System properties.
94   */

95   public static void main(String JavaDoc args[]) {
96         // adjust the application in accordance with derby.ui.locale and derby.ui.codeset
97
LocalizedResource.getInstance();
98
99         LocalizedOutput out;
100
101         //using AppStreamReader(extends InputStreamReader) for conversion into specific codeset
102

103         out = LocalizedResource.OutputWriter();
104
105        // because we're in a static method, we need to
106
// get our own instance variable
107
parseArgs (args);
108
109     if (cptester == true)
110     getClasspathInfo (args, out);
111     else
112     getMainInfo (out, setPause);
113
114   } // end of main (String args[])
115

116 public static void getMainInfo (java.io.PrintWriter JavaDoc aw, boolean pause) {
117
118     aw.println (javaSep);
119     reportJavaInfo (aw);
120     aw.println (jbmsSep);
121     reportDerby (aw);
122
123     aw.println (sep);
124
125     // Locales info
126
try {
127       reportLocales (aw);
128     }
129     catch (Exception JavaDoc e) {
130
131       aw.println (Main.getTextMessage ("SIF01.Q"));
132       aw.println (Main.getTextMessage ("SIF01.B"));
133     }
134
135
136     if (pause) {
137      pause();
138     }
139
140   } // end of getMainInfo (AppStreamWriter aw, boolean printLicense, boolean pause)
141

142
143   private static boolean setPause = false;
144
145   private static boolean setLicense = false;
146
147   private static boolean cptester = false;
148
149   private static void parseArgs (String JavaDoc args[]) {
150
151     if (args == null) {
152
153       return;
154     }
155
156
157     for (int i = 0; i < args.length; i++) {
158
159       if (args[i].equals ("-pause")) {
160
161         setPause = true;
162       }
163
164       if (args[i].equals ("-cp")) {
165
166         cptester=true;
167       }
168
169     } // end for
170

171   } // end of parseArgs (String args[])
172

173
174   /**
175     For the benefit of DOS box users, this method waits for input
176     before returning
177   */

178   private static void pause () {
179
180     try {
181
182       System.out.print (Main.getTextMessage ("SIF01.C"));
183       BufferedReader JavaDoc br = new BufferedReader JavaDoc (new InputStreamReader JavaDoc (System.in));
184       br.readLine ();
185     }
186     catch (IOException JavaDoc ioe) {
187
188       //just return
189
}
190
191   } // end of pause ()
192

193   /**
194     prints out the jbms info to the specified AppStreamWriter.
195     @param localAW the AppStreamWriter to use. If null, System.out is
196     used
197   */

198
199   private static void reportDerby (java.io.PrintWriter JavaDoc localAW) {
200
201       localAW.println("JRE - JDBC: " + org.apache.derby.iapi.services.info.JVMInfo.derbyVMLevel());
202
203       String JavaDoc classpath;
204
205       try {
206           classpath = System.getProperty("java.class.path");
207       }
208       catch (SecurityException JavaDoc se) {
209           localAW.println(
210               Main.getTextMessage ("SIF01.U", se.getMessage()));
211           classpath = null;
212       }
213
214     ZipInfoProperties zip[]= Main.getAllInfo (classpath);
215
216     if (zip != null) {
217
218       for (int i = 0; i < zip.length; i++) {
219
220         String JavaDoc thisInfo = "[" + zip[i].getLocation () + "] " +
221                                 zip[i].getVersionBuildInfo ();
222
223         localAW.println (thisInfo);
224       }
225     }
226
227     else {
228
229       localAW.println (Main.getTextMessage ("SIF01.D"));
230     }
231
232
233   } // end of reportDerby
234

235   /**
236     Writes out the relevant info about the Java environment to
237     the specified AppStreamWriter.
238
239     @param localAW The AppStreamWriter to write info out to. If this is
240     null, the info is written to System.out
241   */

242
243   private static void reportJavaInfo (java.io.PrintWriter JavaDoc localAW) {
244
245     
246
247     localAW.println (Main.getTextMessage ("SIF02.A",
248                                                            getJavaProperty ("java.version")));
249
250     localAW.println (Main.getTextMessage ("SIF02.B",
251                                                            getJavaProperty ("java.vendor")));
252
253     localAW.println (Main.getTextMessage ("SIF02.C",
254                                                            getJavaProperty ("java.home")));
255
256     localAW.println (Main.getTextMessage ("SIF02.D",
257                                                            getJavaProperty ("java.class.path")));
258
259     localAW.println (Main.getTextMessage ("SIF02.E",
260                                                            getJavaProperty ("os.name")));
261
262     localAW.println (Main.getTextMessage ("SIF02.F",
263                                                            getJavaProperty ("os.arch")));
264
265     localAW.println (Main.getTextMessage ("SIF02.G",
266                                                            getJavaProperty ("os.version")));
267
268     localAW.println (Main.getTextMessage ("SIF02.H",
269                                                            getJavaProperty ("user.name")));
270
271     localAW.println (Main.getTextMessage ("SIF02.I",
272                                                            getJavaProperty ("user.home")));
273
274     localAW.println (Main.getTextMessage ("SIF02.J",
275                                                            getJavaProperty ("user.dir")));
276
277     localAW.println("java.specification.name: " + getJavaProperty("java.specification.name"));
278     localAW.println("java.specification.version: " + getJavaProperty("java.specification.version"));
279
280
281   } // end of reportJavaInfo
282

283
284
285   /**
286     Return Java properties from java.lang.System. Will catch
287     SecurityExceptions and note them for displaying information.
288
289     @return the Java property value or a string capturing a
290     security exception.
291    */

292
293   private static String JavaDoc getJavaProperty (String JavaDoc whichProperty) {
294
295     String JavaDoc property;
296     String JavaDoc unavailable = Main.getTextMessage ("SIF01.H");
297
298     try {
299
300       property = System.getProperty (whichProperty, unavailable);
301       return property;
302     }
303     catch (SecurityException JavaDoc se) {
304
305       return Main.getTextMessage ("SIF01.I", se);
306     }
307
308   } // end of getJavaProperty (String whichProperty)
309

310
311
312   /**
313     for use by the main () method
314    */

315
316   private final static String JavaDoc sep = "------------------------------------------------------";
317   private final static String JavaDoc javaSep = Main.getTextMessage ("SIF01.L");
318
319   private final static String JavaDoc jbmsSep = Main.getTextMessage ("SIF01.M");
320
321   private final static String JavaDoc licSep = Main.getTextMessage ("SIF01.N");
322
323   private final static String JavaDoc locSep = Main.getTextMessage ("SIF01.P");
324
325   private final static String JavaDoc curLoc = Main.getTextMessage ("SIF01.T");
326
327   /**
328     The name of the failure tag in the information file.
329     The failure tag's value provides a default value if
330     any other properties are missing.
331    */

332   private final static String JavaDoc failureTag = Main.getTextMessage ("SIF01.J");
333
334   private static void getClasspathInfo (String JavaDoc args[], java.io.PrintWriter JavaDoc aw) {
335
336     Main.useMe (args, aw);
337   }
338
339
340
341
342   /**
343     Writes out information about the locales with the
344     product.
345
346     @param localAW the AppStreamWriter to which the info is written. If this
347     value is null, the info is written to System.out
348
349   */

350   private static void reportLocales (java.io.PrintWriter JavaDoc localAW) { // throws StandardException {
351

352     boolean cur_loc = true;
353
354     localAW.println (locSep);
355
356     // Read all the possible locales, and test for each one, if it loads.
357
// If so, then read the properties, and print them out.
358

359     Locale JavaDoc[] supportedLocales = Locale.getAvailableLocales();
360     String JavaDoc[] stringLocales = new String JavaDoc[supportedLocales.length];
361     for (int i = 0; i < supportedLocales.length; i++)
362     {
363         stringLocales[i] = supportedLocales[i].toString();
364     }
365     java.util.Arrays.sort(stringLocales);
366
367     Properties JavaDoc p = new Properties JavaDoc ();
368     for (int i = 0; i < stringLocales.length; i++) {
369
370       String JavaDoc localeResource =
371          "/org/apache/derby/info/locale_" + stringLocales[i] + ".properties";
372       
373       final Properties JavaDoc finalp = p;
374       final String JavaDoc finalLocaleResource = localeResource;
375      
376       try {
377             InputStream JavaDoc is = (InputStream JavaDoc) AccessController.doPrivileged
378             (new PrivilegedAction JavaDoc() {
379                   public Object JavaDoc run() {
380                     InputStream JavaDoc locis =
381                         finalp.getClass().getResourceAsStream (finalLocaleResource);
382                     return locis;
383                   }
384               }
385            );
386         
387         if (is == null) {
388 // localAW.println("resource is null: " + localeResource);
389
}
390         else {
391
392           try {
393               p.clear();
394             p.load (is);
395         //Displaying Current Locale
396
if (cur_loc)
397         {
398     Locale JavaDoc loc = null;
399     loc = Locale.getDefault();
400         localAW.println(Main.getTextMessage ("SIF01.T") + " [" + loc.getDisplayLanguage() + "/" + loc.getDisplayCountry() + " [" + loc + "]]");
401         cur_loc = false;
402         }
403
404     //Beetle 5079: do not print unlocalized locale names to console, only print locale code.
405
String JavaDoc localeName = p.getProperty("derby.locale.external.name");
406     localeName = localeName.substring(localeName.indexOf("[")+1);
407     localeName = localeName.substring(0,localeName.indexOf("]"));
408     
409             localAW.println (Main.getTextMessage ("SIF01.R",
410                                                                    localeName));
411
412
413             int major = Integer.valueOf(p.getProperty ("derby.locale.version.major")).intValue();
414             int minor = Integer.valueOf(p.getProperty ("derby.locale.version.minor")).intValue();
415             int maint = Integer.valueOf(p.getProperty ("derby.locale.version.maint")).intValue();
416             String JavaDoc build = p.getProperty ("derby.locale.build.number");
417
418             String JavaDoc lv = ProductVersionHolder.fullVersionString(major, minor, maint, false, build);
419
420
421             localAW.println (Main.getTextMessage ("SIF01.S", lv));
422
423
424           }
425           catch (IOException JavaDoc ioe) {
426
427             //This case is a bit ugly. If we get an IOException, we return
428
//null. Though this correctly reflects that the product is not
429
//available for use, it may be confusing to users that we swallow
430
//the IO error here.
431

432             localAW.println("Could not get locale properties from : " + is);
433           }
434         }
435
436       }
437       catch (Throwable JavaDoc t) {
438         localAW.println ("Could not load resource: " + localeResource);
439         localAW.println ("Exception: " + t);
440       }
441
442     }
443
444
445     localAW.println (sep);
446
447   } // end of reportLocales
448

449     /* for arguments, choose from one of:*/
450     private static final String JavaDoc EMBEDDED = "embedded";
451
452     /* you can add this if you like*/
453     private static final String JavaDoc TOOLS = "tools";
454
455     private static final String JavaDoc NET = "server";
456     private static final String JavaDoc CLIENT = "client";
457     private static final String JavaDoc DB2DRIVER = "db2driver";
458
459     /* you can add this if you like */
460
461     private static final String JavaDoc MAINUSAGESTRING = "java org.apache.derby.tools.sysinfo -cp";
462
463     private static final String JavaDoc USAGESTRINGPARTA = MAINUSAGESTRING + " [ [ " + EMBEDDED + " ][ " + NET + " ][ " + CLIENT + "] [ " + DB2DRIVER + " ] [ " + TOOLS + " ] [ ";
464     private static final String JavaDoc USAGESTRINGPARTB = ".class ] ]";
465
466   static void useMe(String JavaDoc[] args, java.io.PrintWriter JavaDoc pw) {
467       java.io.PrintWriter JavaDoc localPW = pw;
468
469         if (localPW == null)
470         {
471             localPW = new java.io.PrintWriter JavaDoc(System.out);
472         }
473
474
475       int length = args.length;
476       if (length==1) {
477
478           try {
479               tryAllClasspaths(localPW);
480
481           }
482
483           catch (Throwable JavaDoc t) {
484
485           }
486       }
487       else {
488           try {
489               trySomeClasspaths(args, localPW);
490           }
491
492           catch (Throwable JavaDoc t) {
493
494           }
495       }
496
497   }
498
499
500
501
502
503       private static void tryAllClasspaths(java.io.PrintWriter JavaDoc localPW) throws Throwable JavaDoc {
504           localPW.println(Main.getTextMessage("SIF08.B"));
505           localPW.println(Main.getTextMessage("SIF08.C", MAINUSAGESTRING + " args"));
506           StringBuffer JavaDoc successes = new StringBuffer JavaDoc(Main.getTextMessage("SIF08.D")+ crLf());
507           StringBuffer JavaDoc failures = new StringBuffer JavaDoc(crLf() + Main.getTextMessage("SIF08.E") + crLf());
508           tryCoreClasspath(successes, failures);
509           tryNetClasspath(successes, failures);
510           tryClientClasspath(successes, failures);
511           tryDB2DriverClasspath(successes, failures);
512           tryUtilsClasspath(successes, failures);
513           localPW.println(successes.toString());
514           if (!failures.toString().equals(crLf() + Main.getTextMessage("SIF08.E") + crLf())) {
515               localPW.println(failures.toString());
516           }
517           else {
518
519               localPW.println(Main.getTextMessage("SIF08.F"));
520           }
521           localPW.flush();
522       }
523
524     private static void trySomeClasspaths(String JavaDoc[] args, java.io.PrintWriter JavaDoc localPW) throws Throwable JavaDoc {
525
526         boolean seenArg = false;
527         StringBuffer JavaDoc successes = new StringBuffer JavaDoc(Main.getTextMessage("SIF08.D")+ crLf());
528         StringBuffer JavaDoc failures = new StringBuffer JavaDoc(crLf() + Main.getTextMessage("SIF08.E") + crLf());
529
530         if (argumentsContain(args, EMBEDDED))
531         {
532
533             tryCoreClasspath(successes, failures);
534             seenArg =true;
535
536         }
537         if (argumentsContain(args,NET)) {
538           tryNetClasspath(successes, failures);
539             seenArg =true;
540
541         }
542         if (argumentsContain(args,CLIENT)) {
543           tryClientClasspath(successes, failures);
544             seenArg =true;
545
546         }
547         if (argumentsContain(args,DB2DRIVER)) {
548             tryDB2DriverClasspath(successes, failures);
549             seenArg =true;
550         }
551
552         if (argumentsContain(args,TOOLS) || argumentsContain(args,"utils")) {
553           tryUtilsClasspath(successes, failures);
554             seenArg =true;
555
556         }
557
558
559         String JavaDoc userclass = argumentMatches(args, ".class");
560         if (!userclass.equals("")) {
561             tryMyClasspath(argumentMatches(args, ".class"), Main.getTextMessage("SIF08.H", userclass), successes, failures);
562             seenArg =true;
563         }
564
565         if (seenArg)
566         {
567
568             localPW.println(successes.toString());
569             if (!failures.toString().equals(crLf() + Main.getTextMessage("SIF08.E") + crLf())) {
570                 localPW.println(failures.toString());
571             }
572             else {
573
574                 localPW.println(Main.getTextMessage("SIF08.F"));
575             }
576         }
577         else
578         {
579             localPW.println(Main.getTextMessage("SIF08.A", USAGESTRINGPARTA, USAGESTRINGPARTB));
580         }
581         localPW.flush();
582
583     }
584
585     private static void tryCoreClasspath(StringBuffer JavaDoc successes, StringBuffer JavaDoc failures) {
586         tryMyClasspath("org.apache.derby.database.Database", Main.getTextMessage("SIF08.J","derby.jar" ), successes, failures);
587     }
588     private static void tryNetClasspath(StringBuffer JavaDoc successes, StringBuffer JavaDoc failures) {
589         tryMyClasspath("org.apache.derby.database.Database", Main.getTextMessage("SIF08.J","derby.jar" ), successes, failures);
590         tryMyClasspath("org.apache.derby.drda.NetworkServerControl", Main.getTextMessage("SIF08.I", "derbynet.jar"), successes, failures);
591     }
592     private static void tryClientClasspath(StringBuffer JavaDoc successes, StringBuffer JavaDoc failures) {
593         tryMyClasspath("org.apache.derby.jdbc.ClientDriver", Main.getTextMessage("SIF08.L", "derbyclient.jar"), successes, failures);
594     }
595     private static void tryDB2DriverClasspath(StringBuffer JavaDoc successes,
596             StringBuffer JavaDoc failures)
597     {
598         tryMyClasspath("com.ibm.db2.jcc.DB2Driver",
599                 Main.getTextMessage("SIF08.L", "db2jcc.jar"),
600                 successes, failures);
601     }
602
603     private static void tryUtilsClasspath(StringBuffer JavaDoc successes, StringBuffer JavaDoc failures) {
604         tryMyClasspath("org.apache.derby.tools.ij", Main.getTextMessage("SIF08.Q", "derbytools.jar"), successes, failures);
605     }
606
607     private static void tryMyClasspath(String JavaDoc cn, String JavaDoc library, StringBuffer JavaDoc successes, StringBuffer JavaDoc failures) {
608
609         try {
610             Class JavaDoc c = Class.forName(cn);
611                         String JavaDoc loc = getFileWhichLoadedClass(c);
612                         successes.append(found(cn, library, loc));
613         }
614
615         catch (Throwable JavaDoc t) {
616
617             failures.append(notFound(cn, library));
618
619         }
620
621
622     }
623
624     private static void tryAsResource(String JavaDoc cn, String JavaDoc library, StringBuffer JavaDoc successes, StringBuffer JavaDoc failures) {
625
626         try {
627             java.io.InputStream JavaDoc in = cn.getClass().getResourceAsStream(cn);
628             in.close();
629                         String JavaDoc loc = getFileWhichLoadedClass(cn.getClass());
630             successes.append(found(cn, library, loc));
631         }
632
633         catch (Throwable JavaDoc t) {
634             failures.append(notFound(cn, library));
635
636         }
637
638     }
639
640     private static String JavaDoc found(String JavaDoc cn, String JavaDoc library, String JavaDoc loc) {
641         StringBuffer JavaDoc temp = new StringBuffer JavaDoc(crLf());
642         temp.append(" " + library);
643         temp.append(crLf());
644                 if (loc != null)
645                     temp.append(" ").append(loc).append(crLf());
646         temp.append(crLf());
647         return temp.toString();
648     }
649     private static String JavaDoc notFound(String JavaDoc cn, String JavaDoc library) {
650
651         StringBuffer JavaDoc temp = new StringBuffer JavaDoc(crLf());
652         temp.append(" " + library);
653         temp.append(crLf());
654         temp.append(" " + Main.getTextMessage("SIF08.U", cn));
655         temp.append(crLf());
656         temp.append(crLf());
657         return temp.toString();
658     }
659
660     private static String JavaDoc crLf() {
661         return System.getProperty("line.separator");
662     }
663
664     private static String JavaDoc lookForMainArg(String JavaDoc[] args, java.io.PrintWriter JavaDoc localPW)
665     {
666         int length=args.length;
667         String JavaDoc[] legalargs = new String JavaDoc[1];
668         legalargs[0] = EMBEDDED;
669
670         int argsfound = 0;
671         String JavaDoc whichargument="";
672
673         for (int i = 0; i < length; i++) {
674
675             for (int j=0; j < legalargs.length; j++) {
676                 if (args[i].toUpperCase(java.util.Locale.ENGLISH).equals(legalargs[j].toUpperCase(java.util.Locale.ENGLISH))) {
677                     argsfound++;
678                     whichargument=legalargs[j];
679                 }
680             }
681         }
682         if (argsfound > 1 || argsfound < 1) {
683             localPW.println(Main.getTextMessage("SIF08.A", USAGESTRINGPARTA, USAGESTRINGPARTB));
684             return "";
685         }
686         return whichargument;
687     }
688
689     private static boolean argumentsContain(String JavaDoc[] args, String JavaDoc s) {
690         for (int i = 0; i < args.length; i++) {
691             if (args[i].equalsIgnoreCase(s))
692                 return true;
693         }
694         return false;
695
696     }
697
698     private static String JavaDoc argumentMatches(String JavaDoc[] args, String JavaDoc ss) {
699         String JavaDoc userclass = "";
700         int length = args.length;
701         for (int i = 0; i < length; i++) {
702             if (args[i].endsWith(ss)) {
703                 userclass = args[i].substring(0,args[i].length()-6) ;
704
705             }
706
707         }
708         return userclass;
709     }
710
711     /*
712     ** Code related to loading info fromjar files.
713     */

714
715     private static final String JavaDoc infoNames[] = {
716
717                                     "org/apache/derby/info/" +
718                                     org.apache.derby.iapi.services.info.ProductGenusNames.DBMS +
719                                     ".properties",
720
721
722                                     "org/apache/derby/info/" +
723                                     org.apache.derby.iapi.services.info.ProductGenusNames.TOOLS +
724                                     ".properties",
725
726                                     "org/apache/derby/info/" +
727                                     org.apache.derby.iapi.services.info.ProductGenusNames.NET +
728                                     ".properties",
729
730                                    "org/apache/derby/info/" +
731                                     org.apache.derby.iapi.services.info.ProductGenusNames.DNC +
732                                     ".properties"
733                                 };
734
735     /**
736      * Get all the info we can obtain from the local execution context
737      * as to the availability of the Derby classes by attempting to load
738      * the info files with loadZipFromResource() and checking classpath
739      * locations with checkForInfo if the classpath is accessible.
740      *
741      * @param classpath the classpath, or null if not accessible
742      * @return an array of ZipInfoProperties with the locations of the located
743      * resources
744      * @see #loadZipFromResource()
745      * @see #checkForInfo(String)
746      */

747     public static ZipInfoProperties[] getAllInfo(String JavaDoc classpath)
748     {
749         ZipInfoProperties zips[] = loadZipFromResource();
750
751         // No info properties files found, but here we are in sysinfo.
752
// Avoid an NPE in mergeZips by creating a ZipInfoProperties array
753
// with the location of the sysinfo that is currently executing.
754
if (zips == null)
755         {
756             zips = new ZipInfoProperties[1];
757             ZipInfoProperties zip = new ZipInfoProperties(ProductVersionHolder.getProductVersionHolderFromMyEnv(org.apache.derby.tools.sysinfo.TOOLS));
758             zip.setLocation(getFileWhichLoadedClass(new Main().getClass()));
759             zips[0] = zip;
760         }
761
762         try
763         {
764             if (classpath != null) {
765                 String JavaDoc cp [] = parseClasspath(classpath);
766                 Vector JavaDoc v = new Vector JavaDoc();
767                 for (int i = 0; i < cp.length; i++)
768                 {
769                     ZipInfoProperties zip = null;
770                     try {
771                         zip = checkForInfo(cp[i]);
772                     }
773                     catch (SecurityException JavaDoc se)
774                     {
775                         zip = new ZipInfoProperties(null);
776                         zip.setLocation(
777                             Main.getTextMessage ("SIF03.C", se.getMessage()));
778                     }
779                     if (zip != null)
780                     {
781                         v.addElement(zip);
782                     }
783                 }
784                 if (v.size() > 0)
785                 {
786                     ZipInfoProperties cpzips[] = new ZipInfoProperties[v.size()];
787                     v.copyInto(cpzips);
788                     return mergeZips(zips, cpzips);
789                 }
790             }
791             return mergeZips(zips, null);
792
793         }
794         catch (SecurityException JavaDoc se)
795         {
796             ZipInfoProperties zip[] = new ZipInfoProperties[1];
797             zip[0] = new ZipInfoProperties(null);
798             zip[0].setLocation(
799                     Main.getTextMessage ("SIF03.C", se.getMessage()));
800             return zip;
801         }
802     }
803
804     /**
805      * Attempt to load the info properties files specified in infoNames[i]
806      * using getResourceAsStream(). If none are able to be loaded, return
807      * a null array.
808      *
809      * @return An array of ZipInfoProperties with the locations from which
810      * the info properties files were loaded.
811      * @see #infoNames
812      */

813     private static ZipInfoProperties [] loadZipFromResource()
814     {
815         java.util.ArrayList JavaDoc al = new java.util.ArrayList JavaDoc();
816
817         for (int i = 0; i < infoNames.length; i++)
818         {
819             final String JavaDoc resource = "/".concat(infoNames[i]);
820
821             InputStream JavaDoc is = (InputStream JavaDoc) AccessController.doPrivileged
822             (new PrivilegedAction JavaDoc() {
823                 public Object JavaDoc run() {
824                     InputStream JavaDoc locis =
825                         new Main().getClass().getResourceAsStream(resource);
826                             return locis;
827                     }
828                 }
829             );
830
831             if (is == null)
832                 continue;
833
834             ZipInfoProperties ze = new ZipInfoProperties(ProductVersionHolder.getProductVersionHolderFromMyEnv(is));
835  
836                         // get the real location of the info file
837
URL JavaDoc locUrl = (URL JavaDoc) AccessController.doPrivileged
838                         (new PrivilegedAction JavaDoc() {
839                             public Object JavaDoc run() {
840                                 URL JavaDoc realUrl = new Main().getClass().getResource(resource);
841                                 return realUrl;
842                             }
843                         });
844
845             ze.setLocation(formatURL(locUrl));
846
847             al.add(ze);
848         }
849
850         if (al.size() == 0)
851         {
852             return null;
853         }
854
855         ZipInfoProperties[] zip = new ZipInfoProperties[al.size()];
856
857         al.toArray(zip);
858
859         return zip;
860     }
861
862     /**
863      * Split the classpath into separate elements.
864      *
865      * @param cp the classpath, if accessible.
866      * @return a String array with the individual classpath elements.
867      */

868     private static String JavaDoc [] parseClasspath(String JavaDoc cp)
869     {
870         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(cp, File.pathSeparator);
871         int count = st.countTokens();
872         if (count == 0)
873         {
874             return null;
875         }
876
877         String JavaDoc vals[] = new String JavaDoc[count];
878         for (int i =0; i < count; i++)
879         {
880             vals[i] = st.nextToken();
881         }
882         return vals;
883     }
884
885     /**
886      * Given an individual element of the element of the classpath, call
887      * checkDirectory() if the element is a directory or checkFile()
888      * if the element is a file.
889      *
890      * @param cpEntry the classpath element
891      * @return a ZipInfoProperties if an info properties file is found.
892      */

893     private static ZipInfoProperties checkForInfo(String JavaDoc cpEntry)
894     {
895         File JavaDoc f = new File JavaDoc(cpEntry);
896         if ( ! f.exists())
897         {
898             return null;
899         }
900
901         if (f.isDirectory())
902         {
903             ZipInfoProperties zip = checkDirectory(cpEntry);
904             return zip;
905         }
906
907         if (f.isFile())
908         {
909             ZipInfoProperties zip = checkFile(cpEntry);
910             return zip;
911         }
912         return null;
913     }
914
915     /**
916      * Check a given directory for the presence of an info properties file in
917      * org/apache/derby/info inside the directory.
918      *
919      * @param dirname the directory to check as a String
920      * @return a ZipInfoProperties if a file is found, otherwise null.
921      */

922     private static ZipInfoProperties checkDirectory(String JavaDoc dirname)
923     {
924         boolean foundOne = false;
925         File JavaDoc f = null;
926         for (int i = 0; i < infoNames.length; i++)
927         {
928             String JavaDoc localSysinfo = infoNames[i].replace('/', File.separatorChar);
929             f = new File JavaDoc(dirname, localSysinfo);
930             if (f.exists())
931             {
932                 foundOne = true;
933                 break;
934             }
935         }
936
937         if (!foundOne || (f == null))
938         {
939             return null;
940         }
941
942         try
943         {
944             InputStream JavaDoc bis = new FileInputStream JavaDoc(f);
945
946             ZipInfoProperties zip = new ZipInfoProperties(ProductVersionHolder.getProductVersionHolderFromMyEnv(bis));
947             zip.setLocation(new File JavaDoc(dirname).getCanonicalPath().replace('/', File.separatorChar));
948             return zip;
949         }
950         catch (IOException JavaDoc ioe)
951         {
952             return null;
953         }
954
955     }
956
957     /**
958      * Check inside a jar file for the presence of a Derby info properties
959      * file. There is a special case for db2jcc, which does not have a Derby
960      * info propeties file. If db2jcc is in the filename, acquire DB2Driver
961      * via reflection and get the version number from it.
962      *
963      * @param filename the jar file to check
964      * @return ZipInfoProperties with the jar file set as the location
965      * or null if not found.
966      */

967     private static ZipInfoProperties checkFile(String JavaDoc filename)
968     {
969         // try to create a ZipFile from it
970

971     // Check to see if it's a version of db2jcc.jar and if so, report the version number.
972
if (filename.indexOf("db2jcc") >= 0)
973     {
974         Class JavaDoc c = null;
975         Method JavaDoc m = null;
976         Object JavaDoc o = null;
977         Integer JavaDoc build = null;
978         Integer JavaDoc major = null;
979             Integer JavaDoc minor = null;
980         try
981         {
982                 try
983         {
984             c = Class.forName("com.ibm.db2.jcc.DB2Driver");
985             m = c.getMethod("getJCCBuildNumber", null);
986             o = c.newInstance();
987             build = (Integer JavaDoc)m.invoke(o,null);
988         } catch (ClassNotFoundException JavaDoc cnfe) {
989             c = Class.forName("com.ibm.db2.jcc.DB2Version");
990             m = c.getMethod("getBuildNumber", null);
991             o = c.newInstance();
992             build = (Integer JavaDoc)m.invoke(o,null);
993             }
994         m = c.getMethod("getMajorVersion", null);
995         major = (Integer JavaDoc)m.invoke(o,null);
996         m = c.getMethod("getMinorVersion", null);
997         minor = (Integer JavaDoc)m.invoke(o,null);
998
999         ProductVersionHolder jccVersion = ProductVersionHolder.getProductVersionHolder(
1000            "IBM Corp.",
1001            "DB2 Java Common Client",
1002            "DRDA:jcc",
1003            major.intValue(),
1004            minor.intValue(),
1005            0,
1006            0,
1007            build.toString(),
1008            Boolean.FALSE);
1009
1010        ZipInfoProperties zip = new ZipInfoProperties(jccVersion);
1011
1012                String JavaDoc loc = getFileWhichLoadedClass(c);
1013                // For db2jcc.jar, report the actual file from which DB2Driver
1014
// was loaded, if we can determine it. For db2jcc_license_c,
1015
// report the filename from the classpath, and the version
1016
// info from the DB2Driver that we loaded. This is slightly
1017
// misleading, since db2jcc_license_c.jar doesn't really have
1018
// a "version", but the two jars are usually linked.
1019
if (loc != null && filename.indexOf("license_c") < 0)
1020                    zip.setLocation(loc);
1021                else
1022        zip.setLocation(new File JavaDoc(filename).getCanonicalPath().replace('/', File.separatorChar));
1023        return zip;
1024            } catch (Exception JavaDoc e) { return null; }
1025    }
1026
1027        try
1028        {
1029            ZipFile JavaDoc zf = new ZipFile JavaDoc(filename);
1030            // try to get a ZipEntry from the ZipFile
1031

1032            ZipEntry JavaDoc thisEntry = null;
1033
1034            for (int i =0; i < infoNames.length; i++)
1035            {
1036                thisEntry = zf.getEntry(infoNames[i]);
1037                if (thisEntry != null)
1038                {
1039                    break;
1040                }
1041            }
1042
1043            if (thisEntry == null)
1044            {
1045                return null;
1046            }
1047
1048            InputStream JavaDoc bis = zf.getInputStream(thisEntry);
1049            if (bis == null)
1050            {
1051                return null;
1052            }
1053
1054            ZipInfoProperties zip = new ZipInfoProperties(ProductVersionHolder.getProductVersionHolderFromMyEnv(bis));
1055            zip.setLocation(new File JavaDoc(filename).getCanonicalPath().replace('/', File.separatorChar));
1056            return zip;
1057
1058        }
1059        catch (IOException JavaDoc ioe)
1060        {
1061            //guess not
1062
return null;
1063        }
1064
1065    }
1066
1067    /*
1068    ** Message handling
1069    */

1070    private static ResourceBundle JavaDoc getBundle() {
1071        try {
1072            return ResourceBundle.getBundle("org.apache.derby.loc.sysinfoMessages");
1073        } catch (MissingResourceException JavaDoc mre) {
1074        }
1075        return null;
1076    }
1077
1078    public static String JavaDoc getTextMessage(String JavaDoc msgId) {
1079        return getCompleteMessage(msgId, (Object JavaDoc[]) null);
1080    }
1081    public static String JavaDoc getTextMessage(String JavaDoc msgId, Object JavaDoc a1) {
1082
1083        return getCompleteMessage(msgId, new Object JavaDoc[] {a1});
1084    }
1085    public static String JavaDoc getTextMessage(String JavaDoc msgId, Object JavaDoc a1, Object JavaDoc a2) {
1086        return getCompleteMessage(msgId, new Object JavaDoc[] {a1, a2});
1087    }
1088    public static String JavaDoc getTextMessage(String JavaDoc msgId, Object JavaDoc a1, Object JavaDoc a2, Object JavaDoc a3) {
1089        return getCompleteMessage(msgId, new Object JavaDoc[] {a1, a2, a3});
1090    }
1091    public static String JavaDoc getTextMessage(String JavaDoc msgId, Object JavaDoc a1, Object JavaDoc a2, Object JavaDoc a3, Object JavaDoc a4) {
1092        return getCompleteMessage(msgId, new Object JavaDoc[] {a1, a2, a3, a4});
1093    }
1094
1095    /**
1096     */

1097    public static String JavaDoc getCompleteMessage(String JavaDoc msgId, Object JavaDoc[] arguments) {
1098
1099        // we have a base file (sysinfoMessages.properties) so don't give us a last chance.
1100
return org.apache.derby.iapi.services.i18n.MessageService.formatMessage(getBundle(), msgId, arguments, false);
1101    }
1102
1103    /**
1104     * Given a loaded class, this
1105     * routine asks the class's class loader for information about where the
1106     * class was loaded from. Typically, this is a file, which might be
1107     * either a class file or a jar file. The routine figures that out, and
1108     * returns the name of the file. If it can't figure it out, it returns null
1109     */

1110    private static String JavaDoc getFileWhichLoadedClass(final Class JavaDoc cls)
1111    {
1112         return (String JavaDoc)AccessController.doPrivileged( new PrivilegedAction JavaDoc()
1113        {
1114            public Object JavaDoc run()
1115            {
1116                CodeSource JavaDoc cs = null;
1117                try {
1118                    cs = cls.getProtectionDomain().getCodeSource ();
1119                }
1120                catch (SecurityException JavaDoc se) {
1121                    return Main.getTextMessage("SIF01.V", cls, se.getMessage());
1122                }
1123 
1124                if ( cs == null )
1125                    return null;
1126     
1127                URL JavaDoc result = cs.getLocation ();
1128     
1129                return formatURL(result);
1130            }
1131        });
1132    }
1133
1134    /**
1135     * <P>
1136     * Merge and flatten two arrays of ZipInfoProperties, removing any
1137     * duplicates. There may be duplicates in the arrays because
1138     * loadZipFromResource may find all the properties files in the same
1139     * location, such as when loading from compiled source instead of
1140     * packaged jars. Also, a poorly constructed classpath may contain
1141     * duplicate entries that each contain the Derby classes, and we
1142     * need only report the first of each such instances found.
1143     * <P>
1144     * The second array may be null if the classpath was empty, in which
1145     * case we still remove the duplicates from the first array and return
1146     * the shortened array.
1147     *
1148     * @param zip1 the first array from loadZipWithResource
1149     * @param zip2 the second array from analyzing the classpath
1150     * @return the merged array
1151     */

1152    private static ZipInfoProperties[] mergeZips(ZipInfoProperties[] zip1,
1153                                                 ZipInfoProperties[] zip2)
1154    {
1155        Vector JavaDoc v = new Vector JavaDoc();
1156        boolean foundDup = false;
1157  
1158        // remove duplicates from first array
1159
for (int i = 0; i < zip1.length; i++)
1160        {
1161            if (zip1[i] != null && zip1.length > 1)
1162            {
1163                for (int j = i + 1; j < zip1.length; j++)
1164                {
1165                    if (zip1[i].getLocation().equals(zip1[j].getLocation()))
1166                    zip1[j] = null;
1167                }
1168            }
1169            if (zip1[i] != null)
1170              v.addElement(zip1[i]);
1171        }
1172  
1173        // if provided a second array, remove any locations in second array
1174
// still in first array.
1175
if (zip2 != null)
1176        {
1177          for (int j = 0; j < zip2.length; j++)
1178          {
1179            for (int k = 0; k < v.size(); k++)
1180            {
1181                ZipInfoProperties z = (ZipInfoProperties)v.get(k);
1182                if (zip2[j].getLocation().equals(z.getLocation()))
1183                  foundDup = true;
1184            }
1185            if (!foundDup)
1186            {
1187                v.addElement(zip2[j]);
1188            }
1189            foundDup = false;
1190          }
1191        }
1192  
1193        ZipInfoProperties[] merged = new ZipInfoProperties[v.size()];
1194        v.copyInto(merged);
1195        return merged;
1196    }
1197
1198    /**
1199     * Strip a given URL down to the filename. The URL will be a jarfile or
1200     * directory containing a Derby info properties file. Return the canonical
1201     * path for the filename, with the path separators normalized.
1202     */

1203    private static String JavaDoc formatURL(URL JavaDoc loc)
1204    {
1205        String JavaDoc filename = URLDecoder.decode(loc.toString());
1206
1207        if (filename.startsWith("jar:")) { filename = filename.substring(4); }
1208        if (filename.startsWith("file:")) { filename = filename.substring(5); }
1209        if (filename.indexOf("!") > -1) { filename = filename.substring(0, filename.indexOf("!")); }
1210        if (filename.indexOf("/org/apache/derby") > -1) {
1211            filename = filename.substring(0, filename.indexOf("/org/apache/derby"));
1212        }
1213        if (filename.charAt(0) == '/' &&
1214            Character.isLetter(filename.charAt(1)) &&
1215            filename.charAt(2) == ':' &&
1216            filename.charAt(2) == '/') { filename = filename.substring(1); }
1217
1218        String JavaDoc result = "";
1219        try {
1220            result = new File JavaDoc(filename).getCanonicalPath().replace('/', File.separatorChar);
1221        } catch (IOException JavaDoc e) {
1222            result = "IOException";
1223        }
1224        return result;
1225    }
1226
1227} // end of class Main
1228

1229
Popular Tags