001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017:
018: package org.apache.harmony.sql.tests.java.sql;
019:
020: import java.io.ByteArrayOutputStream;
021: import java.io.IOException;
022: import java.io.PrintStream;
023: import java.io.PrintWriter;
024: import java.lang.reflect.Method;
025: import java.security.Permission;
026: import java.sql.Connection;
027: import java.sql.Driver;
028: import java.sql.DriverManager;
029: import java.sql.DriverPropertyInfo;
030: import java.sql.SQLException;
031: import java.sql.SQLPermission;
032: import java.util.Enumeration;
033: import java.util.Properties;
034: import tests.support.Support_Exec;
035:
036: import junit.framework.TestCase;
037:
038: /**
039: * JUnit Testcase for the java.sql.DriverManager class
040: *
041: */
042: public class DriverManagerTest extends TestCase {
043:
044: // Set of driver names to use
045: static final String DRIVER1 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver1";
046:
047: static final String DRIVER2 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver2";
048:
049: static final String DRIVER3 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver3";
050:
051: static final String DRIVER4 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver4";
052:
053: static final String DRIVER5 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver5";
054:
055: static final String INVALIDDRIVER1 = "abc.klm.Foo";
056:
057: static String[] driverNames = { DRIVER1, DRIVER2, DRIVER4, DRIVER5 };
058:
059: static int numberLoaded;
060:
061: static String baseURL1 = "jdbc:mikes1";
062:
063: static String baseURL4 = "jdbc:mikes4";
064:
065: static final String JDBC_PROPERTY = "jdbc.drivers";
066:
067: static TestHelper_ClassLoader testClassLoader = new TestHelper_ClassLoader();
068:
069: // Static initializer to load the drivers so that they are available to all
070: // the
071: // test methods as needed.
072: @Override
073: public void setUp() {
074: numberLoaded = loadDrivers();
075: } // end setUp()
076:
077: /**
078: * Test for the method DriverManager.deregisterDriver
079: *
080: * @throws SQLException
081: */
082: public void testDeregisterDriver() throws Exception {
083: // First get one of the drivers loaded by the test
084: Driver aDriver;
085: aDriver = DriverManager.getDriver(baseURL4);
086:
087: // Deregister this driver
088: DriverManager.deregisterDriver(aDriver);
089:
090: assertFalse(
091: "testDeregisterDriver: Driver was not deregistered.",
092: isDriverLoaded(aDriver));
093:
094: // Re-register this driver (so subsequent tests have it available)
095: DriverManager.registerDriver(aDriver);
096: assertTrue("testDeregisterDriver: Driver did not reload.",
097: isDriverLoaded(aDriver));
098:
099: // Test deregistering a null driver
100: DriverManager.deregisterDriver(null);
101:
102: // Test deregistering a driver which was not loaded by this test's
103: // classloader
104: // TODO - need to load a driver with a different classloader!!
105: aDriver = DriverManager.getDriver(baseURL1);
106:
107: Class<?> driverClass = Class
108: .forName(
109: "org.apache.harmony.sql.tests.java.sql.TestHelper_DriverManager",
110: true, testClassLoader);
111:
112: // Give the Helper class one of our drivers....
113: Class<?>[] methodClasses = { Class.forName("java.sql.Driver") };
114: Method theMethod = driverClass.getDeclaredMethod("setDriver",
115: methodClasses);
116: Object[] args = { aDriver };
117: theMethod.invoke(null, args);
118:
119: // Check that the driver was not deregistered
120: assertTrue(
121: "testDeregisterDriver: Driver was incorrectly deregistered.",
122: DriverManagerTest.isDriverLoaded(aDriver));
123:
124: } // end method testDeregisterDriver()
125:
126: static void printClassLoader(Object theObject) {
127: Class<? extends Object> theClass = theObject.getClass();
128: ClassLoader theClassLoader = theClass.getClassLoader();
129: System.out.println("ClassLoader is: "
130: + theClassLoader.toString() + " for object: "
131: + theObject.toString());
132: } // end method printClassLoader( Object )
133:
134: static boolean isDriverLoaded(Driver theDriver) {
135: Enumeration<?> driverList = DriverManager.getDrivers();
136: while (driverList.hasMoreElements()) {
137: if ((Driver) driverList.nextElement() == theDriver) {
138: return true;
139: }
140: } // end while
141: return false;
142: } // end method isDriverLoaded( Driver )
143:
144: /*
145: * Class under test for Connection getConnection(String)
146: */
147: // valid connection - data1 does not require a user and password...
148: static String validConnectionURL = "jdbc:mikes1:data1";
149:
150: // invalid connection - data2 requires a user & password
151: static String invalidConnectionURL1 = "jdbc:mikes1:data2";
152:
153: // invalid connection - URL is gibberish
154: static String invalidConnectionURL2 = "xyz1:abc3:456q";
155:
156: // invalid connection - URL is null
157: static String invalidConnectionURL3 = null;
158:
159: static String[] invalidConnectionURLs = { invalidConnectionURL2,
160: invalidConnectionURL3 };
161:
162: public void testGetConnectionString() throws SQLException {
163: Connection theConnection = null;
164: // validConnection - no user & password required
165: theConnection = DriverManager.getConnection(validConnectionURL);
166: assertNotNull(theConnection);
167: assertNotNull(DriverManager
168: .getConnection(invalidConnectionURL1));
169:
170: for (String element : invalidConnectionURLs) {
171: try {
172: theConnection = DriverManager.getConnection(element);
173: fail("Should throw SQLException");
174: } catch (SQLException e) {
175: // expected
176: } // end try
177: } // end for
178: } // end method testGetConnectionString()
179:
180: /**
181: * @tests java.sql.DriverManager#getConnection(String, Properties)
182: */
183: public void test_getConnection_LStringLProperties() {
184: try {
185: DriverManager.getConnection("fff", //$NON-NLS-1$
186: new Properties());
187: fail("Should throw SQLException.");
188: } catch (SQLException e) {
189: assertEquals("08001", e.getSQLState()); //$NON-NLS-1$
190: }
191:
192: try {
193: DriverManager.getConnection(null, new Properties());
194: fail("Should throw SQLException.");
195: } catch (SQLException e) {
196: assertEquals("08001", e.getSQLState()); //$NON-NLS-1$
197: }
198: }
199:
200: /*
201: * Class under test for Connection getConnection(String, Properties)
202: */
203: public void testGetConnectionStringProperties() throws SQLException {
204: String validURL1 = "jdbc:mikes1:data2";
205: String validuser1 = "theuser";
206: String validpassword1 = "thepassword";
207: String invalidURL1 = "xyz:abc1:foo";
208: String invalidURL2 = "jdbc:mikes1:crazyone";
209: String invalidURL3 = "";
210: String invaliduser1 = "jonny nouser";
211: String invalidpassword1 = "whizz";
212: Properties nullProps = null;
213: Properties validProps = new Properties();
214: validProps.setProperty("user", validuser1);
215: validProps.setProperty("password", validpassword1);
216: Properties invalidProps1 = new Properties();
217: invalidProps1.setProperty("user", invaliduser1);
218: invalidProps1.setProperty("password", invalidpassword1);
219: String[] invalidURLs = { null, invalidURL1, invalidURL2,
220: invalidURL3 };
221: Properties[] invalidProps = { nullProps, invalidProps1 };
222:
223: Connection theConnection = null;
224: // validConnection - user & password required
225: theConnection = DriverManager.getConnection(validURL1,
226: validProps);
227: assertNotNull(theConnection);
228:
229: // invalid Connections
230: for (int i = 0; i < invalidURLs.length; i++) {
231: theConnection = null;
232: try {
233: theConnection = DriverManager.getConnection(
234: invalidURLs[i], validProps);
235: fail("Should throw SQLException");
236: } catch (SQLException e) {
237: // expected
238: } // end try
239: } // end for
240: for (Properties invalidProp : invalidProps) {
241: assertNotNull(DriverManager.getConnection(validURL1,
242: invalidProp));
243: }
244: } // end method testGetConnectionStringProperties()
245:
246: /*
247: * Class under test for Connection getConnection(String, String, String)
248: */
249: public void testGetConnectionStringStringString()
250: throws SQLException {
251: String validURL1 = "jdbc:mikes1:data2";
252: String validuser1 = "theuser";
253: String validpassword1 = "thepassword";
254: String invalidURL1 = "xyz:abc1:foo";
255: String invaliduser1 = "jonny nouser";
256: String invalidpassword1 = "whizz";
257: String[] invalid1 = { null, validuser1, validpassword1 };
258: String[] invalid2 = { validURL1, null, validpassword1 };
259: String[] invalid3 = { validURL1, validuser1, null };
260: String[] invalid4 = { invalidURL1, validuser1, validpassword1 };
261: String[] invalid5 = { validURL1, invaliduser1, invalidpassword1 };
262: String[] invalid6 = { validURL1, validuser1, invalidpassword1 };
263: String[][] invalids1 = { invalid1, invalid4 };
264: String[][] invalids2 = { invalid2, invalid3, invalid5, invalid6 };
265:
266: Connection theConnection = null;
267: // validConnection - user & password required
268: theConnection = DriverManager.getConnection(validURL1,
269: validuser1, validpassword1);
270: assertNotNull(theConnection);
271: for (String[] theData : invalids1) {
272: theConnection = null;
273: try {
274: theConnection = DriverManager.getConnection(theData[0],
275: theData[1], theData[2]);
276: fail("Should throw SQLException.");
277: } catch (SQLException e) {
278: // expected
279: } // end try
280: } // end for
281: for (String[] theData : invalids2) {
282: assertNotNull(DriverManager.getConnection(theData[0],
283: theData[1], theData[2]));
284: }
285: } // end method testGetConnectionStringStringString()
286:
287: static String validURL1 = "jdbc:mikes1";
288:
289: static String validURL2 = "jdbc:mikes2";
290:
291: static String invalidURL1 = "xyz:acb";
292:
293: static String invalidURL2 = null;
294:
295: static String[] validURLs = { validURL1, validURL2 };
296:
297: static String[] invalidURLs = { invalidURL1, invalidURL2 };
298:
299: static String exceptionMsg1 = "No suitable driver";
300:
301: public void testGetDriver() throws SQLException {
302: for (String element : validURLs) {
303: Driver validDriver = DriverManager.getDriver(element);
304: assertNotNull(validDriver);
305: } // end for
306:
307: // Comment out since it depends on the drivers providered
308: // for (String element : invalidURLs) {
309: // System.out.println(element);
310: // try {
311: // DriverManager.getDriver(element);
312: // fail("Should throw SQLException");
313: // } catch (SQLException e) {
314: // assertEquals("08001", e.getSQLState());
315: // assertEquals(exceptionMsg1, e.getMessage());
316: // } // end try
317: // } // end for
318:
319: } // end method testGetDriver()
320:
321: public void testGetDrivers() {
322: // Load a driver manager
323: Enumeration<Driver> driverList = DriverManager.getDrivers();
324: int i = 0;
325: while (driverList.hasMoreElements()) {
326: Driver theDriver = driverList.nextElement();
327: assertNotNull(theDriver);
328: i++;
329: } // end while
330:
331: // Check that all the drivers are in the list...
332: // There might be other drivers loaded in other classes
333: assertTrue(
334: "testGetDrivers: Don't see all the loaded drivers - ",
335: i >= numberLoaded);
336: } // end method testGetDrivers()
337:
338: static int timeout1 = 25;
339:
340: public void testGetLoginTimeout() {
341: DriverManager.setLoginTimeout(timeout1);
342: assertEquals(timeout1, DriverManager.getLoginTimeout());
343: } // end method testGetLoginTimeout()
344:
345: @SuppressWarnings("deprecation")
346: public void testGetLogStream() {
347: assertNull(DriverManager.getLogStream());
348:
349: DriverManager.setLogStream(testPrintStream);
350: assertTrue(DriverManager.getLogStream() == testPrintStream);
351:
352: DriverManager.setLogStream(null);
353: } // end method testGetLogStream()
354:
355: public void testGetLogWriter() {
356: assertNull(DriverManager.getLogWriter());
357:
358: DriverManager.setLogWriter(testPrintWriter);
359:
360: assertTrue(DriverManager.getLogWriter() == testPrintWriter);
361:
362: DriverManager.setLogWriter(null);
363: } // end method testGetLogWriter()
364:
365: static String testMessage = "DriverManagerTest: test message for print stream";
366:
367: @SuppressWarnings("deprecation")
368: public void testPrintln() {
369: // System.out.println("testPrintln");
370: DriverManager.println(testMessage);
371:
372: DriverManager.setLogWriter(testPrintWriter);
373: DriverManager.println(testMessage);
374:
375: String theOutput = outputStream.toString();
376: // System.out.println("testPrintln: output= " + theOutput );
377: assertTrue(theOutput.startsWith(testMessage));
378:
379: DriverManager.setLogWriter(null);
380:
381: DriverManager.setLogStream(testPrintStream);
382: DriverManager.println(testMessage);
383:
384: theOutput = outputStream2.toString();
385: // System.out.println("testPrintln: output= " + theOutput );
386: assertTrue(theOutput.startsWith(testMessage));
387:
388: DriverManager.setLogStream(null);
389: } // end method testPrintln()
390:
391: public void testRegisterDriver() throws ClassNotFoundException,
392: SQLException, IllegalAccessException,
393: InstantiationException {
394: String EXTRA_DRIVER_NAME = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver3";
395:
396: try {
397: DriverManager.registerDriver(null);
398: fail("Should throw NullPointerException.");
399: } catch (NullPointerException e) {
400: // expected
401: } // end try
402:
403: Driver theDriver = null;
404: // Load another Driver that isn't in the basic set
405: Class<?> driverClass = Class.forName(EXTRA_DRIVER_NAME);
406: theDriver = (Driver) driverClass.newInstance();
407: DriverManager.registerDriver(theDriver);
408:
409: assertTrue("testRegisterDriver: driver not in loaded set",
410: isDriverLoaded(theDriver));
411:
412: } // end testRegisterDriver()
413:
414: static int validTimeout1 = 15;
415:
416: static int validTimeout2 = 0;
417:
418: static int[] validTimeouts = { validTimeout1, validTimeout2 };
419:
420: static int invalidTimeout1 = -10;
421:
422: public void testSetLoginTimeout() {
423: for (int element : validTimeouts) {
424: DriverManager.setLoginTimeout(element);
425:
426: assertEquals(element, DriverManager.getLoginTimeout());
427: } // end for
428: // Invalid timeouts
429: DriverManager.setLoginTimeout(invalidTimeout1);
430: assertEquals(invalidTimeout1, DriverManager.getLoginTimeout());
431: } // end testSetLoginTimeout()
432:
433: static ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
434:
435: static PrintStream testPrintStream = new PrintStream(outputStream2);
436:
437: @SuppressWarnings("deprecation")
438: public void testSetLogStream() {
439: // System.out.println("testSetLogStream");
440: DriverManager.setLogStream(testPrintStream);
441:
442: assertSame(testPrintStream, DriverManager.getLogStream());
443:
444: DriverManager.setLogStream(null);
445:
446: assertNull(DriverManager.getLogStream());
447:
448: // Now let's deal with the case where there is a SecurityManager in
449: // place
450: TestSecurityManager theSecManager = new TestSecurityManager();
451: System.setSecurityManager(theSecManager);
452:
453: theSecManager.setLogAccess(false);
454:
455: try {
456: DriverManager.setLogStream(testPrintStream);
457: fail("Should throw SecurityException.");
458: } catch (SecurityException s) {
459: // expected
460: }
461:
462: theSecManager.setLogAccess(true);
463:
464: DriverManager.setLogStream(testPrintStream);
465:
466: System.setSecurityManager(null);
467: } // end method testSetLogStream()
468:
469: static ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
470:
471: static PrintWriter testPrintWriter = new PrintWriter(outputStream);
472:
473: /**
474: * Test for the setLogWriter method
475: */
476: public void testSetLogWriter() {
477: // System.out.println("testSetLogWriter");
478: DriverManager.setLogWriter(testPrintWriter);
479:
480: assertSame(testPrintWriter, DriverManager.getLogWriter());
481:
482: DriverManager.setLogWriter(null);
483:
484: assertNull("testDriverManager: Log writer not null:",
485: DriverManager.getLogWriter());
486:
487: // Now let's deal with the case where there is a SecurityManager in
488: // place
489: TestSecurityManager theSecManager = new TestSecurityManager();
490: System.setSecurityManager(theSecManager);
491:
492: theSecManager.setLogAccess(false);
493:
494: try {
495: DriverManager.setLogWriter(testPrintWriter);
496: fail("Should throw SecurityException.");
497: } catch (SecurityException s) {
498: // expected
499: }
500:
501: theSecManager.setLogAccess(true);
502: DriverManager.setLogWriter(testPrintWriter);
503:
504: System.setSecurityManager(null);
505: } // end method testSetLogWriter()
506:
507: /*
508: * Method which loads a set of JDBC drivers ready for use by the various
509: * tests @return the number of drivers loaded
510: */
511: static boolean driversLoaded = false;
512:
513: private static int loadDrivers() {
514: if (driversLoaded) {
515: return numberLoaded;
516: }
517: /*
518: * First define a value for the System property "jdbc.drivers" - before
519: * the DriverManager class is loaded - this property defines a set of
520: * drivers which the DriverManager will load during its initialization
521: * and which will be loaded on the System ClassLoader - unlike the ones
522: * loaded later by this method which are loaded on the Application
523: * ClassLoader.
524: */
525: int numberLoaded = 0;
526:
527: for (String element : driverNames) {
528: try {
529: Class<?> driverClass = Class.forName(element);
530: assertNotNull(driverClass);
531: // System.out.println("Loaded driver - classloader = " +
532: // driverClass.getClassLoader());
533: numberLoaded++;
534: } catch (ClassNotFoundException e) {
535: System.out
536: .println("DriverManagerTest: failed to load Driver: "
537: + element);
538: } // end try
539: } // end for
540: /*
541: * System.out.println("DriverManagerTest: number of drivers loaded: " +
542: * numberLoaded);
543: */
544: driversLoaded = true;
545: return numberLoaded;
546: } // end method loadDrivers()
547:
548: class TestSecurityManager extends SecurityManager {
549:
550: boolean logAccess = true;
551:
552: SQLPermission sqlPermission = new SQLPermission("setLog");
553:
554: RuntimePermission setManagerPermission = new RuntimePermission(
555: "setSecurityManager");
556:
557: TestSecurityManager() {
558: super ();
559: } // end method TestSecurityManager()
560:
561: void setLogAccess(boolean allow) {
562: logAccess = allow;
563: } // end method setLogAccess( boolean )
564:
565: @Override
566: public void checkPermission(Permission thePermission) {
567: if (thePermission.equals(sqlPermission)) {
568: if (!logAccess) {
569: throw new SecurityException(
570: "Cannot set the sql Log Writer");
571: } // end if
572: return;
573: } // end if
574:
575: if (thePermission.equals(setManagerPermission)) {
576: return;
577: } // end if
578: // super.checkPermission( thePermission );
579: } // end method checkPermission( Permission )
580:
581: } // end class TestSecurityManager
582:
583: /**
584: * @tests {@link java.sql.DriverManager#registerDriver(Driver)}
585: *
586: * Registers a driver for multiple times and deregisters it only once.
587: *
588: * Regression for HARMONY-4205
589: */
590: public void test_registerDriver_MultiTimes() throws SQLException {
591: int register_count = 10;
592: int deregister_count = 1;
593:
594: Driver dummy = new DummyDriver();
595: DriverManager.registerDriver(new BadDummyDriver());
596: for (int i = 0; i < register_count; i++) {
597: DriverManager.registerDriver(dummy);
598: }
599: DriverManager.registerDriver(new BadDummyDriver());
600: for (int i = 0; i < deregister_count; i++) {
601: DriverManager.deregisterDriver(dummy);
602: }
603: Driver d = DriverManager
604: .getDriver("jdbc:dummy_protocol:dummy_subname");
605: assertNotNull(d);
606: }
607:
608: /**
609: * Regression for HARMONY-4303
610: */
611: public void test_initClass() throws Exception {
612: String[] arg = new String[1];
613: arg[0] = "org/apache/harmony/sql/tests/java/sql/TestMainForDriver";
614: String result = Support_Exec.execJava(arg, null, true);
615: assertEquals("", result);
616: }
617:
618: private static class BadDummyDriver extends DummyDriver {
619: public boolean acceptsURL(String url) {
620: return false;
621: }
622: }
623:
624: private static class DummyDriver implements Driver {
625:
626: String goodurl = "jdbc:dummy_protocol:dummy_subname";
627:
628: public boolean acceptsURL(String url) {
629: return url.equals(goodurl);
630: }
631:
632: public Connection connect(String url, Properties info) {
633: return null;
634: }
635:
636: public DriverPropertyInfo[] getPropertyInfo(String url,
637: Properties info) {
638: return null;
639: }
640:
641: public int getMajorVersion() {
642: return 0;
643: }
644:
645: public int getMinorVersion() {
646: return 0;
647: }
648:
649: public boolean jdbcCompliant() {
650: return true;
651: }
652:
653: }
654:
655: } // end class DriverManagerTest
|