• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 package org.apache.harmony.sql.tests.java.sql;
19 
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.PrintStream;
23 import java.io.PrintWriter;
24 import java.lang.reflect.Method;
25 import java.security.Permission;
26 import java.sql.Connection;
27 import java.sql.Driver;
28 import java.sql.DriverManager;
29 import java.sql.DriverPropertyInfo;
30 import java.sql.SQLException;
31 import java.sql.SQLPermission;
32 import java.util.Enumeration;
33 import java.util.Properties;
34 import tests.support.Support_Exec;
35 
36 import junit.framework.TestCase;
37 
38 /**
39  * JUnit Testcase for the java.sql.DriverManager class
40  */
41 public class DriverManagerTest extends TestCase {
42 
43     // Set of driver names to use
44     static final String DRIVER1 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver1";
45 
46     static final String DRIVER2 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver2";
47 
48     static final String DRIVER3 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver3";
49 
50     static final String DRIVER4 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver4";
51 
52     static final String DRIVER5 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver5";
53 
54     static final String INVALIDDRIVER1 = "abc.klm.Foo";
55 
56     static String[] driverNames = { DRIVER1, DRIVER2, DRIVER4, DRIVER5 };
57 
58     static int numberLoaded;
59 
60     static String baseURL1 = "jdbc:mikes1";
61 
62     static String baseURL4 = "jdbc:mikes4";
63 
64     static final String JDBC_PROPERTY = "jdbc.drivers";
65 
66     static TestHelper_ClassLoader testClassLoader = new TestHelper_ClassLoader();
67 
68     // Static initializer to load the drivers so that they are available to all
69     // the
70     // test methods as needed.
71     @Override
setUp()72     public void setUp() {
73         numberLoaded = loadDrivers();
74     } // end setUp()
75 
76     /**
77      * Test for the method DriverManager.deregisterDriver
78      *
79      * @throws SQLException
80      */
testDeregisterDriver()81     public void testDeregisterDriver() throws Exception {
82         // First get one of the drivers loaded by the test
83         Driver aDriver;
84         aDriver = DriverManager.getDriver(baseURL4);
85 
86         // Deregister this driver
87         DriverManager.deregisterDriver(aDriver);
88 
89         assertFalse("testDeregisterDriver: Driver was not deregistered.",
90                 isDriverLoaded(aDriver));
91 
92         // Re-register this driver (so subsequent tests have it available)
93         DriverManager.registerDriver(aDriver);
94         assertTrue("testDeregisterDriver: Driver did not reload.",
95                 isDriverLoaded(aDriver));
96 
97         // Test deregistering a null driver
98         DriverManager.deregisterDriver(null);
99 
100         // Test deregistering a driver which was not loaded by this test's
101         // classloader
102         // TODO - need to load a driver with a different classloader!!
103         aDriver = DriverManager.getDriver(baseURL1);
104 
105         Class<?> driverClass = Class
106                 .forName(
107                         "org.apache.harmony.sql.tests.java.sql.TestHelper_DriverManager",
108                         true, testClassLoader);
109 
110         // Give the Helper class one of our drivers....
111         Class<?>[] methodClasses = { Class.forName("java.sql.Driver") };
112         Method theMethod = driverClass.getDeclaredMethod("setDriver",
113                 methodClasses);
114         Object[] args = { aDriver };
115         theMethod.invoke(null, args);
116 
117         // Check that the driver was not deregistered
118         assertTrue(
119                 "testDeregisterDriver: Driver was incorrectly deregistered.",
120                 DriverManagerTest.isDriverLoaded(aDriver));
121 
122     } // end method testDeregisterDriver()
123 
printClassLoader(Object theObject)124     static void printClassLoader(Object theObject) {
125         Class<? extends Object> theClass = theObject.getClass();
126         ClassLoader theClassLoader = theClass.getClassLoader();
127         System.out.println("ClassLoader is: " + theClassLoader.toString()
128                 + " for object: " + theObject.toString());
129     } // end method printClassLoader( Object )
130 
isDriverLoaded(Driver theDriver)131     static boolean isDriverLoaded(Driver theDriver) {
132         Enumeration<?> driverList = DriverManager.getDrivers();
133         while (driverList.hasMoreElements()) {
134             if ((Driver) driverList.nextElement() == theDriver) {
135                 return true;
136             }
137         } // end while
138         return false;
139     } // end method isDriverLoaded( Driver )
140 
141     /*
142      * Class under test for Connection getConnection(String)
143      */
144     // valid connection - data1 does not require a user and password...
145     static String validConnectionURL = "jdbc:mikes1:data1";
146 
147     // invalid connection - data2 requires a user & password
148     static String invalidConnectionURL1 = "jdbc:mikes1:data2";
149 
150     // invalid connection - URL is gibberish
151     static String invalidConnectionURL2 = "xyz1:abc3:456q";
152 
153     // invalid connection - URL is null
154     static String invalidConnectionURL3 = null;
155 
156     static String[] invalidConnectionURLs = { invalidConnectionURL2,
157             invalidConnectionURL3 };
158 
testGetConnectionString()159     public void testGetConnectionString() throws SQLException {
160         Connection theConnection = null;
161         // validConnection - no user & password required
162         theConnection = DriverManager.getConnection(validConnectionURL);
163         assertNotNull(theConnection);
164         assertNotNull(DriverManager.getConnection(invalidConnectionURL1));
165 
166         for (String element : invalidConnectionURLs) {
167             try {
168                 theConnection = DriverManager.getConnection(element);
169                 fail("Should throw SQLException");
170             } catch (SQLException e) {
171                 // expected
172             } // end try
173         } // end for
174     } // end method testGetConnectionString()
175 
176     /**
177      * @tests java.sql.DriverManager#getConnection(String, Properties)
178      */
test_getConnection_LStringLProperties()179     public void test_getConnection_LStringLProperties() {
180         try {
181             DriverManager.getConnection("fff", //$NON-NLS-1$
182                     new Properties());
183             fail("Should throw SQLException.");
184         } catch (SQLException e) {
185             assertEquals("08001", e.getSQLState()); //$NON-NLS-1$
186         }
187 
188         try {
189             DriverManager.getConnection(null, new Properties());
190             fail("Should throw SQLException.");
191         } catch (SQLException e) {
192             assertEquals("08001", e.getSQLState()); //$NON-NLS-1$
193         }
194     }
195 
196     /*
197      * Class under test for Connection getConnection(String, Properties)
198      */
testGetConnectionStringProperties()199     public void testGetConnectionStringProperties() throws SQLException {
200         String validURL1 = "jdbc:mikes1:data2";
201         String validuser1 = "theuser";
202         String validpassword1 = "thepassword";
203         String invalidURL1 = "xyz:abc1:foo";
204         String invalidURL2 = "jdbc:mikes1:crazyone";
205         String invalidURL3 = "";
206         String invaliduser1 = "jonny nouser";
207         String invalidpassword1 = "whizz";
208         Properties nullProps = null;
209         Properties validProps = new Properties();
210         validProps.setProperty("user", validuser1);
211         validProps.setProperty("password", validpassword1);
212         Properties invalidProps1 = new Properties();
213         invalidProps1.setProperty("user", invaliduser1);
214         invalidProps1.setProperty("password", invalidpassword1);
215         String[] invalidURLs = { null, invalidURL1, invalidURL2, invalidURL3 };
216         Properties[] invalidProps = { nullProps, invalidProps1 };
217 
218         Connection theConnection = null;
219         // validConnection - user & password required
220         theConnection = DriverManager.getConnection(validURL1, validProps);
221         assertNotNull(theConnection);
222 
223         // invalid Connections
224         for (int i = 0; i < invalidURLs.length; i++) {
225             theConnection = null;
226             try {
227                 theConnection = DriverManager.getConnection(invalidURLs[i],
228                         validProps);
229                 fail("Should throw SQLException");
230             } catch (SQLException e) {
231                 // expected
232             } // end try
233         } // end for
234         for (Properties invalidProp : invalidProps) {
235             assertNotNull(DriverManager.getConnection(validURL1, invalidProp));
236         }
237     } // end method testGetConnectionStringProperties()
238 
239     /*
240      * Class under test for Connection getConnection(String, String, String)
241      */
testGetConnectionStringStringString()242     public void testGetConnectionStringStringString() throws SQLException {
243         String validURL1 = "jdbc:mikes1:data2";
244         String validuser1 = "theuser";
245         String validpassword1 = "thepassword";
246         String invalidURL1 = "xyz:abc1:foo";
247         String invaliduser1 = "jonny nouser";
248         String invalidpassword1 = "whizz";
249         String[] invalid1 = { null, validuser1, validpassword1 };
250         String[] invalid2 = { validURL1, null, validpassword1 };
251         String[] invalid3 = { validURL1, validuser1, null };
252         String[] invalid4 = { invalidURL1, validuser1, validpassword1 };
253         String[] invalid5 = { validURL1, invaliduser1, invalidpassword1 };
254         String[] invalid6 = { validURL1, validuser1, invalidpassword1 };
255         String[][] invalids1 = { invalid1, invalid4 };
256         String[][] invalids2 = { invalid2, invalid3, invalid5, invalid6 };
257 
258         Connection theConnection = null;
259         // validConnection - user & password required
260         theConnection = DriverManager.getConnection(validURL1, validuser1,
261                 validpassword1);
262         assertNotNull(theConnection);
263         for (String[] theData : invalids1) {
264             theConnection = null;
265             try {
266                 theConnection = DriverManager.getConnection(theData[0],
267                         theData[1], theData[2]);
268                 fail("Should throw SQLException.");
269             } catch (SQLException e) {
270                 // expected
271             } // end try
272         } // end for
273         for (String[] theData : invalids2) {
274             assertNotNull(DriverManager.getConnection(theData[0], theData[1],
275                     theData[2]));
276         }
277     } // end method testGetConnectionStringStringString()
278 
279     static String validURL1 = "jdbc:mikes1";
280 
281     static String validURL2 = "jdbc:mikes2";
282 
283     static String invalidURL1 = "xyz:acb";
284 
285     static String invalidURL2 = null;
286 
287     static String[] validURLs = { validURL1, validURL2 };
288 
289     static String[] invalidURLs = { invalidURL1, invalidURL2 };
290 
291     static String exceptionMsg1 = "No suitable driver";
292 
testGetDriver()293     public void testGetDriver() throws SQLException {
294         for (String element : validURLs) {
295             Driver validDriver = DriverManager.getDriver(element);
296             assertNotNull(validDriver);
297         } // end for
298 
299 //      Comment out since it depends on the drivers providered
300 //        for (String element : invalidURLs) {
301 //            System.out.println(element);
302 //            try {
303 //                DriverManager.getDriver(element);
304 //                fail("Should throw SQLException");
305 //            } catch (SQLException e) {
306 //                assertEquals("08001", e.getSQLState());
307 //                assertEquals(exceptionMsg1, e.getMessage());
308 //            } // end try
309 //        } // end for
310 
311     } // end method testGetDriver()
312 
testGetDrivers()313     public void testGetDrivers() {
314         // Load a driver manager
315         Enumeration<Driver> driverList = DriverManager.getDrivers();
316         int i = 0;
317         while (driverList.hasMoreElements()) {
318             Driver theDriver = driverList.nextElement();
319             assertNotNull(theDriver);
320             i++;
321         } // end while
322 
323         // Check that all the drivers are in the list...
324         // There might be other drivers loaded in other classes
325         assertTrue("testGetDrivers: Don't see all the loaded drivers - ",
326                 i >= numberLoaded);
327     } // end method testGetDrivers()
328 
329     static int timeout1 = 25;
330 
testGetLoginTimeout()331     public void testGetLoginTimeout() {
332         DriverManager.setLoginTimeout(timeout1);
333         assertEquals(timeout1, DriverManager.getLoginTimeout());
334     } // end method testGetLoginTimeout()
335 
336     @SuppressWarnings("deprecation")
testGetLogStream()337     public void testGetLogStream() {
338         assertNull(DriverManager.getLogStream());
339 
340         DriverManager.setLogStream(testPrintStream);
341         assertTrue(DriverManager.getLogStream() == testPrintStream);
342 
343         DriverManager.setLogStream(null);
344     } // end method testGetLogStream()
345 
testGetLogWriter()346     public void testGetLogWriter() {
347         assertNull(DriverManager.getLogWriter());
348 
349         DriverManager.setLogWriter(testPrintWriter);
350 
351         assertTrue(DriverManager.getLogWriter() == testPrintWriter);
352 
353         DriverManager.setLogWriter(null);
354     } // end method testGetLogWriter()
355 
356     static String testMessage = "DriverManagerTest: test message for print stream";
357 
358     @SuppressWarnings("deprecation")
testPrintln()359     public void testPrintln() {
360         // System.out.println("testPrintln");
361         DriverManager.println(testMessage);
362 
363         DriverManager.setLogWriter(testPrintWriter);
364         DriverManager.println(testMessage);
365 
366         String theOutput = outputStream.toString();
367         // System.out.println("testPrintln: output= " + theOutput );
368         assertTrue(theOutput.startsWith(testMessage));
369 
370         DriverManager.setLogWriter(null);
371 
372         DriverManager.setLogStream(testPrintStream);
373         DriverManager.println(testMessage);
374 
375         theOutput = outputStream2.toString();
376         // System.out.println("testPrintln: output= " + theOutput );
377         assertTrue(theOutput.startsWith(testMessage));
378 
379         DriverManager.setLogStream(null);
380     } // end method testPrintln()
381 
testRegisterDriver()382     public void testRegisterDriver() throws ClassNotFoundException,
383             SQLException, IllegalAccessException, InstantiationException {
384         String EXTRA_DRIVER_NAME = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver3";
385 
386         try {
387             DriverManager.registerDriver(null);
388             fail("Should throw NullPointerException.");
389         } catch (NullPointerException e) {
390             // expected
391         } // end try
392 
393         Driver theDriver = null;
394         // Load another Driver that isn't in the basic set
395         Class<?> driverClass = Class.forName(EXTRA_DRIVER_NAME);
396         theDriver = (Driver) driverClass.newInstance();
397         DriverManager.registerDriver(theDriver);
398 
399         assertTrue("testRegisterDriver: driver not in loaded set",
400                 isDriverLoaded(theDriver));
401 
402     } // end testRegisterDriver()
403 
404     static int validTimeout1 = 15;
405 
406     static int validTimeout2 = 0;
407 
408     static int[] validTimeouts = { validTimeout1, validTimeout2 };
409 
410     static int invalidTimeout1 = -10;
411 
testSetLoginTimeout()412     public void testSetLoginTimeout() {
413         for (int element : validTimeouts) {
414             DriverManager.setLoginTimeout(element);
415 
416             assertEquals(element, DriverManager.getLoginTimeout());
417         } // end for
418         // Invalid timeouts
419         DriverManager.setLoginTimeout(invalidTimeout1);
420         assertEquals(invalidTimeout1, DriverManager.getLoginTimeout());
421     } // end testSetLoginTimeout()
422 
423     static ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
424 
425     static PrintStream testPrintStream = new PrintStream(outputStream2);
426 
427     @SuppressWarnings("deprecation")
testSetLogStream()428     public void testSetLogStream() {
429         // System.out.println("testSetLogStream");
430         DriverManager.setLogStream(testPrintStream);
431 
432         assertSame(testPrintStream, DriverManager.getLogStream());
433 
434         DriverManager.setLogStream(null);
435 
436         assertNull(DriverManager.getLogStream());
437     } // end method testSetLogStream()
438 
439     static ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
440 
441     static PrintWriter testPrintWriter = new PrintWriter(outputStream);
442 
443     /**
444      * Test for the setLogWriter method
445      */
testSetLogWriter()446     public void testSetLogWriter() {
447         // System.out.println("testSetLogWriter");
448         DriverManager.setLogWriter(testPrintWriter);
449 
450         assertSame(testPrintWriter, DriverManager.getLogWriter());
451 
452         DriverManager.setLogWriter(null);
453 
454         assertNull("testDriverManager: Log writer not null:", DriverManager
455                 .getLogWriter());
456     } // end method testSetLogWriter()
457 
458     /*
459      * Method which loads a set of JDBC drivers ready for use by the various
460      * tests @return the number of drivers loaded
461      */
462     static boolean driversLoaded = false;
463 
loadDrivers()464     private static int loadDrivers() {
465         if (driversLoaded) {
466             return numberLoaded;
467         }
468         /*
469          * First define a value for the System property "jdbc.drivers" - before
470          * the DriverManager class is loaded - this property defines a set of
471          * drivers which the DriverManager will load during its initialization
472          * and which will be loaded on the System ClassLoader - unlike the ones
473          * loaded later by this method which are loaded on the Application
474          * ClassLoader.
475          */
476         int numberLoaded = 0;
477 
478         for (String element : driverNames) {
479             try {
480                 Class<?> driverClass = Class.forName(element);
481                 assertNotNull(driverClass);
482                 // System.out.println("Loaded driver - classloader = " +
483                 // driverClass.getClassLoader());
484                 numberLoaded++;
485             } catch (ClassNotFoundException e) {
486                 System.out.println("DriverManagerTest: failed to load Driver: "
487                         + element);
488             } // end try
489         } // end for
490         /*
491          * System.out.println("DriverManagerTest: number of drivers loaded: " +
492          * numberLoaded);
493          */
494         driversLoaded = true;
495         return numberLoaded;
496     } // end method loadDrivers()
497 
498     /**
499      * @tests {@link java.sql.DriverManager#registerDriver(Driver)}
500      * <p/>
501      * Registers a driver for multiple times and deregisters it only once.
502      * <p/>
503      * Regression for HARMONY-4205
504      */
test_registerDriver_MultiTimes()505     public void test_registerDriver_MultiTimes() throws SQLException {
506         int register_count = 10;
507         int deregister_count = 1;
508 
509         Driver dummy = new DummyDriver();
510         DriverManager.registerDriver(new BadDummyDriver());
511         for (int i = 0; i < register_count; i++) {
512             DriverManager.registerDriver(dummy);
513         }
514         DriverManager.registerDriver(new BadDummyDriver());
515         for (int i = 0; i < deregister_count; i++) {
516             DriverManager.deregisterDriver(dummy);
517         }
518         Driver d = DriverManager.getDriver("jdbc:dummy_protocol:dummy_subname");
519         assertNotNull(d);
520     }
521 
522     /**
523      * Regression for HARMONY-4303
524      */
test_initClass()525     public void test_initClass() throws Exception {
526         String[] arg = new String[1];
527         arg[0] = "org/apache/harmony/sql/tests/java/sql/TestMainForDriver";
528         String result = Support_Exec.execJava(arg, null, true);
529         assertEquals("", result);
530     }
531 
532     private static class BadDummyDriver extends DummyDriver {
acceptsURL(String url)533         public boolean acceptsURL(String url) {
534             return false;
535         }
536     }
537 
538     private static class DummyDriver implements Driver {
539 
540         String goodurl = "jdbc:dummy_protocol:dummy_subname";
541 
acceptsURL(String url)542         public boolean acceptsURL(String url) {
543             return url.equals(goodurl);
544         }
545 
connect(String url, Properties info)546         public Connection connect(String url, Properties info) {
547             return null;
548         }
549 
getPropertyInfo(String url, Properties info)550         public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) {
551             return null;
552         }
553 
getMajorVersion()554         public int getMajorVersion() {
555             return 0;
556         }
557 
getMinorVersion()558         public int getMinorVersion() {
559             return 0;
560         }
561 
jdbcCompliant()562         public boolean jdbcCompliant() {
563             return true;
564         }
565 
566     }
567 
568 } // end class DriverManagerTest
569