KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > impl > tools > ij > util


1 /*
2
3    Derby - Class org.apache.derby.impl.tools.ij.util
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.ij;
23
24 import org.apache.derby.tools.JDBCDisplayUtil;
25 import org.apache.derby.iapi.tools.i18n.*;
26
27 import java.io.BufferedInputStream JavaDoc;
28 import java.io.FileInputStream JavaDoc;
29 import java.io.FileNotFoundException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.lang.reflect.InvocationTargetException JavaDoc;
33
34 import java.sql.Connection JavaDoc;
35 import java.sql.DriverManager JavaDoc;
36 import java.sql.SQLException JavaDoc;
37 import java.sql.SQLWarning JavaDoc;
38 import java.sql.Statement JavaDoc;
39 import java.sql.PreparedStatement JavaDoc;
40 import java.sql.ResultSet JavaDoc;
41 import java.sql.ResultSetMetaData JavaDoc;
42 import java.sql.Types JavaDoc;
43
44 import java.util.Properties JavaDoc;
45 import java.util.Vector JavaDoc;
46 import java.util.Locale JavaDoc;
47
48 /**
49     Methods used to control setup for apps as
50     well as display some internal ij structures.
51
52     @see org.apache.derby.tools.JDBCDisplayUtil
53     @author ames
54  */

55 public final class util implements java.security.PrivilegedAction JavaDoc {
56     
57     private static boolean HAVE_BIG_DECIMAL;
58     
59     {
60         boolean haveBigDecimal;
61         try {
62             Class.forName("java.math.BigDecimal");
63             haveBigDecimal = true;
64         } catch (Throwable JavaDoc t) {
65             haveBigDecimal = false;
66         }
67         HAVE_BIG_DECIMAL = haveBigDecimal;
68     }
69     
70     private static final Class JavaDoc[] DS_GET_CONN_TYPES = {"".getClass(), "".getClass()};
71     private util() {}
72
73     //-----------------------------------------------------------------
74
// Methods for starting up JBMS
75

76     /**
77      * Find the argument that follows the specified parameter.
78      *
79      * @param param the parameter (e.g. "-p")
80      * @param args the argument list to consider.
81      *
82      * @return the argument that follows the parameter, or null if not found
83      */

84     static public String JavaDoc getArg(String JavaDoc param, String JavaDoc[] args)
85     {
86         int pLocn;
87         Properties JavaDoc p;
88
89         if (args == null) return null;
90
91         for (pLocn=0; pLocn<args.length; pLocn++) {
92             if (param.equals(args[pLocn])) break;
93         }
94         if (pLocn >= (args.length-1)) // not found or no file
95
return null;
96
97         return args[pLocn+1];
98     }
99
100     /**
101         ij is started with "-p[r] file OtherArgs";
102         the file contains properties to control the driver and database
103         used to run ij, and can provide additional system properties.
104         <p>
105         getPropertyArg will look at the args and take out a "-p <file>" pair,
106         reading the file into the system properties.
107         <p>
108         If there was a -p without a following <file>, no action is taken.
109
110         @exception IOException thrown if file not found
111
112         @param args the argument list to consider.
113         @return true if a property item was found and loaded.
114      */

115     static public boolean getPropertyArg(String JavaDoc[] args) throws IOException JavaDoc {
116         String JavaDoc n;
117         InputStream JavaDoc in1;
118         Properties JavaDoc p;
119
120         if ((n = getArg("-p", args))!= null){
121             in1 = new FileInputStream JavaDoc(n);
122             in1 = new BufferedInputStream JavaDoc(in1);
123         }
124         else if ((n = getArg("-pr", args)) != null) {
125             in1 = getResourceAsStream(n);
126             if (in1 == null) throw ijException.resourceNotFound();
127         }
128         else
129             return false;
130
131         p = System.getProperties();
132
133         // Trim off excess whitespace in property file, if any, and
134
// then load those properties into 'p'.
135
util.loadWithTrimmedValues(in1, p);
136
137         return true;
138     }
139
140     /**
141         ij is started with "-ca[r] file OtherArgs";
142         the file contains connection attibute properties
143         to pass to getConnection
144         <p>
145         getConnAttributeArg will look at the args and take out a
146         "-ca[r] <file>" pair and returning the Properties
147         <p>
148
149         @exception IOException thrown if file not found
150
151         @param args the argument list to consider.
152         @return properties in the file
153      */

154     static public Properties JavaDoc getConnAttributeArg(String JavaDoc[] args)
155         throws IOException JavaDoc
156     {
157         String JavaDoc n;
158         InputStream JavaDoc in1;
159         Properties JavaDoc p = new Properties JavaDoc();
160
161         if ((n = getArg("-ca", args))!= null){
162             in1 = new FileInputStream JavaDoc(n);
163             in1 = new BufferedInputStream JavaDoc(in1);
164         }
165         else if ((n = getArg("-car", args)) != null) {
166             in1 = getResourceAsStream(n);
167             if (in1 == null) throw ijException.resourceNotFound();
168         }
169         else
170             return null;
171
172         // Trim off excess whitespace in property file, if any, and
173
// then load those properties into 'p'.
174
util.loadWithTrimmedValues(in1, p);
175
176         return p;
177     }
178
179
180
181     /**
182       Convenience routine to qualify a resource name with "ij.defaultPackageName"
183       if it is not qualified (does not begin with a "/").
184
185       @param absolute true means return null if the name is not absolute and false
186       means return partial names.
187       */

188     static String JavaDoc qualifyResourceName(String JavaDoc resourceName, boolean absolute)
189     {
190         resourceName=resourceName.trim();
191         if (resourceName.startsWith("/"))
192         {
193             return resourceName;
194         }
195         else
196         {
197             String JavaDoc pName = util.getSystemProperty("ij.defaultResourcePackage").trim();
198             if (pName == null) return null;
199             if ((pName).endsWith("/"))
200                 resourceName = pName+resourceName;
201             else
202                 resourceName = pName+"/"+resourceName;
203             if (absolute && !resourceName.startsWith("/"))
204                 return null;
205             else
206                 return resourceName;
207         }
208     }
209     /**
210       Convenience routine to get a resource as a BufferedInputStream. If the
211       resourceName is not absolute (does not begin with a "/") this qualifies
212       the name with the "ij.defaultResourcePackage" name.
213
214       @param resourceName the name of the resource
215       @return a buffered stream for the resource if it exists and null otherwise.
216       */

217     static public InputStream JavaDoc getResourceAsStream(String JavaDoc resourceName)
218     {
219         Class JavaDoc c= util.class;
220         resourceName = qualifyResourceName(resourceName,true);
221         if (resourceName == null)
222             return null;
223         InputStream JavaDoc is = c.getResourceAsStream(resourceName);
224         if (is != null)
225             is = new BufferedInputStream JavaDoc(is, utilMain.BUFFEREDFILESIZE);
226         return is;
227     }
228
229     /**
230       Return the name of the ij command file or null if none is
231       specified. The command file may be proceeded with -f flag on
232       the command line. Alternatively, the command file may be
233       specified without a -f flag. In this case we assume the first
234       unknown argument is the command file.
235
236       <P>
237       This should only be called after calling invalidArgs.
238
239       <p>
240       If there is no such argument, a null is returned.
241
242       @param args the argument list to consider.
243       @return the name of the first argument not preceded by "-p",
244       null if none found.
245       
246       @exception IOException thrown if file not found
247      */

248     static public String JavaDoc getFileArg(String JavaDoc[] args) throws IOException JavaDoc {
249         String JavaDoc fileName;
250         int fLocn;
251         boolean foundP = false;
252
253         if (args == null) return null;
254         if ((fileName=getArg("-f",args))!=null) return fileName;
255         //
256
//The first unknown arg is the file
257
for (int ix=0; ix < args.length; ix++)
258             if(args[ix].equals("-f") ||
259                args[ix].equals("-fr") ||
260                args[ix].equals("-ca") ||
261                args[ix].equals("-car") ||
262                args[ix].equals("-p") ||
263                args[ix].equals("-pr"))
264                 ix++; //skip the parameter to these args
265
else
266                 return args[ix];
267         return null;
268     }
269
270     /**
271       Return the name of a resource containing input commands or
272       null iff none has been specified.
273       */

274     static public String JavaDoc getInputResourceNameArg(String JavaDoc[] args) {
275         return getArg("-fr", args);
276     }
277
278     /**
279       Verify the ij line arguments command arguments. Also used to detect --help.
280       @return true if the args are invalid
281       <UL>
282       <LI>Only legal argument provided.
283       <LI>Only specify a quantity once.
284       </UL>
285      */

286     static public boolean invalidArgs(String JavaDoc[] args) {
287         int countSupported = 0;
288         boolean haveInput = false;
289         for (int ix=0; ix < args.length; ix++)
290         {
291             //
292
//If the arguemnt is a supported flag skip the flags argument
293
if(!haveInput && (args[ix].equals("-f") || args[ix].equals("-fr")))
294             {
295                 haveInput = true;
296                 ix++;
297                 if (ix >= args.length) return true;
298             }
299
300             else if ((args[ix].equals("-p") || args[ix].equals("-pr") ||
301                       args[ix].equals("-ca") || args[ix].equals("-car") ))
302             {
303                 // next arg is the file/resource name
304
ix++;
305                 if (ix >= args.length) return true;
306             } else if (args[ix].equals("--help")) { return true; }
307
308             //
309
//Assume the first unknown arg is a file name.
310
else if (!haveInput)
311             {
312                 haveInput = true;
313             }
314
315             else
316             {
317                 return true;
318             }
319         }
320         return false;
321     }
322
323     /**
324      * print a usage message for invocations of main().
325      */

326     static void Usage(LocalizedOutput out) {
327         out.println(
328         LocalizedResource.getMessage("IJ_UsageJavaComCloudToolsIjPPropeInput"));
329         out.flush();
330     }
331
332
333     private static final Class JavaDoc[] STRING_P = { "".getClass() };
334     private static final Class JavaDoc[] INT_P = { Integer.TYPE };
335
336
337     /**
338      * Sets up a data source with values specified in ij.dataSource.* properties or
339      * passed as parameters of this method
340      *
341      * @param ds DataSource object
342      * @param dbName Database Name
343      * @param firstTime If firstTime is false, ij.dataSource.createDatabase and ij.dataSource.databaseName
344      * properties will not be used. The value in parameter dbName will be used instead of
345      * ij.dataSource.databaseName.
346      *
347      * @throws Exception
348      */

349     static public void setupDataSource(Object JavaDoc ds,String JavaDoc dbName,boolean firstTime) throws Exception JavaDoc {
350     // Loop over set methods on Datasource object, if there is a property
351
// then call the method with corresponding value. Call setCreateDatabase based on
352
//parameter create.
353
java.lang.reflect.Method JavaDoc[] methods = ds.getClass().getMethods();
354     for (int i = 0; i < methods.length; i++) {
355         java.lang.reflect.Method JavaDoc m = methods[i];
356         String JavaDoc name = m.getName();
357         
358         if (name.startsWith("set") && (name.length() > "set".length())) {
359             //Check if setCreateDatabase has to be called based on create parameter
360
if(name.equals("setCreateDatabase") && !firstTime)
361                 continue;
362             
363             String JavaDoc property = name.substring("set".length()); // setXyyyZwww
364
property = "ij.dataSource."+property.substring(0,1).toLowerCase(java.util.Locale.ENGLISH)+ property.substring(1); // xyyyZwww
365
String JavaDoc value = util.getSystemProperty(property);
366             if(name.equals("setDatabaseName") && !firstTime)
367                 value = dbName;
368             if (value != null) {
369                 try {
370                     // call string method
371
m.invoke(ds, new Object JavaDoc[] {value});
372                 } catch (Throwable JavaDoc ignore) {
373                     // failed, assume it's an integer parameter
374
m.invoke(ds, new Object JavaDoc[] {Integer.valueOf(value)});
375                 }
376             }
377         }
378     }
379     }
380     
381     /**
382      * Returns a connection obtained using the DataSource. This method will be called when ij.dataSource
383      * property is set. It uses ij.dataSource.* properties to get details for the connection.
384      *
385      * @param dsName Data Source name
386      * @param user User name
387      * @param password Password
388      * @param dbName Database Name
389      * @param firstTime Indicates if the method is called first time. This is passed to setupDataSource
390      * method.
391      *
392      * @throws SQLException
393      */

394     public static Connection JavaDoc getDataSourceConnection(String JavaDoc dsName,String JavaDoc user,String JavaDoc password,
395                                                     String JavaDoc dbName,boolean firstTime) throws SQLException JavaDoc{
396         // Get a new proxied connection through DataSource
397
Object JavaDoc ds = null; // really javax.sql.DataSource
398
try {
399             
400             Class JavaDoc dc = Class.forName(dsName);
401             ds = dc.newInstance();
402             
403             // set datasource properties
404
setupDataSource(ds,dbName,firstTime);
405
406             // Java method call "by hand" { con = ds.getConnection(); }
407
// or con = ds.getConnection(user, password)
408

409             java.lang.reflect.Method JavaDoc m =
410                 user == null ? dc.getMethod("getConnection", null) :
411                      dc.getMethod("getConnection", DS_GET_CONN_TYPES);
412                 
413             return (java.sql.Connection JavaDoc) m.invoke(ds,
414                      user == null ? null : new String JavaDoc[] {user, password});
415         } catch (InvocationTargetException JavaDoc ite)
416         {
417             if (ite.getTargetException() instanceof SQLException JavaDoc)
418                 throw (SQLException JavaDoc) ite.getTargetException();
419             ite.printStackTrace(System.out);
420         } catch (Exception JavaDoc e)
421         {
422             e.printStackTrace(System.out);
423         }
424         return null;
425     }
426
427     /**
428         This will look for the System properties "ij.driver" and "ij.database"
429         and return a java.sql.Connection if it successfully connects.
430         The deprecated driver and database properties are examined first.
431         <p>
432         If no connection was possible, it will return a null.
433         <p>
434         Failure to load the driver class is quietly ignored.
435
436         @param defaultDriver the driver to use if no property value found
437         @param defaultURL the database URL to use if no property value found
438         @param connInfo Connection attributes to pass to getConnection
439         @return a connection to the defaultURL if possible; null if not.
440         @exception SQLException on failure to connect.
441         @exception ClassNotFoundException on failure to load driver.
442         @exception InstantiationException on failure to load driver.
443         @exception IllegalAccessException on failure to load driver.
444      */

445     static public Connection JavaDoc startJBMS(String JavaDoc defaultDriver, String JavaDoc defaultURL,
446                        Properties JavaDoc connInfo)
447     throws SQLException JavaDoc, ClassNotFoundException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc
448     {
449     Connection JavaDoc con = null;
450         String JavaDoc driverName;
451         String JavaDoc databaseURL;
452
453     // deprecate the non-ij prefix. actually, we should defer to jdbc.drivers...
454
driverName = util.getSystemProperty("driver");
455         if (driverName == null) driverName = util.getSystemProperty("ij.driver");
456     if (driverName == null || driverName.length()==0) driverName = defaultDriver;
457         if (driverName != null) {
458         util.loadDriver(driverName);
459     }
460
461     String JavaDoc jdbcProtocol = util.getSystemProperty("ij.protocol");
462     if (jdbcProtocol != null)
463         util.loadDriverIfKnown(jdbcProtocol);
464     
465     String JavaDoc user = util.getSystemProperty("ij.user");
466     String JavaDoc password = util.getSystemProperty("ij.password");
467
468     // deprecate the non-ij prefix name
469
databaseURL = util.getSystemProperty("database");
470     if (databaseURL == null) databaseURL = util.getSystemProperty("ij.database");
471     if (databaseURL == null || databaseURL.length()==0) databaseURL = defaultURL;
472     if (databaseURL != null) {
473         // add protocol if might help find driver.
474
// if have full URL, load driver for it
475
if (databaseURL.startsWith("jdbc:"))
476             util.loadDriverIfKnown(databaseURL);
477         if (!databaseURL.startsWith("jdbc:") && jdbcProtocol != null)
478         databaseURL = jdbcProtocol+databaseURL;
479
480         // Update connInfo for ij system properties and
481
// framework network server
482

483         connInfo = updateConnInfo(user, password,connInfo);
484
485         // JDBC driver
486
String JavaDoc driver = util.getSystemProperty("driver");
487         if (driver == null) {
488         driver = "org.apache.derby.jdbc.EmbeddedDriver";
489         }
490         
491         loadDriver(driver);
492         con = DriverManager.getConnection(databaseURL,connInfo);
493         return con;
494     }
495
496         // handle datasource property
497
String JavaDoc dsName = util.getSystemProperty("ij.dataSource");
498         if (dsName == null)
499             return null;
500         
501         //First connection - pass firstTime=true, dbName=null. For database name,
502
//value in ij.dataSource.databaseName will be used.
503
con = getDataSourceConnection(dsName,user,password,null,true);
504         return con;
505    }
506
507
508     public static Properties JavaDoc updateConnInfo(String JavaDoc user, String JavaDoc password, Properties JavaDoc connInfo)
509     {
510         String JavaDoc ijGetMessages = util.getSystemProperty("ij.retrieveMessagesFromServerOnGetMessage");
511         boolean retrieveMessages = false;
512         
513         
514         // For JCC make sure we set it to retrieve messages
515
if (isJCCFramework())
516             retrieveMessages = true;
517         
518         if (ijGetMessages != null)
519         {
520             if (ijGetMessages.equals("false"))
521                 retrieveMessages = false;
522             else
523                 retrieveMessages = true;
524             
525         }
526         
527         if (connInfo == null)
528             connInfo = new Properties JavaDoc();
529         
530         if (retrieveMessages == true)
531         {
532             connInfo.put("retrieveMessagesFromServerOnGetMessage",
533                          "true");
534         }
535         if (user != null)
536             connInfo.put("user",user);
537         if (password != null)
538             connInfo.put("password", password);
539         
540         return connInfo;
541     }
542
543     /**
544         Utility interface that defaults driver and database to null.
545
546         @return a connection to the defaultURL if possible; null if not.
547         @exception SQLException on failure to connect.
548         @exception ClassNotFoundException on failure to load driver.
549         @exception InstantiationException on failure to load driver.
550         @exception IllegalAccessException on failure to load driver.
551      */

552     static public Connection JavaDoc startJBMS() throws SQLException JavaDoc, ClassNotFoundException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc {
553         return startJBMS(null,null);
554     }
555     
556     /**
557        Utility interface that defaults connInfo to null
558        <p>
559
560
561         @param defaultDriver the driver to use if no property value found
562         @param defaultURL the database URL to use if no property value found
563         @return a connection to the defaultURL if possible; null if not.
564         @exception SQLException on failure to connect.
565         @exception ClassNotFoundException on failure to load driver.
566         @exception InstantiationException on failure to load driver.
567         @exception IllegalAccessException on failure to load driver.
568      */

569     static public Connection JavaDoc startJBMS(String JavaDoc defaultDriver, String JavaDoc defaultURL)
570             throws SQLException JavaDoc, ClassNotFoundException JavaDoc, InstantiationException JavaDoc,
571                    IllegalAccessException JavaDoc {
572         return startJBMS(defaultDriver,defaultURL,null);
573         
574     }
575     //-----------------------------------------------------------------
576
// Methods for displaying and checking results
577
// See org.apache.derby.tools.JDBCDisplayUtil for more general displays.
578

579
580     /**
581         Display a vector of strings to the out stream.
582      */

583     public static void DisplayVector(LocalizedOutput out, Vector JavaDoc v) {
584         int l = v.size();
585         for (int i=0;i<l;i++)
586             out.println(v.elementAt(i));
587     }
588
589     /**
590         Display a vector of statements to the out stream.
591     public static void DisplayVector(AppStreamWriter out, Vector v, Connection conn) throws SQLException {
592         int l = v.size();
593 AppUI.out.println("SIZE="+l);
594         for (int i=0;i<l;i++) {
595             Object o = v.elementAt(i);
596             if (o instanceof Integer) { // update count
597                 JDBCDisplayUtil.DisplayUpdateCount(out,((Integer)o).intValue());
598             } else { // o instanceof ResultSet
599                 JDBCDisplayUtil.DisplayResults(out,(ResultSet)o,conn);
600                 ((ResultSet)o).close(); // release the result set
601             }
602         }
603     }
604      */

605
606     /**
607         Display a statement that takes parameters by
608         stuffing it with rows from the result set and
609         displaying each result each time through.
610         Deal with autocommit behavior along the way.
611
612         @exception SQLException thrown on db error
613         @exception ijException thrown on ij error
614      */

615     public static void DisplayMulti(LocalizedOutput out, PreparedStatement JavaDoc ps,
616         ResultSet JavaDoc rs, Connection JavaDoc conn) throws SQLException JavaDoc, ijException {
617
618         boolean autoCommited = false; // mark if autocommit in place
619
boolean exec = false; // mark the first time through
620
boolean anotherUsingRow = false; // remember if there's another row
621
// from using.
622
ResultSetMetaData JavaDoc rsmd = rs.getMetaData();
623         int numCols = rsmd.getColumnCount();
624
625         /* NOTE: We need to close the USING RS first
626          * so that RunTimeStatistic gets info from
627          * the user query.
628          */

629         anotherUsingRow = rs.next();
630
631         while (! autoCommited && anotherUsingRow) {
632             // note the first time through
633
if (!exec) {
634                 exec = true;
635
636                 // send a warning if additional results may be lost
637
if (conn.getAutoCommit()) {
638                     out.println(LocalizedResource.getMessage("IJ_IjWarniAutocMayCloseUsingResulSet"));
639                     autoCommited = true;
640                 }
641             }
642
643             // We need to make sure we pass along the scale, because
644
// setObject assumes a scale of zero (beetle 4365)
645
for (int c=1; c<=numCols; c++) {
646                 int sqlType = rsmd.getColumnType(c);
647                 
648                 if (sqlType == Types.DECIMAL)
649                 {
650                     if (util.HAVE_BIG_DECIMAL)
651                     {
652                         ps.setObject(c,rs.getObject(c),
653                                  sqlType,
654                                  rsmd.getScale(c));
655                     }
656                     else
657                     {
658                         // In J2ME there is no object that represents
659
// a DECIMAL value. By default use String to
660
// pass values around, but for integral types
661
// first convert to a integral type from the DECIMAL
662
// because strings like 3.4 are not convertible to
663
// an integral type.
664
switch (ps.getMetaData().getColumnType(c))
665                         {
666                         case Types.BIGINT:
667                             ps.setLong(c, rs.getLong(c));
668                             break;
669                         case Types.INTEGER:
670                         case Types.SMALLINT:
671                         case Types.TINYINT:
672                             ps.setInt(c, rs.getInt(c));
673                             break;
674                         default:
675                             ps.setString(c,rs.getString(c));
676                             break;
677                         }
678                     }
679                     
680                 }
681                 else
682                 {
683                     ps.setObject(c,rs.getObject(c),
684                              sqlType);
685                 }
686                 
687                 
688
689             }
690
691
692             // Advance in the USING RS
693
anotherUsingRow = rs.next();
694             // Close the USING RS when exhausted and appropriate
695
// NOTE: Close before the user query
696
if (! anotherUsingRow || conn.getAutoCommit()) //if no more rows or if auto commit is on, close the resultset
697
{
698                 rs.close();
699             }
700
701             /*
702                 4. execute the statement against those parameters
703              */

704
705             ps.execute();
706             JDBCDisplayUtil.DisplayResults(out,ps,conn);
707
708             /*
709                 5. clear the parameters
710              */

711             ps.clearParameters();
712         }
713         if (!exec) {
714             rs.close(); //this means, using clause didn't qualify any rows. Just close the resultset associated with using clause
715
throw ijException.noUsingResults();
716         }
717         // REMIND: any way to look for more rsUsing rows if autoCommit?
718
// perhaps just document the behavior...
719
}
720
721     static final String JavaDoc getSystemProperty(String JavaDoc propertyName) {
722         try
723         {
724             if (propertyName.startsWith("ij.") || propertyName.startsWith("derby."))
725             {
726                 util u = new util();
727                 u.key = propertyName;
728                 return (String JavaDoc) java.security.AccessController.doPrivileged(u);
729             }
730             else
731             {
732                 return System.getProperty(propertyName);
733             }
734         } catch (SecurityException JavaDoc se) {
735             return null;
736         }
737     }
738
739     private String JavaDoc key;
740
741     public final Object JavaDoc run() {
742         return System.getProperty(key);
743     }
744     /**
745      * Read a set of properties from the received input stream, strip
746      * off any excess white space that exists in those property values,
747      * and then add those newly-read properties to the received
748      * Properties object; not explicitly removing the whitespace here can
749      * lead to problems.
750      *
751      * This method exists because of the manner in which the jvm reads
752      * properties from file--extra spaces are ignored after a _key_, but
753      * if they exist at the _end_ of a property decl line (i.e. as part
754      * of a _value_), they are preserved, as outlined in the Java API:
755      *
756      * "Any whitespace after the key is skipped; if the first non-
757      * whitespace character after the key is = or :, then it is ignored
758      * and any whitespace characters after it are also skipped. All
759      * remaining characters on the line become part of the associated
760      * element string."
761      *
762      * Creates final properties set consisting of 'prop' plus all
763      * properties loaded from 'iStr' (with the extra whitespace (if any)
764      * removed from all values), will be returned via the parameter.
765      *
766      * @param iStr An input stream from which the new properties are to be
767      * loaded (should already be initialized).
768      * @param prop A set of properties to which the properties from
769      * iStr will be added (should already be initialized).
770      *
771      * Copied here to avoid dependency on an engine class.
772      **/

773     private static void loadWithTrimmedValues(InputStream JavaDoc iStr,
774         Properties JavaDoc prop) throws IOException JavaDoc {
775
776         // load the properties from the received input stream.
777
Properties JavaDoc p = new Properties JavaDoc();
778         p.load(iStr);
779
780         // Now, trim off any excess whitespace, if any, and then
781
// add the properties from file to the received Properties
782
// set.
783
for (java.util.Enumeration JavaDoc propKeys = p.propertyNames();
784           propKeys.hasMoreElements();) {
785         // get the value, trim off the whitespace, then store it
786
// in the received properties object.
787
String JavaDoc tmpKey = (String JavaDoc)propKeys.nextElement();
788             String JavaDoc tmpValue = p.getProperty(tmpKey);
789             tmpValue = tmpValue.trim();
790             prop.put(tmpKey, tmpValue);
791         }
792
793         return;
794
795     }
796
797     private static final String JavaDoc[][] protocolDrivers =
798         {
799           { "jdbc:derby:net:", "com.ibm.db2.jcc.DB2Driver"},
800           { "jdbc:derby://", "org.apache.derby.jdbc.ClientDriver"},
801
802           { "jdbc:derby:", "org.apache.derby.jdbc.EmbeddedDriver" },
803         };
804
805     /**
806         Find the appropriate driver and load it, given a JDBC URL.
807         No action if no driver known for a given URL.
808
809         @param jdbcProtocol the protocol to try.
810
811         @exception ClassNotFoundException if unable to
812             locate class for driver.
813         @exception InstantiationException if unable to
814             create an instance.
815         @exception IllegalAccessException if driver class constructor not visible.
816      */

817     public static void loadDriverIfKnown(String JavaDoc jdbcProtocol) throws ClassNotFoundException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc {
818         for (int i=0; i < protocolDrivers.length; i++) {
819             if (jdbcProtocol.startsWith(protocolDrivers[i][0])) {
820                 loadDriver(protocolDrivers[i][1]);
821                 break; // only want the first one
822
}
823         }
824     }
825
826     /**
827         Load a driver given a class name.
828
829         @exception ClassNotFoundException if unable to
830             locate class for driver.
831         @exception InstantiationException if unable to
832             create an instance.
833         @exception IllegalAccessException if driver class constructor not visible.
834      */

835     public static void loadDriver(String JavaDoc driverClass) throws ClassNotFoundException JavaDoc, InstantiationException JavaDoc, IllegalAccessException JavaDoc {
836         Class.forName(driverClass).newInstance();
837     }
838
839     /**
840      * Used to determine if this is a JCC testing framework
841      * So that retrieveMessages can be sent. The plan is to have
842      * ij will retrieve messages by default and not look at the testing
843      * frameworks. So, ulitmately this function will look at the driver
844      * rather than the framework.
845      *
846      * @return true if the framework contains Net or JCC.
847      */

848     private static boolean isJCCFramework()
849     {
850         String JavaDoc framework = util.getSystemProperty("framework");
851         return ((framework != null) &&
852             ((framework.toUpperCase(Locale.ENGLISH).equals("DERBYNET")) ||
853              (framework.toUpperCase(Locale.ENGLISH).indexOf("JCC") != -1)));
854     }
855     
856     /**
857      * Selects the current schema from the given connection.
858      *
859      * As there are no way of getting current schema supported by
860      * all major DBMS-es, this method may return null.
861      *
862      * @param theConnection Connection to get current schema for
863      * @return the current schema of the connection, or null if error.
864      */

865     public static String JavaDoc getSelectedSchema(Connection JavaDoc theConnection) throws SQLException JavaDoc {
866         String JavaDoc schema = null;
867                 if (theConnection == null)
868                   return null;
869         Statement JavaDoc st = theConnection.createStatement();
870         try {
871             if(!st.execute("VALUES CURRENT SCHEMA"))
872                 return null;
873             
874             ResultSet JavaDoc rs = st.getResultSet();
875             if(rs==null || !rs.next())
876                 return null;
877             schema = rs.getString(1);
878         } catch(SQLException JavaDoc e) {
879             // There are no standard way of getting schema.
880
// Getting default schema may fail.
881
} finally {
882             st.close();
883         }
884         return schema;
885     }
886 }
887
888
Popular Tags