KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derbyTesting > functionTests > tests > jdbcapi > checkDriver


1 /*
2
3 Derby - Class org.apache.derby.jdbc.EmbeddedDriver
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.derbyTesting.functionTests.tests.jdbcapi;
23 import org.apache.derbyTesting.functionTests.util.TestUtil;
24
25 import java.io.File JavaDoc;
26 import java.sql.DatabaseMetaData JavaDoc;
27 import java.sql.Driver JavaDoc;
28 import java.sql.DriverManager JavaDoc;
29 import java.sql.Connection JavaDoc;
30 import java.sql.ResultSet JavaDoc;
31 import java.sql.SQLException JavaDoc;
32 import java.util.Properties JavaDoc;
33 import org.apache.derby.tools.JDBCDisplayUtil;
34
35 /**
36  * @author marsden
37  *
38  * This test tests java.sql.Driver methods.
39  * Right now it just tests acceptsURL and some attributes
40  * Tests for getPropertyInfo need to be added. as well as connection attributes
41  *
42  */

43
44 public class checkDriver {
45
46     private static String JavaDoc hostName;
47     private static String JavaDoc EMBEDDED_URL = "jdbc:derby:wombat;create=true";
48     private static String JavaDoc CLIENT_URL;
49     private static String JavaDoc JCC_URL;
50     private static String JavaDoc INVALID_URL = "jdbc:db2j:wombat;create=true";
51     
52     private static String JavaDoc DERBY_SYSTEM_HOME = System.getProperty("derby.system.home");
53     
54     private static String JavaDoc CLIENT_URL_WITH_COLON1;
55     private static String JavaDoc CLIENT_URL_WITH_COLON2;
56     private static String JavaDoc CLIENT_URL_WITH_DOUBLE_QUOTES1;
57     private static String JavaDoc CLIENT_URL_WITH_DOUBLE_QUOTES2;
58     private static String JavaDoc CLIENT_URL_WITH_SINGLE_QUOTES1;
59     private static String JavaDoc CLIENT_URL_WITH_SINGLE_QUOTES2;
60     
61     // DERBY-618 - Database name with spaces
62
private static String JavaDoc DB_NAME_WITH_SPACES = "db name with spaces";
63     private static String JavaDoc EMBEDDED_URL_WITH_SPACES = "jdbc:derby:" +
64                                         DB_NAME_WITH_SPACES + ";create=true";
65     private static String JavaDoc CLIENT_URL_WITH_SPACES;
66     private static String JavaDoc JCC_URL_WITH_SPACES;
67     
68     /**
69      * url prefix for this framework
70      */

71     private static String JavaDoc frameworkPrefix;
72     
73     // The acceptsURLTable uses the frameworkOffset column int he table
74
// to check for valid results for each framework
75
private static int frameworkOffset;
76     
77     private static int EMBEDDED_OFFSET = 0;
78     private static int DERBYNETCLIENT_OFFSET = 1;
79     private static int DERBYNET_OFFSET = 2; // JCC
80

81     static {
82         frameworkPrefix = TestUtil.getJdbcUrlPrefix();
83         if (TestUtil.isEmbeddedFramework())
84             frameworkOffset = EMBEDDED_OFFSET;
85         else if (TestUtil.isDerbyNetClientFramework())
86             frameworkOffset = DERBYNETCLIENT_OFFSET;
87         else if (TestUtil.isJCCFramework())
88             frameworkOffset = DERBYNET_OFFSET; // JCC
89

90         hostName = TestUtil.getHostName();
91         CLIENT_URL = "jdbc:derby://" + hostName + ":1527/wombat;create=true";
92         JCC_URL = "jdbc:derby:net://" + hostName + ":1527/wombat;create=true";
93         CLIENT_URL_WITH_COLON1 = "jdbc:derby://" + hostName + ":1527/wombat:create=true";
94         CLIENT_URL_WITH_COLON2 = "jdbc:derby://" + hostName + ":1527/"+ DERBY_SYSTEM_HOME + File.separator +"wombat:create=true";
95         CLIENT_URL_WITH_DOUBLE_QUOTES1 = "jdbc:derby://" + hostName + ":1527/\"wombat\";create=true";
96         CLIENT_URL_WITH_DOUBLE_QUOTES2 = "jdbc:derby://" + hostName + ":1527/\"" + DERBY_SYSTEM_HOME + File.separator + "wombat\";create=true";
97         CLIENT_URL_WITH_SINGLE_QUOTES1 = "jdbc:derby://" + hostName + ":1527/'" + DERBY_SYSTEM_HOME + File.separator + "wombat';create=true";
98         CLIENT_URL_WITH_SINGLE_QUOTES2 = "jdbc:derby://" + hostName + ":1527/'wombat';create=true";
99         
100         CLIENT_URL_WITH_SPACES = "jdbc:derby://" + hostName + ":1527/" + DB_NAME_WITH_SPACES + ";create=true";
101         JCC_URL_WITH_SPACES = "jdbc:derby:net://" + hostName + ":1527/" + DB_NAME_WITH_SPACES + ";create=true";
102     }
103
104     // URLS to check. New urls need to also be added to the acceptsUrl table
105
private static String JavaDoc[] urls = new String JavaDoc[]
106     {
107         EMBEDDED_URL,
108         CLIENT_URL,
109         JCC_URL,
110         INVALID_URL,
111     };
112         
113     //Client URLS
114
private static String JavaDoc[] clientUrls = new String JavaDoc[]
115     {
116         CLIENT_URL_WITH_COLON1,
117         //CLIENT_URL_WITH_COLON2,
118
//CLIENT_URL_WITH_DOUBLE_QUOTES1,
119
//CLIENT_URL_WITH_DOUBLE_QUOTES2,
120
//CLIENT_URL_WITH_SINGLE_QUOTES1,
121
CLIENT_URL_WITH_SINGLE_QUOTES2
122     };
123     
124     
125     // Table that shows whether tested urls should return true for acceptsURL
126
// under the given framework
127
private static boolean[][] acceptsURLTable = new boolean[][]
128     {
129     // Framework/url EMBEDDED DERBYNETCLIENT DERBYNET (JCC)
130
/*EMBEDDED_URL */ { true , false , false },
131     /*CLIENT_URL */ { false , true , false },
132     /* JCC_URL */ { false , false , true },
133     /* INVALID_URL */ { false , false , false }
134     };
135
136             
137
138     public static void main(String JavaDoc[] args) {
139         
140         try {
141             Driver JavaDoc driver = loadAndCheckDriverForFramework();
142             checkAcceptsURL(driver);
143             testEmbeddedAttributes(driver);
144             testClientAttributes(driver);
145             doClientURLTest(driver);
146             testDbNameWithSpaces(driver);
147         }
148         catch (SQLException JavaDoc se)
149         {
150             while (se != null)
151             {
152                 se.printStackTrace(System.out);
153                 se = se.getNextException();
154             }
155         }
156         catch (Throwable JavaDoc e)
157         {
158             e.printStackTrace(System.out);
159         }
160         
161     }
162     
163
164     /**
165      * Tests that client side attributes cann be specified in either url or info argument to connect.
166      * DERBY"-530.
167      *
168      * TODO: Add more comprehensive client attribute testing and enhance to handle jcc attributes in url.
169      *
170      * @param driver
171      */

172     private static void testClientAttributes(Driver JavaDoc driver) throws SQLException JavaDoc
173     {
174         if (!TestUtil.isDerbyNetClientFramework())
175             return;
176         
177         System.out.println("\ntestClientAttributes()");
178         Properties JavaDoc info = new Properties JavaDoc();
179
180         // Note: we have to put the trace file in an absolute path because the
181
// test harness sets user.dir and this confuses the File api greatly.
182
// We put it in DERBY_SYSTEM_HOME since that is always available when
183
// tests are run
184
String JavaDoc traceDirectory = DERBY_SYSTEM_HOME
185             + File.separator;
186         String JavaDoc traceFile= traceDirectory + "trace.out";
187         
188         // traceFile attribute in url
189
testConnect(driver, frameworkPrefix + "testpropdb;traceFile=" +
190                     traceFile,info);
191         assertTraceFileExists(traceFile);
192         
193         traceFile = traceDirectory + "trace2.out";
194         
195         // traceFile attribute in property
196
info.setProperty("traceFile",traceFile);
197         testConnect(driver, frameworkPrefix + "testpropdb",info);
198         assertTraceFileExists(traceFile);
199
200     }
201
202
203
204     /**
205      * Check that trace file exists in <framework> directory
206      *
207      * @param filename Name of trace file
208      */

209     private static void assertTraceFileExists(String JavaDoc filename)
210     {
211         File JavaDoc traceFile = new File JavaDoc(filename);
212         //System.out.println("user.dir=" + System.getProperty("user.dir"));
213
//System.out.println("fullpath = " + traceFile.getAbsolutePath());
214
boolean exists = traceFile.exists();
215         if (! exists)
216             new Exception JavaDoc("FAILED trace file: " + filename + " does not exist").printStackTrace(System.out);
217         else
218             System.out.println(" trace file exists");
219             
220     }
221
222
223     /**
224      * Tests that embedded attributes can be specified in either url or info argument to connect
225      * DERBY-530. Only valid for emebedded driver and client. JCC has a different url format for
226      * embedded attributes
227      *
228      * @param driver
229      */

230     private static void testEmbeddedAttributes(Driver JavaDoc driver) throws SQLException JavaDoc
231     {
232         // JCC can't take embedded attributes in info or as normal url attributes,
233
// so not tested here.
234
if (TestUtil.isJCCFramework())
235             return;
236         
237         System.out.println("\ntestEmbeddedAttributes()");
238         Properties JavaDoc info = new Properties JavaDoc();
239         // create attribute as property
240
info.setProperty("create","true");
241         testConnect(driver, frameworkPrefix + "testcreatedb1", info);
242         
243         // create attribute in url
244
testConnect(driver, frameworkPrefix + "testcreatedb2;create=true", null);
245         
246         // user/password in properties
247
// testpropdb was created in load and test driver
248
info.clear();
249         info.setProperty("user","APP");
250         info.setProperty("password", "xxxx");
251         testConnect(driver, frameworkPrefix + "testpropdb", info);
252         
253         // user/password in url
254
testConnect(driver, frameworkPrefix + "testpropdb;user=testuser;password=testpass", null);
255         
256         // user in url, password in property
257
info.clear();
258         info.setProperty("password","testpass");
259         testConnect(driver,frameworkPrefix + "testpropdb;user=testusr",info);
260
261         // different users in url and in properties. URL is the winner
262
info.clear();
263         info.setProperty("user","APP");
264         info.setProperty("password","xxxx");
265         testConnect(driver, frameworkPrefix + "testpropdb;user=testuser;password=testpass", null);
266         
267         // shutdown with properties
268
info.clear();
269         info.setProperty("shutdown","true");
270         try {
271             testConnect(driver,frameworkPrefix + "testcreatedb1", info);
272         } catch (SQLException JavaDoc se)
273         {
274             System.out.println("Expected Exception:" + se.getSQLState() + ":" + se.getMessage());
275         }
276     }
277         
278
279     /**
280      * Check that drivers accept the correct urls and reject those for other supported drivers.
281      *
282      * @param driver driver we are testing.
283      *
284      * @throws SQLException
285      */

286     private static void checkAcceptsURL(Driver JavaDoc driver) throws SQLException JavaDoc{
287         for (int u = 0; u < urls.length;u++)
288         {
289             String JavaDoc url = urls[u];
290             //System.out.println("acceptsURLTable[" + u +"][" + frameworkOffset+ "]");
291
boolean expectedAcceptance = acceptsURLTable[u][frameworkOffset];
292             boolean actualAcceptance = driver.acceptsURL(url);
293             System.out.println("checking acceptsURL(" + url + ")" );
294             assertExpectedURLAcceptance(url, expectedAcceptance, actualAcceptance);
295                     
296         }
297         
298     }
299
300
301     /**
302      * Load the driver and check java.sql.Driver methods,
303      * @return
304      * @throws Exception
305      */

306     private static Driver JavaDoc loadAndCheckDriverForFramework() throws Exception JavaDoc
307     {
308         TestUtil.loadDriver();
309         String JavaDoc frameworkURL = TestUtil.getJdbcUrlPrefix() + "testpropdb;create=true";
310         
311         // Test that we loaded the right driver by making a connection
312
Driver JavaDoc driver = DriverManager.getDriver(frameworkURL);
313         Properties JavaDoc props = new Properties JavaDoc();
314         props.put("user","testuser");
315         props.put("password","testpass");
316         Connection JavaDoc conn = DriverManager.getConnection(frameworkURL, props);
317         DatabaseMetaData JavaDoc dbmd = conn.getMetaData();
318         System.out.println("jdbcCompliant() = " + driver.jdbcCompliant());
319         
320         // Just check versions against database metadata to avoid more master updates.
321
// Metadata test prints the actual version.
322

323         int majorVersion = driver.getMajorVersion();
324         if (majorVersion == dbmd.getDriverMajorVersion())
325             System.out.println("driver.getMajorVersion() = EXPECTED VERSION");
326         else
327             new Exception JavaDoc("FAILED: unexpected value for getMajorVersion(): " +
328                         majorVersion).printStackTrace();
329         
330         int minorVersion = driver.getMinorVersion();
331         if (minorVersion == dbmd.getDriverMinorVersion())
332             System.out.println("driver.getMinorVersion() = EXPECTED VERSION");
333         else
334             new Exception JavaDoc("FAILED: unexpected value for getMinorVersion()" +
335                     minorVersion).printStackTrace(System.out);
336         
337         conn.close();
338         return driver;
339     }
340         
341
342     
343     
344     /**
345      * Check the actual return value of acceptsURL against the expected value and error and stack
346      * trace if they don't match
347      *
348      * @param url URL that was checked for acceptsURL
349      * @param expectedAcceptance expected return value
350      * @param actualAcceptance actual return value
351      *
352      */

353     private static void assertExpectedURLAcceptance(String JavaDoc url, boolean expectedAcceptance,
354                 boolean actualAcceptance)
355     {
356         if (actualAcceptance != expectedAcceptance)
357         {
358             new Exception JavaDoc("FAILED acceptsURL check. url = " + url +
359                            " expectedAcceptance = " + expectedAcceptance +
360                            " actualAcceptance = " + actualAcceptance).printStackTrace(System.out);
361         }
362
363     }
364     
365     /**
366      * Tests client URLs to see connection is successful or the correct exception is thrown.
367      *
368      * @param driver
369      * @throws SQLException
370      */

371     private static void doClientURLTest(Driver JavaDoc driver){
372         if (!TestUtil.isDerbyNetClientFramework())
373             return;
374         
375         System.out.println("doClientURLTest()");
376         Properties JavaDoc info = null; //test with null Properties object
377

378         for (int i = 0; i < clientUrls.length;i++)
379         {
380             String JavaDoc url = clientUrls[i];
381             System.out.println("doClientURLTest with url: " + replaceSystemHome(url));
382             try{
383                 Connection JavaDoc conn = testConnect(driver,url,info);
384                 if(conn != null)
385                     System.out.println("PASSED:Connection Successful with url: " + replaceSystemHome(url) );
386             }
387             catch(SQLException JavaDoc se){
388                 System.out.println("EXPECTED EXCEPTION:"+replaceSystemHome(se.getMessage()));
389             }
390         }
391     }
392     
393     /**
394      * Tests URL with spaces in database name to check create and connect works.
395      * (DERBY-618). Make sure that the specified database gets created. We need
396      * to check this because even without the patch for DERBY-618, no exception
397      * gets thrown when we try to connect to a database name with spaces.
398      * Instead, client driver extracts the database name as the string before
399      * the first occurence of space separator. Hence the database which gets
400      * created is wrong. e.g, if we specified database name as
401      * "db name with spaces", the database that got created by client driver
402      * was "db", which was wrong. We can check this by checking the correct URL
403      * is returned by call to conn.getMetaData().getURL(). This is currently
404      * checked inside the testConnect method. We do not explicilty check the
405      * database directory creation since this check fails in remote server
406      * testing.
407      *
408      * @param driver
409      * @throws SQLException
410      */

411     private static void testDbNameWithSpaces(Driver JavaDoc driver) throws SQLException JavaDoc {
412         System.out.println("START testDbNameWithSpaces ...");
413         
414         Connection JavaDoc conn = null;
415         Properties JavaDoc info = null;
416         String JavaDoc url = null;
417         
418         if(TestUtil.isEmbeddedFramework())
419             url = EMBEDDED_URL_WITH_SPACES;
420         else if(TestUtil.isDerbyNetClientFramework())
421             url = CLIENT_URL_WITH_SPACES;
422         else if(TestUtil.isJCCFramework()) {
423             url = JCC_URL_WITH_SPACES;
424             // JCC requires user and password
425
info = new Properties JavaDoc();
426             info.put("user", "tester");
427             info.put("password", "testpass");
428         }
429         
430         conn = testConnect(driver, url, info);
431         if(conn != null)
432             System.out.println("PASSED:Connection Successful with url: " + url );
433     }
434     
435     /**
436      * Make java.sql.Driver.connect(String url, Properties info call) and print the status of
437      * the connection.
438      *
439      * @param driver driver for framework
440      * @param url url to pass to Driver.connect()
441      * @param info properties to pass to Driver.Connect()
442      *
443      * @throws SQLException on error.
444      */

445     private static Connection JavaDoc testConnect(Driver JavaDoc driver, String JavaDoc url, Properties JavaDoc info) throws SQLException JavaDoc
446     {
447         String JavaDoc infoString = null;
448         if (info != null)
449             infoString = replaceSystemHome(info.toString());
450         String JavaDoc urlString = replaceSystemHome(url);
451         Connection JavaDoc conn = driver.connect(url,info);
452         
453         if(conn == null){
454             System.out.println("Null connection returned for url "+urlString);
455             return conn;
456         }
457         
458         System.out.println("\nConnection info for connect(" + urlString + ", " + infoString +")");
459         String JavaDoc getUrlValue = conn.getMetaData().getURL();
460         // URL may include path of DERBY_SYSTEM_HOME for traceFile
461
// filter it out.
462
getUrlValue = replaceSystemHome(getUrlValue);
463         System.out.println("getURL() = " + getUrlValue);
464         System.out.println("getUserName() = " + conn.getMetaData().getUserName());
465         // CURRENT SCHEMA should match getUserName()
466
ResultSet JavaDoc rs = conn.createStatement().executeQuery("VALUES(CURRENT SCHEMA)");
467         rs.next();
468         System.out.println("CURRENT SCHEMA = " + rs.getString(1));
469         conn.close();
470         return conn;
471     }
472
473
474     /**
475      * @param origString
476      *
477      * @return origString with derby.system.home path replaed with [DERBY_SYSTEM_HOME]
478      */

479     private static String JavaDoc replaceSystemHome(String JavaDoc origString) {
480         String JavaDoc replaceString = DERBY_SYSTEM_HOME + File.separator;
481         int offset = origString.indexOf(replaceString);
482         if (offset == -1)
483             return origString;
484         else
485             return origString.substring(0,offset) + "[DERBY_SYSTEM_HOME]/"+
486             origString.substring(offset + replaceString.length());
487     }
488     
489 }
Popular Tags