KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > dbcp > datasources > TestPerUserPoolDataSource


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.commons.dbcp.datasources;
18
19 import java.sql.Connection JavaDoc;
20 import java.sql.PreparedStatement JavaDoc;
21 import java.sql.ResultSet JavaDoc;
22 import java.sql.SQLException JavaDoc;
23
24 import java.io.ByteArrayInputStream JavaDoc;
25 import java.io.ByteArrayOutputStream JavaDoc;
26 import java.io.ObjectInputStream JavaDoc;
27 import java.io.ObjectOutputStream JavaDoc;
28 import java.io.Serializable JavaDoc;
29
30 import javax.sql.DataSource JavaDoc;
31
32 import junit.framework.Test;
33 import junit.framework.TestSuite;
34
35 import org.apache.commons.dbcp.TestConnectionPool;
36 import org.apache.commons.dbcp.TesterDriver;
37 import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
38
39 /**
40  * @author John McNally
41  * @author Dirk Verbeeck
42  * @version $Revision: 1.9 $ $Date: 2004/02/28 11:47:52 $
43  */

44 public class TestPerUserPoolDataSource extends TestConnectionPool {
45     public TestPerUserPoolDataSource(String JavaDoc testName) {
46         super(testName);
47     }
48
49     public static Test suite() {
50         return new TestSuite(TestPerUserPoolDataSource.class);
51     }
52
53     protected Connection JavaDoc getConnection() throws Exception JavaDoc {
54         return ds.getConnection("foo","bar");
55     }
56
57     private DataSource JavaDoc ds;
58
59     public void setUp() throws Exception JavaDoc {
60         DriverAdapterCPDS pcds = new DriverAdapterCPDS();
61         pcds.setDriver("org.apache.commons.dbcp.TesterDriver");
62         pcds.setUrl("jdbc:apache:commons:testdriver");
63         pcds.setUser("foo");
64         pcds.setPassword("bar");
65
66         PerUserPoolDataSource tds = new PerUserPoolDataSource();
67         tds.setConnectionPoolDataSource(pcds);
68         tds.setDefaultMaxActive(getMaxActive());
69         tds.setDefaultMaxWait((int)(getMaxWait()));
70         tds.setPerUserMaxActive("foo",new Integer JavaDoc(getMaxActive()));
71         tds.setPerUserMaxWait("foo",new Integer JavaDoc((int)(getMaxWait())));
72         tds.setDefaultTransactionIsolation(
73             Connection.TRANSACTION_READ_COMMITTED);
74
75         ds = tds;
76     }
77
78     /**
79      * Switching 'u1 -> 'u2' and 'p1' -> 'p2' will
80      * exhibit the bug detailed in
81      * http://nagoya.apache.org/bugzilla/show_bug.cgi?id=18905
82      */

83     public void testIncorrectPassword() throws Exception JavaDoc
84     {
85         try {
86             // Use bad password
87
ds.getConnection("u1", "zlsafjk").close();
88             fail("Able to retrieve connection with incorrect password");
89         } catch (SQLException JavaDoc e1) {
90             // should fail
91

92         }
93         
94         // Use good password
95
ds.getConnection("u1", "p1").close();
96         try
97         {
98             ds.getConnection("u1", "x").close();
99             fail("Able to retrieve connection with incorrect password");
100         }
101         catch (SQLException JavaDoc e)
102         {
103             if (!e.getMessage().startsWith("Given password did not match"))
104             {
105                 throw e;
106             }
107             // else the exception was expected
108
}
109         
110         // Make sure we can still use our good password.
111
ds.getConnection("u1", "p1").close();
112     }
113
114
115     public void testSimple() throws Exception JavaDoc
116     {
117         Connection JavaDoc conn = ds.getConnection();
118         assertTrue(null != conn);
119         PreparedStatement JavaDoc stmt = conn.prepareStatement("select * from dual");
120         assertTrue(null != stmt);
121         ResultSet JavaDoc rset = stmt.executeQuery();
122         assertTrue(null != rset);
123         assertTrue(rset.next());
124         rset.close();
125         stmt.close();
126         conn.close();
127     }
128
129     public void testSimpleWithUsername() throws Exception JavaDoc
130     {
131         Connection JavaDoc conn = ds.getConnection("u1", "p1");
132         assertTrue(null != conn);
133         PreparedStatement JavaDoc stmt = conn.prepareStatement("select * from dual");
134         assertTrue(null != stmt);
135         ResultSet JavaDoc rset = stmt.executeQuery();
136         assertTrue(null != rset);
137         assertTrue(rset.next());
138         rset.close();
139         stmt.close();
140         conn.close();
141     }
142
143     public void testClosingWithUserName()
144         throws Exception JavaDoc
145     {
146         Connection JavaDoc[] c = new Connection JavaDoc[getMaxActive()];
147         // open the maximum connections
148
for (int i=0; i<c.length; i++)
149         {
150             c[i] = ds.getConnection("u1", "p1");
151         }
152
153         // close one of the connections
154
c[0].close();
155         assertTrue(c[0].isClosed());
156         // get a new connection
157
c[0] = ds.getConnection("u1", "p1");
158
159         for (int i=0; i<c.length; i++)
160         {
161             c[i].close();
162         }
163
164         // open the maximum connections
165
for (int i=0; i<c.length; i++)
166         {
167             c[i] = ds.getConnection("u1", "p1");
168         }
169         for (int i=0; i<c.length; i++)
170         {
171             c[i].close();
172         }
173     }
174
175     public void testSimple2()
176         throws Exception JavaDoc
177     {
178         Connection JavaDoc conn = ds.getConnection();
179         assertTrue(null != conn);
180
181         PreparedStatement JavaDoc stmt =
182             conn.prepareStatement("select * from dual");
183         assertTrue(null != stmt);
184         ResultSet JavaDoc rset = stmt.executeQuery();
185         assertTrue(null != rset);
186         assertTrue(rset.next());
187         rset.close();
188         stmt.close();
189         
190         stmt = conn.prepareStatement("select * from dual");
191         assertTrue(null != stmt);
192         rset = stmt.executeQuery();
193         assertTrue(null != rset);
194         assertTrue(rset.next());
195         rset.close();
196         stmt.close();
197         
198         conn.close();
199         try
200         {
201             conn.createStatement();
202             fail("Can't use closed connections");
203         }
204         catch(SQLException JavaDoc e)
205         {
206             // expected
207
}
208
209         conn = ds.getConnection();
210         assertTrue(null != conn);
211
212         stmt = conn.prepareStatement("select * from dual");
213         assertTrue(null != stmt);
214         rset = stmt.executeQuery();
215         assertTrue(null != rset);
216         assertTrue(rset.next());
217         rset.close();
218         stmt.close();
219
220         stmt = conn.prepareStatement("select * from dual");
221         assertTrue(null != stmt);
222         rset = stmt.executeQuery();
223         assertTrue(null != rset);
224         assertTrue(rset.next());
225         rset.close();
226         stmt.close();
227         
228         conn.close();
229         conn = null;
230     }
231
232     public void testOpening()
233         throws Exception JavaDoc
234     {
235         Connection JavaDoc[] c = new Connection JavaDoc[getMaxActive()];
236         // test that opening new connections is not closing previous
237
for (int i=0; i<c.length; i++)
238         {
239             c[i] = ds.getConnection();
240             assertTrue(c[i] != null);
241             for (int j=0; j<=i; j++)
242             {
243                 assertTrue(!c[j].isClosed());
244             }
245         }
246
247         for (int i=0; i<c.length; i++)
248         {
249             c[i].close();
250         }
251     }
252
253     public void testClosing()
254         throws Exception JavaDoc
255     {
256         Connection JavaDoc[] c = new Connection JavaDoc[getMaxActive()];
257         // open the maximum connections
258
for (int i=0; i<c.length; i++)
259         {
260             c[i] = ds.getConnection();
261         }
262
263         // close one of the connections
264
c[0].close();
265         assertTrue(c[0].isClosed());
266         
267         // get a new connection
268
c[0] = ds.getConnection();
269
270         for (int i=0; i<c.length; i++)
271         {
272             c[i].close();
273         }
274     }
275
276     public void testMaxActive()
277         throws Exception JavaDoc
278     {
279         Connection JavaDoc[] c = new Connection JavaDoc[getMaxActive()];
280         for (int i=0; i<c.length; i++)
281         {
282             c[i] = ds.getConnection();
283             assertTrue(c[i] != null);
284         }
285
286         try
287         {
288             ds.getConnection();
289             fail("Allowed to open more than DefaultMaxActive connections.");
290         }
291         catch(java.sql.SQLException JavaDoc e)
292         {
293             // should only be able to open 10 connections, so this test should
294
// throw an exception
295
}
296
297         for (int i=0; i<c.length; i++)
298         {
299             c[i].close();
300         }
301     }
302     
303     public void testPerUserMethods() throws Exception JavaDoc {
304         PerUserPoolDataSource tds = (PerUserPoolDataSource) ds;
305         
306         // you need to set maxActive otherwise there is no accounting
307
tds.setPerUserMaxActive("u1", new Integer JavaDoc(5));
308         tds.setPerUserMaxActive("u2", new Integer JavaDoc(5));
309         
310         assertEquals(0, tds.getNumActive());
311         assertEquals(0, tds.getNumActive("u1", "p1"));
312         assertEquals(0, tds.getNumActive("u2", "p2"));
313         assertEquals(0, tds.getNumIdle());
314         assertEquals(0, tds.getNumIdle("u1", "p1"));
315         assertEquals(0, tds.getNumIdle("u2", "p2"));
316         
317         Connection JavaDoc conn = tds.getConnection();
318         assertNotNull(conn);
319         assertEquals(1, tds.getNumActive());
320         assertEquals(0, tds.getNumActive("u1", "p1"));
321         assertEquals(0, tds.getNumActive("u2", "p2"));
322         assertEquals(0, tds.getNumIdle());
323         assertEquals(0, tds.getNumIdle("u1", "p1"));
324         assertEquals(0, tds.getNumIdle("u2", "p2"));
325
326         conn.close();
327         assertEquals(0, tds.getNumActive());
328         assertEquals(0, tds.getNumActive("u1", "p1"));
329         assertEquals(0, tds.getNumActive("u2", "p2"));
330         assertEquals(1, tds.getNumIdle());
331         assertEquals(0, tds.getNumIdle("u1", "p1"));
332         assertEquals(0, tds.getNumIdle("u2", "p2"));
333
334         conn = tds.getConnection("u1", "p1");
335         assertNotNull(conn);
336         assertEquals(0, tds.getNumActive());
337         assertEquals(1, tds.getNumActive("u1", "p1"));
338         assertEquals(0, tds.getNumActive("u2", "p2"));
339         assertEquals(1, tds.getNumIdle());
340         assertEquals(0, tds.getNumIdle("u1", "p1"));
341         assertEquals(0, tds.getNumIdle("u2", "p2"));
342
343         conn.close();
344         assertEquals(0, tds.getNumActive());
345         assertEquals(0, tds.getNumActive("u1", "p1"));
346         assertEquals(0, tds.getNumActive("u2", "p2"));
347         assertEquals(1, tds.getNumIdle());
348         assertEquals(1, tds.getNumIdle("u1", "p1"));
349         assertEquals(0, tds.getNumIdle("u2", "p2"));
350     }
351     
352     public void testMultipleThreads() throws Exception JavaDoc {
353         assertTrue(multipleThreads(1));
354         assertTrue(!multipleThreads(2 * (int)(getMaxWait())));
355     }
356
357     private boolean multipleThreads(int holdTime) throws Exception JavaDoc {
358         long startTime = System.currentTimeMillis();
359         final boolean[] success = new boolean[1];
360         success[0] = true;
361         final PoolTest[] pts = new PoolTest[2 * getMaxActive()];
362         ThreadGroup JavaDoc threadGroup = new ThreadGroup JavaDoc("foo") {
363             public void uncaughtException(Thread JavaDoc t, Throwable JavaDoc e) {
364                 /*
365                 for (int i = 0; i < pts.length; i++)
366                 {
367                     System.out.println(i + ": " + pts[i].reportState());
368                 }
369                 */

370                 for (int i = 0; i < pts.length; i++) {
371                     pts[i].stop();
372                 }
373
374                 //e.printStackTrace();
375
success[0] = false;
376             }
377         };
378
379         for (int i = 0; i < pts.length; i++) {
380             pts[i] = new PoolTest(threadGroup, holdTime);
381         }
382         Thread.sleep(10 * holdTime);
383         for (int i = 0; i < pts.length; i++) {
384             pts[i].stop();
385         }
386         long time = System.currentTimeMillis() - startTime;
387         // - (pts.length*10*holdTime);
388
System.out.println("Multithread test time = " + time + " ms");
389
390         Thread.sleep(holdTime);
391         return success[0];
392     }
393
394     private static int currentThreadCount = 0;
395
396     private class PoolTest implements Runnable JavaDoc {
397         /**
398          * The number of milliseconds to hold onto a database connection
399          */

400         private int connHoldTime;
401
402         private boolean isRun;
403
404         private String JavaDoc state;
405
406         protected PoolTest(ThreadGroup JavaDoc threadGroup, int connHoldTime) {
407             this.connHoldTime = connHoldTime;
408             Thread JavaDoc thread =
409                 new Thread JavaDoc(threadGroup, this, "Thread+" + currentThreadCount++);
410             thread.setDaemon(false);
411             thread.start();
412         }
413
414         public void run() {
415             isRun = true;
416             while (isRun) {
417                 try {
418                     Connection JavaDoc conn = null;
419                     state = "Getting Connection";
420                     conn = getConnection();
421                     state = "Using Connection";
422                     assertTrue(null != conn);
423                     PreparedStatement JavaDoc stmt =
424                         conn.prepareStatement("select * from dual");
425                     assertTrue(null != stmt);
426                     ResultSet JavaDoc rset = stmt.executeQuery();
427                     assertTrue(null != rset);
428                     assertTrue(rset.next());
429                     state = "Holding Connection";
430                     Thread.sleep(connHoldTime);
431                     state = "Returning Connection";
432                     rset.close();
433                     stmt.close();
434                     conn.close();
435                 } catch (RuntimeException JavaDoc e) {
436                     throw e;
437                 } catch (Exception JavaDoc e) {
438                     throw new RuntimeException JavaDoc(e.toString());
439                 }
440             }
441         }
442
443         public void stop() {
444             isRun = false;
445         }
446
447         public String JavaDoc reportState() {
448             return state;
449         }
450     }
451
452     public void testTransactionIsolationBehavior() throws Exception JavaDoc {
453         Connection JavaDoc conn = getConnection();
454         assertTrue(conn != null);
455         assertEquals(Connection.TRANSACTION_READ_COMMITTED,
456                      conn.getTransactionIsolation());
457         conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
458         conn.close();
459         
460         Connection JavaDoc conn2 = getConnection();
461         assertEquals(Connection.TRANSACTION_READ_COMMITTED,
462                      conn2.getTransactionIsolation());
463         
464         Connection JavaDoc conn3 = getConnection();
465         assertEquals(Connection.TRANSACTION_READ_COMMITTED,
466                      conn3.getTransactionIsolation());
467         conn2.close();
468         conn3.close();
469     }
470
471     public void testSerialization() throws Exception JavaDoc {
472         // make sure the pool has initialized
473
Connection JavaDoc conn = ds.getConnection();
474         conn.close();
475
476         // serialize
477
ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
478         ObjectOutputStream JavaDoc out = new ObjectOutputStream JavaDoc(baos);
479         out.writeObject((Serializable JavaDoc)ds);
480         byte[] b = baos.toByteArray();
481         out.close();
482
483         ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(b);
484         ObjectInputStream JavaDoc in = new ObjectInputStream JavaDoc(bais);
485         Object JavaDoc obj = in.readObject();
486         in.close();
487
488         assertEquals( 1, ((PerUserPoolDataSource)obj).getNumIdle() );
489     }
490
491     // see issue http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23843
492
// unregistered user is in the same pool as without username
493
public void testUnregisteredUser() throws Exception JavaDoc {
494         PerUserPoolDataSource tds = (PerUserPoolDataSource) ds;
495         
496         assertEquals(0, tds.getNumActive());
497         assertEquals(0, tds.getNumIdle());
498         
499         Connection JavaDoc conn = tds.getConnection();
500         assertNotNull(conn);
501         assertEquals(1, tds.getNumActive());
502         assertEquals(0, tds.getNumIdle());
503
504         conn.close();
505         assertEquals(0, tds.getNumActive());
506         assertEquals(1, tds.getNumIdle());
507
508         conn = tds.getConnection("u1", "p1");
509         assertNotNull(conn);
510         assertEquals(0, tds.getNumActive());
511         assertEquals(1, tds.getNumIdle());
512         assertEquals(1, tds.getNumActive("u1", "p1"));
513         assertEquals(0, tds.getNumIdle("u1", "p1"));
514
515         conn.close();
516         assertEquals(0, tds.getNumActive());
517         assertEquals(1, tds.getNumIdle());
518         assertEquals(0, tds.getNumActive("u1", "p1"));
519         assertEquals(1, tds.getNumIdle("u1", "p1"));
520     }
521
522     // see issue http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23843
523
public void testDefaultUser1() throws Exception JavaDoc {
524         TesterDriver.addUser("mkh", "password");
525         TesterDriver.addUser("hanafey", "password");
526         TesterDriver.addUser("jsmith", "password");
527
528         PerUserPoolDataSource puds = (PerUserPoolDataSource) ds;
529         puds.setPerUserMaxActive("jsmith", new Integer JavaDoc(2));
530         String JavaDoc[] users = {"mkh", "hanafey", "jsmith"};
531         String JavaDoc password = "password";
532         Connection JavaDoc[] c = new Connection JavaDoc[users.length];
533         for (int i = 0; i < users.length; i++) {
534             c[i] = puds.getConnection(users[i], password);
535             assertEquals(users[i], getUsername(c[i]));
536         }
537         for (int i = 0; i < users.length; i++) {
538             c[i].close();
539         }
540     }
541     
542     // see issue http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23843
543
public void testDefaultUser2() throws Exception JavaDoc {
544         TesterDriver.addUser("mkh", "password");
545         TesterDriver.addUser("hanafey", "password");
546         TesterDriver.addUser("jsmith", "password");
547
548         PerUserPoolDataSource puds = (PerUserPoolDataSource) ds;
549         puds.setPerUserMaxActive("jsmith", new Integer JavaDoc(2));
550         String JavaDoc[] users = {"jsmith", "hanafey", "mkh"};
551         String JavaDoc password = "password";
552         Connection JavaDoc[] c = new Connection JavaDoc[users.length];
553         for (int i = 0; i < users.length; i++) {
554             c[i] = puds.getConnection(users[i], password);
555             assertEquals(users[i], getUsername(c[i]));
556         }
557         for (int i = 0; i < users.length; i++) {
558             c[i].close();
559         }
560     }
561 }
562
Popular Tags