KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > persist > db > connectionpool > DatabaseConnectionFactoryBaseTest


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: DatabaseConnectionFactoryBaseTest.java,v 1.7 2007/01/07 06:14:20 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.persist.db.connectionpool;
23
24 import java.sql.Connection JavaDoc;
25 import java.sql.PreparedStatement JavaDoc;
26 import java.sql.ResultSet JavaDoc;
27 import java.sql.SQLException JavaDoc;
28 import java.sql.Statement JavaDoc;
29 import java.util.logging.Level JavaDoc;
30 import java.util.logging.Logger JavaDoc;
31
32 import org.opensubsystems.core.error.OSSDatabaseAccessException;
33 import org.opensubsystems.core.error.OSSException;
34 import org.opensubsystems.core.persist.db.Database;
35 import org.opensubsystems.core.persist.db.DatabaseConnectionFactory;
36 import org.opensubsystems.core.persist.db.DatabaseConnectionFactoryImpl;
37 import org.opensubsystems.core.persist.db.DatabaseImpl;
38 import org.opensubsystems.core.persist.db.DatabaseSchemaManager;
39 import org.opensubsystems.core.persist.db.DatabaseTest;
40 import org.opensubsystems.core.persist.db.DatabaseTransactionFactoryImpl;
41 import org.opensubsystems.core.persist.db.driver.DatabaseTestSchema;
42 import org.opensubsystems.core.util.Config;
43 import org.opensubsystems.core.util.DatabaseUtils;
44 import org.opensubsystems.core.util.Log;
45
46 /**
47  * Base class containing tests for general concepts of database connection
48  * factories, which every database connection factory shoudl support.
49  *
50  * @version $Id: DatabaseConnectionFactoryBaseTest.java,v 1.7 2007/01/07 06:14:20 bastafidli Exp $
51  * @author Julian Legeny
52  * @code.reviewer Miro Halas
53  * @code.reviewed 1.4 2005/09/01 05:22:03 bastafidli
54  */

55 public abstract class DatabaseConnectionFactoryBaseTest extends DatabaseTest
56 {
57    // Constants ////////////////////////////////////////////////////////////////
58

59    /**
60     * Name ot the admin DataSource.
61     */

62    public static final String JavaDoc DATASOURCE_NAME_ADMIN = "DATASOURCE_TEST_ADMIN";
63
64    /**
65     * Name ot the DataSource 1.
66     */

67    public static final String JavaDoc DATASOURCE_NAME_1 = "DATASOURCE_TEST_1";
68
69    /**
70     * Name ot the DataSource 2
71     */

72    public static final String JavaDoc DATASOURCE_NAME_2 = "DATASOURCE_TEST_2";
73
74    /**
75     * Username for 2nd datasource
76     */

77    public static final String JavaDoc USERNAME_FOR_DS_2 = "bastatest1";
78    
79    /**
80     * Database URL
81     */

82    private String JavaDoc m_strDatabaseURL;
83
84    /**
85     * User password
86     */

87    private String JavaDoc m_strPassword;
88
89    /**
90     * User password for datasources 1 and 2
91     */

92    private String JavaDoc m_strPasswordDS;
93
94    /**
95     * Default username from property file
96     */

97    private String JavaDoc m_strUsername;
98
99    /**
100     * Default username for datasource 1
101     */

102    private String JavaDoc m_strUsernameDS1;
103
104    /**
105     * Default username for datasource 2
106     */

107    private String JavaDoc m_strUsernameDS2;
108
109    // Attributes ///////////////////////////////////////////////////////////////
110

111    /**
112     * Database connection factory which can be used by test. This connection object
113     * is instantiated before every test is started by the concrete derived class.
114     */

115    protected DatabaseConnectionFactory m_connectionFactory = null;
116
117    // Cached values ////////////////////////////////////////////////////////////
118

119    /**
120     * Logger for this class
121     */

122    private static Logger JavaDoc s_logger = Log.getInstance(DatabaseConnectionFactoryBaseTest.class);
123
124    // Constructors /////////////////////////////////////////////////////////////
125

126    /**
127     * Static initializer
128     */

129    static
130    {
131       if (Config.getInstance().getPropertyFileName() == null)
132       {
133          Config.getInstance().setPropertyFileName(DatabaseTest.DEFAULT_PROPERTY_FILE);
134       }
135
136       // This test use special database schema so make the database aware of it
137
Database dbDatabase;
138       try
139       { // Add schema database tests needs to the database
140
dbDatabase = DatabaseImpl.getInstance();
141          dbDatabase.add(DatabaseTestSchema.class);
142       }
143       catch (OSSException bfeExc)
144       {
145          throw new RuntimeException JavaDoc("Unexpected exception.", bfeExc);
146       }
147    }
148
149    /**
150     * Create new DatabaseConnectionFactoryBaseTest.
151     *
152     * @param strTestName - name of the test
153     */

154    public DatabaseConnectionFactoryBaseTest(
155       String JavaDoc strTestName
156    )
157    {
158       super(strTestName);
159
160       // Initialize in constructor to avoid checkstyle warnings
161
m_strDatabaseURL = "";
162       m_strPassword = "";
163       m_strPasswordDS = "";
164       m_strUsername = "";
165       m_strUsernameDS1 = "";
166       m_strUsernameDS2 = "";
167    }
168
169    /**
170     * Set up environment for the test case.
171     *
172     * @throws Exception - an error has occured during setting up test
173     */

174    protected void setUp(
175    ) throws Exception JavaDoc
176    {
177       String JavaDoc strTestName = getName();
178
179       DatabaseConnectionFactory defaultFactory = DatabaseConnectionFactoryImpl.getInstance();
180       
181       m_strDatabaseURL = defaultFactory.getDatabaseURL();
182       
183       // For testing 'Request Connection By User And Password' we add data sources 1 and 2
184
// with another user/password as will be used for requesting connection in the test.
185
if (strTestName.equals("testRequestConnectionFromTwoDataSourcesByUserAndPassword"))
186       {
187          m_strUsernameDS1 = defaultFactory.getDatabaseAdminUser();
188          m_strUsernameDS2 = m_strUsernameDS1;
189          m_strPasswordDS = defaultFactory.getDatabaseAdminPassword();
190       }
191       else
192       {
193          m_strUsernameDS1 = defaultFactory.getDatabaseUser();
194          m_strUsernameDS2 = USERNAME_FOR_DS_2;
195          m_strPasswordDS = defaultFactory.getDatabasePassword();
196       }
197
198       m_strPassword = defaultFactory.getDatabasePassword();
199       m_strUsername = defaultFactory.getDatabaseUser();
200
201       // add data sources
202
if (!strTestName.equals("testCreatingDefaultDataSource"))
203       {
204          m_connectionFactory.addDataSource(DATASOURCE_NAME_1,
205                                            defaultFactory.getDatabaseDriver(),
206                                            m_strDatabaseURL,
207                                            m_strUsernameDS1,
208                                            m_strPasswordDS);
209       }
210
211       if (strTestName.equals("testRequestConnectionFromTwoDataSources")
212           || strTestName.equals("testConnectionCountForTwoDataSources")
213           || strTestName.equals("testRequestConnectionCountByDataSource")
214           || strTestName.equals("testRequestConnectionCountByDataSourceWithUserAndPasswd")
215           || strTestName.equals("testRequestConnectionCountForSpecifiedDataSource")
216           || strTestName.equals("testRequestConnectionFromTwoDataSourcesByUserAndPassword")
217           || strTestName.equals("testRequestConnectionByUserAndPassword"))
218       {
219          Connection JavaDoc cAdminConnection = null;
220          
221          // add data source for admin user
222
((DatabaseTestSchema) DatabaseSchemaManager.getInstance(
223             DatabaseTestSchema.class)).createDataSource(m_connectionFactory,
224                                                         DATASOURCE_NAME_ADMIN,
225                                                         defaultFactory.getDatabaseDriver(),
226                                                         m_strDatabaseURL,
227                                                         defaultFactory.getDatabaseAdminUser(),
228                                                         defaultFactory.getDatabaseAdminPassword());
229          
230          m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_ADMIN);
231
232          try
233          {
234             // Request autocommit false since we are modifying database
235
cAdminConnection = m_connectionFactory.requestConnection(false);
236    
237             // create user for this specific test
238
((DatabaseTestSchema) DatabaseSchemaManager.getInstance(
239                 DatabaseTestSchema.class)).createTestUser(cAdminConnection,
240                                                           m_strDatabaseURL,
241                                                           USERNAME_FOR_DS_2,
242                                                           m_strPassword);
243
244             DatabaseTransactionFactoryImpl.getInstance().commitTransaction(cAdminConnection);
245          }
246          catch (Throwable JavaDoc thr)
247          {
248             DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(cAdminConnection);
249             throw new Exception JavaDoc(thr);
250          }
251          finally
252          {
253             m_connectionFactory.returnConnection(cAdminConnection);
254          }
255          // add data source 2
256
((DatabaseTestSchema) DatabaseSchemaManager.getInstance(
257             DatabaseTestSchema.class)).createDataSource(m_connectionFactory,
258                                                         DATASOURCE_NAME_2,
259                                                         defaultFactory.getDatabaseDriver(),
260                                                         m_strDatabaseURL,
261                                                         m_strUsernameDS2,
262                                                         m_strPasswordDS);
263       }
264
265       if (!strTestName.equals("testCreatingDefaultDataSource"))
266       {
267          m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
268       }
269
270       super.setUp();
271    }
272
273    /**
274     * Restore original environment after the test case.
275     *
276     * @throws Exception - an error has occured during tearing down up test
277     */

278    protected void tearDown() throws Exception JavaDoc
279    {
280       String JavaDoc strTestName = getName();
281       if (strTestName.equals("testRequestConnectionFromTwoDataSources")
282           || strTestName.equals("testConnectionCountForTwoDataSources")
283           || strTestName.equals("testRequestConnectionCountByDataSource")
284           || strTestName.equals("testRequestConnectionCountByDataSourceWithUserAndPasswd")
285           || strTestName.equals("testRequestConnectionCountForSpecifiedDataSource")
286           || strTestName.equals("testRequestConnectionFromTwoDataSourcesByUserAndPassword")
287           || strTestName.equals("testRequestConnectionByUserAndPassword"))
288       {
289          // we have to stop connection because there is not allowed for some database
290
// (for example SapDB) to drop user while user is connected
291
m_connectionFactory.stop();
292
293          // add data source for admin
294
DatabaseConnectionFactory defaultFactory = DatabaseConnectionFactoryImpl.getInstance();
295          ((DatabaseTestSchema) DatabaseSchemaManager.getInstance(
296             DatabaseTestSchema.class)).createDataSource(m_connectionFactory,
297                                                         DATASOURCE_NAME_ADMIN,
298                                                         defaultFactory.getDatabaseDriver(),
299                                                         m_strDatabaseURL,
300                                                         defaultFactory.getDatabaseAdminUser(),
301                                                         defaultFactory.getDatabaseAdminPassword());
302
303          // set admin datasource and drop test user
304
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_ADMIN);
305          Connection JavaDoc cAdminConnection = null;
306
307          try
308          {
309             // there has to be here autocommit = true, because there is problem to execute
310
// some stored procedure while in transaction
311
cAdminConnection = m_connectionFactory.requestConnection(true);
312             // drop user for this specific test
313
((DatabaseTestSchema) DatabaseSchemaManager.getInstance(
314                 DatabaseTestSchema.class)).dropTestUser(cAdminConnection,
315                                                         m_strDatabaseURL,
316                                                         USERNAME_FOR_DS_2);
317          }
318          finally
319          {
320             m_connectionFactory.returnConnection(cAdminConnection);
321          }
322       }
323
324       m_connectionFactory.stop();
325
326       super.tearDown();
327    }
328
329    // Tests ////////////////////////////////////////////////////////////////////
330

331    /**
332     * Test for request connection will create default data source if there
333     * wasn't specified.
334     *
335     * @throws Exception - an error has occured during test
336     */

337    public void testCreatingDefaultDataSource(
338    ) throws Exception JavaDoc
339    {
340       Connection JavaDoc con = null;
341       String JavaDoc strDefaultDS = "";
342
343       try
344       {
345          strDefaultDS = m_connectionFactory.getDefaultDataSourceName();
346
347          assertEquals("There should be not specified default data source yet.",
348                       "", strDefaultDS);
349
350          // Request autocommit true since we are just reading data from the database
351
con = m_connectionFactory.requestConnection(true);
352
353          strDefaultDS = m_connectionFactory.getDefaultDataSourceName();
354
355          assertTrue("There should be already specified default data source.",
356                     strDefaultDS.length() > 0);
357       }
358       catch (IllegalArgumentException JavaDoc iaeExc)
359       {
360          s_logger.log(Level.WARNING,
361                       "Proxool doesn't support creation of multiple connection pools" +
362                       " with the same name, see bug 1275551",
363                       iaeExc);
364          fail("Proxool doesn't support creation of multiple connection pools" +
365               " with the same name, see bug 1275551");
366       }
367       finally
368       {
369          m_connectionFactory.returnConnection(con);
370       }
371    }
372
373    /**
374     * Test for request connection - if there is connection requested, request
375     * counter has to increase.
376     *
377     * @throws Exception - an error has occured during test
378     */

379    public void testRequestConnectionCount(
380    ) throws Exception JavaDoc
381    {
382       Connection JavaDoc con = null;
383       int testReqConCount = -1;
384
385       try
386       {
387          // Request autocommit true since we are just reading data from the database
388
con = m_connectionFactory.requestConnection(true);
389          assertTrue("Autocommit should be true for pooled connections.", con.getAutoCommit());
390          
391          // get number of connections
392
testReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
393          
394          assertEquals("Incorrect number of requested connections", 1, testReqConCount);
395       }
396       finally
397       {
398          m_connectionFactory.returnConnection(con);
399       }
400    }
401
402    /**
403     * Test for connection count that is specified by data source
404     *
405     * @throws Exception - an error has occured during test
406     */

407    public void testRequestConnectionCountForSpecifiedDataSource(
408    ) throws Exception JavaDoc
409    {
410       Connection JavaDoc con1 = null;
411       Connection JavaDoc con2 = null;
412       int testReqConCount = -1;
413       int testTotalReqConCount = -1;
414
415       try
416       {
417          // Check if there is set default data source 1.
418
assertEquals("Incorrect default data source is specified",
419                       DATASOURCE_NAME_1, m_connectionFactory.getDefaultDataSourceName());
420
421          // Check for total connection count
422
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
423          assertEquals("Incorrect initial total connection count.",
424                       0, testTotalReqConCount);
425
426          // Check for connection count for data source 1
427
testReqConCount = m_connectionFactory.getRequestedConnectionCount(DATASOURCE_NAME_1);
428          assertEquals("Incorrect initial connection count for data source 1.",
429                       0, testReqConCount);
430
431          // Check for connection count for data source 2
432
testReqConCount = m_connectionFactory.getRequestedConnectionCount(DATASOURCE_NAME_2);
433          assertEquals("Incorrect initial connection count for data source 2.",
434                       0, testReqConCount);
435
436          // Request autocommit true since we are just reading data from the database
437
con1 = m_connectionFactory.requestConnection(true);
438          
439          // Check if there is still default data source 1.
440
assertEquals("There should be still datasource 1 specified as default",
441                       DATASOURCE_NAME_1, m_connectionFactory.getDefaultDataSourceName());
442
443          // Check for total connection count
444
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
445          assertEquals("Incorrect total connection count after requesting connection " +
446                       "from data source 2.", 1, testTotalReqConCount);
447
448          // Check for connection count of data source 1
449
testReqConCount = m_connectionFactory.getRequestedConnectionCount(DATASOURCE_NAME_1);
450          assertEquals("Incorrect connection count for data source 1.",
451                       1, testReqConCount);
452
453          // Check for connection count of data source 2
454
testReqConCount = m_connectionFactory.getRequestedConnectionCount(DATASOURCE_NAME_2);
455          assertEquals("Incorrect connection count for data source 2.",
456                       0, testReqConCount);
457
458          // Now set datasource 2 as default
459
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
460
461          // Request connection from data source 2
462
// Request autocommit true since we are just reading data from the database
463
con2 = m_connectionFactory.requestConnection(true);
464
465          // Check if there is still default data source 2.
466
assertEquals("There should be still datasource 2 specified as default",
467                       DATASOURCE_NAME_2, m_connectionFactory.getDefaultDataSourceName());
468
469          // Check for total connection count
470
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
471          assertEquals("Incorrect total connection count after requesting connection " +
472                       "from data source 1.", 2, testTotalReqConCount);
473
474          // Check for connection count of data source 1
475
testReqConCount = m_connectionFactory.getRequestedConnectionCount(DATASOURCE_NAME_1);
476          assertEquals("Incorrect connection count for data source 1.",
477                       1, testReqConCount);
478          
479          // Check for connection count of data source 2
480
testReqConCount = m_connectionFactory.getRequestedConnectionCount(DATASOURCE_NAME_2);
481          assertEquals("Incorrect connection count for data source 2.",
482                       1, testReqConCount);
483       }
484       finally
485       {
486          // return connections
487
m_connectionFactory.returnConnection(con1);
488          m_connectionFactory.returnConnection(con2);
489       }
490
491    }
492
493    /**
494     * Test for return connection - if there is connection returned, request
495     * counter has to decrease.
496     *
497     * @throws Exception - an error has occured during test
498     */

499    public void testReturnConnectionCount(
500    ) throws Exception JavaDoc
501    {
502       Connection JavaDoc con = null;
503       int testReqConCount = -1;
504
505       try
506       {
507          // Request autocommit true since we are just reading data from the database
508
con = m_connectionFactory.requestConnection(true);
509       }
510       finally
511       {
512          // return connection
513
m_connectionFactory.returnConnection(con);
514       }
515       // get number of connections
516
testReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
517
518       assertEquals("Incorrect number of connections after returning connection",
519                    0, testReqConCount);
520    }
521
522    /**
523     * Test for adding data source with the same name as already has been added.
524     *
525     * @throws Exception - an error has occured during test
526     */

527    public void testAddDataSourceWithTheSameName(
528    ) throws Exception JavaDoc
529    {
530       try
531       {
532          DatabaseConnectionFactory defaultFactory = DatabaseConnectionFactoryImpl.getInstance();
533          
534          // add data sources
535
m_connectionFactory.addDataSource(DATASOURCE_NAME_1,
536                                            defaultFactory.getDatabaseDriver(),
537                                            defaultFactory.getDatabaseURL(),
538                                            defaultFactory.getDatabaseUser(),
539                                            defaultFactory.getDatabasePassword());
540
541          fail("It should be not permitted to add DataSource with the same name.");
542       }
543       catch (OSSDatabaseAccessException daeExc)
544       {
545          // there should be thrown exception when DataSource with the same name is added
546
// This exception is expected.
547
}
548    }
549
550    /**
551     * Test for 2 data sources. When there was requested connection from DS1, then set to DS2,
552     * then return conection (for DS1 when active is DS2), connection count will be still 1
553     * instead of 0.
554     *
555     * @throws Exception - an error has occured during test
556     */

557    public void testConnectionCountForTwoDataSources(
558    ) throws Exception JavaDoc
559    {
560       Connection JavaDoc con1 = null;
561       Connection JavaDoc con2 = null;
562       int testConCountDS1 = -1;
563       int testConCountDS2 = -1;
564
565       try
566       {
567          // at this moment there are added 2 data sources
568

569          // set to DS1, request connection from DS1 and get connection count for DS1
570
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
571          // Request autocommit true since we are just reading data from the database
572
con1 = m_connectionFactory.requestConnection(true);
573          testConCountDS1 = m_connectionFactory.getRequestedConnectionCount();
574          
575          assertEquals("Incorrect number of connections for DataSource 1", 1, testConCountDS1);
576
577          // set to DS2 and get connection count for DS2
578
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
579          testConCountDS2 = m_connectionFactory.getRequestedConnectionCount();
580          
581          assertEquals("Incorrect number of connections for DataSource 2", 0, testConCountDS2);
582          
583          // return connection (it's still active DS2) and here should be returned connection for
584
// DS1 because there was not yet requested connection for DS2
585
m_connectionFactory.returnConnection(con1);
586          // reset so that we don't return it again below
587
con1 = null;
588          
589          // get connection count - it's still active DS2 and there should be
590
// returned connection count for DS2
591
testConCountDS2 = m_connectionFactory.getRequestedConnectionCount();
592          assertEquals("Incorrect number of connections for DataSource 2", 0, testConCountDS2);
593          
594          // set to DS1 and get connection count for DS1
595
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
596          testConCountDS1 = m_connectionFactory.getRequestedConnectionCount();
597
598          assertEquals("Incorrect number of connections for DataSource 1", 0, testConCountDS1);
599       }
600       finally
601       {
602          // return con1 only if there was error above
603
m_connectionFactory.returnConnection(con1);
604          m_connectionFactory.returnConnection(con2);
605       }
606    }
607
608    /**
609     * Test for requesting connection implicitly without specifying user name and
610     * password. There are 2 data sources. It should be possible to switch them
611     * and retrieve connections from each one of them. Each data source has different
612     * user which creates different table and inserts some data to it and selects
613     * some data from it. These data should be different for both connections and
614     * it should not be possible to access the other table using incorrect connection.
615     *
616     * @throws Exception - an error has occured during test
617     */

618    public void testRequestConnectionFromTwoDataSources(
619    ) throws Exception JavaDoc
620    {
621       Connection JavaDoc con1 = null;
622       Connection JavaDoc con2 = null;
623       int testConCountDS1 = -1;
624       int testConCountDS2 = -1;
625       int iInsertCount = 0;
626       String JavaDoc testValueDS1 = "";
627       String JavaDoc testValueDS2 = "";
628
629       Statement JavaDoc createStatement = null;
630       PreparedStatement JavaDoc insertStatement = null;
631       Statement JavaDoc selectStatement = null;
632       ResultSet JavaDoc rsResults = null;
633
634
635       final String JavaDoc CREATE_TABLE1 = "create table REQ_CONN_TEST1 (TEST_VALUE varchar(20))";
636       final String JavaDoc DROP_TABLE1 = "drop table REQ_CONN_TEST1";
637       final String JavaDoc INSERT_VALUE1 = "insert into REQ_CONN_TEST1 (TEST_VALUE) values (?)";
638       final String JavaDoc SELECT_VALUE1 = "select * from REQ_CONN_TEST1";
639       final String JavaDoc CREATE_TABLE2 = "create table REQ_CONN_TEST2 (TEST_VALUE varchar(20))";
640       final String JavaDoc DROP_TABLE2 = "drop table REQ_CONN_TEST2";
641       final String JavaDoc INSERT_VALUE2 = "insert into REQ_CONN_TEST2 (TEST_VALUE) values (?)";
642       final String JavaDoc SELECT_VALUE2 = "select * from REQ_CONN_TEST2";
643       final String JavaDoc VALUE_DS1 = "test_value_DS1";
644       final String JavaDoc VALUE_DS2 = "test_value_DS2";
645
646       try
647       {
648          // at this moment there are added 2 data sources
649

650          // set to DS1, request connection from DS1 and get connection count for DS1
651
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
652          // Request autocommit false since we are modifying database
653
con1 = m_connectionFactory.requestConnection(false);
654          testConCountDS1 = m_connectionFactory.getRequestedConnectionCount();
655          
656          assertEquals("Incorrect number of connections for DataSource 1", 1, testConCountDS1);
657
658          // ==========================================
659
// 1. Create table for DS1 and insert record
660
// ==========================================
661
try
662          {
663             try
664             {
665                 // create table for DS1
666
createStatement = con1.createStatement();
667                createStatement.execute(CREATE_TABLE1);
668                
669                // insert value to the table
670
insertStatement = con1.prepareStatement(INSERT_VALUE1);
671                insertStatement.setString(1, VALUE_DS1);
672                iInsertCount = insertStatement.executeUpdate();
673                assertEquals("One record should have been inserted.",
674                                    1, iInsertCount);
675             }
676             finally
677             {
678                DatabaseUtils.closeStatement(createStatement);
679                DatabaseUtils.closeStatement(insertStatement);
680                createStatement = null;
681                insertStatement = null;
682             }
683             // We are using 2 connections so we need to make commitTransaction for particular
684
// connection. There will be better to have distributed connection manager.
685
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(con1);
686          }
687          catch (Throwable JavaDoc thr)
688          {
689             // We are using 2 connections so we need to do rollbackTransaction for particular
690
// connection.There will be better to have distributed connection manager.
691
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con1);
692             throw new Exception JavaDoc(thr);
693          }
694
695          // set to DS2, request connection from DS2 and get connection count for DS2
696
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
697          // Request autocommit false since we are modifying database
698
con2 = m_connectionFactory.requestConnection(false);
699          testConCountDS2 = m_connectionFactory.getRequestedConnectionCount();
700          
701          assertEquals("Incorrect number of connections for DataSource 1", 1, testConCountDS2);
702
703          // ==========================================
704
// 1. Create table for DS2 and insert record
705
// ==========================================
706
try
707          {
708             try
709             {
710                // create table for DS1
711
createStatement = con2.createStatement();
712                createStatement.execute(CREATE_TABLE2);
713                
714                // insert value to the table
715
insertStatement = con2.prepareStatement(INSERT_VALUE2);
716                insertStatement.setString(1, VALUE_DS2);
717                iInsertCount = insertStatement.executeUpdate();
718                assertEquals("One record should have been inserted.",
719                                    1, iInsertCount);
720             }
721             finally
722             {
723                DatabaseUtils.closeStatement(createStatement);
724                DatabaseUtils.closeStatement(insertStatement);
725                createStatement = null;
726                insertStatement = null;
727             }
728             // We are using 2 connections so we need to make commitTransaction for particular
729
// connection. There will be better to have distributed connection manager.
730
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(con2);
731          }
732          catch (Throwable JavaDoc thr)
733          {
734             // We are using 2 connections so we need to do rollbackTransaction for particular
735
// connection.There will be better to have distributed connection manager.
736
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con2);
737             throw new Exception JavaDoc(thr);
738          }
739
740          // Now try to select from DS2 using this connection
741
try
742          {
743             selectStatement = con2.createStatement();
744             rsResults = selectStatement.executeQuery(SELECT_VALUE2);
745             assertTrue("There should be selected value for DS2", rsResults.next());
746             testValueDS2 = rsResults.getString(1);
747             assertEquals("Incorrect value for data source 2", VALUE_DS2, testValueDS2);
748
749          }
750          finally
751          {
752             DatabaseUtils.closeResultSetAndStatement(rsResults, selectStatement);
753             rsResults = null;
754             selectStatement = null;
755          }
756
757          // set to DS1
758
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
759
760          // Now try to select from DS1 using this connection
761
try
762          {
763             selectStatement = con1.createStatement();
764             rsResults = selectStatement.executeQuery(SELECT_VALUE1);
765             assertTrue("There should be selected value for DS1", rsResults.next());
766             testValueDS1 = rsResults.getString(1);
767             assertEquals("Incorrect value for data source 1", VALUE_DS1, testValueDS1);
768          }
769          finally
770          {
771             DatabaseUtils.closeResultSetAndStatement(rsResults, selectStatement);
772             rsResults = null;
773             selectStatement = null;
774          }
775
776          // At this point we know there are inserted correct records in particular
777
// tables for particular data sources. Now try to retrieve data from TABLE 2
778
// using data source 1 and retrieve data from TABLE 1 using data source 2.
779
// Now try to select from DS1 using this connection
780
try
781          {
782             selectStatement = con1.createStatement();
783             rsResults = selectStatement.executeQuery(SELECT_VALUE2);
784             if (rsResults.next())
785             {
786               testValueDS1 = rsResults.getString(1);
787             }
788             assertNull("The database by default doesn't isolate tables created by" +
789                        " one user from tables created by other user since it should" +
790                        " not be possible to select value from Table 2 for DS1",
791                        rsResults);
792          }
793          catch (SQLException JavaDoc sqlExc)
794          {
795             DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con1);
796             // This exception is expected, beacause there is not Table 2 for DS1
797
// (Table 2 belongs to DS2)
798
assertNull("There should not be selected value from Table 2 for DS1", rsResults);
799          }
800          finally
801          {
802             DatabaseUtils.closeResultSetAndStatement(rsResults, selectStatement);
803             rsResults = null;
804             selectStatement = null;
805          }
806          
807          // set to DS2
808
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
809
810          try
811          {
812             selectStatement = con2.createStatement();
813             rsResults = selectStatement.executeQuery(SELECT_VALUE1);
814             if (rsResults.next())
815             {
816               testValueDS2 = rsResults.getString(1);
817             }
818
819             assertNull("There should not be selected value from Table 2 for DS1", rsResults);
820          }
821          catch (SQLException JavaDoc sqlExc)
822          {
823             DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con2);
824
825             // This exception is expected, beacause there is not Table 1 for DS2
826
// (Table 1 belongs to DS1)
827
assertNull("The database by default doesn't isolate tables created by" +
828                        " one user from tables created by other user since it should" +
829                        " not be possible to select value from Table 1 for DS2",
830                        rsResults);
831          }
832          finally
833          {
834             DatabaseUtils.closeResultSetAndStatement(rsResults, selectStatement);
835             rsResults = null;
836             selectStatement = null;
837          }
838       }
839       finally
840       {
841          Statement JavaDoc stmQuery = null;
842
843          try
844          {
845             // If connection wasn't created due to some error, there is no
846
// need to delete this table
847
if (con1 != null)
848             {
849                // set to DS1
850
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
851             
852                try
853                {
854                   stmQuery = con1.createStatement();
855                   // drop table 1
856
if (stmQuery.execute(DROP_TABLE1))
857                   {
858                      // Close any results
859
stmQuery.getMoreResults(Statement.CLOSE_ALL_RESULTS);
860                   }
861                   // We are using 2 connections so we need to make commitTransaction for particular
862
// connection. There will be better to have distributed connection manager.
863
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(con1);
864                }
865                finally
866                {
867                    DatabaseUtils.closeStatement(stmQuery);
868                }
869             }
870          }
871          catch (Throwable JavaDoc thr)
872          {
873             // We are using 2 connections so we need to do rollbackTransaction for particular
874
// connection.There will be better to have distributed connection manager.
875
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con1);
876             throw new Exception JavaDoc(thr);
877          }
878          finally
879          {
880             try
881             {
882                // If connection wasn't created due to some error, there is no
883
// need to delete this table
884
if (con2 != null)
885                {
886                   // set to DS1
887
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
888                
889                   try
890                   {
891                      stmQuery = con2.createStatement();
892                      // drop table 2
893
if (stmQuery.execute(DROP_TABLE2))
894                      {
895                         // Close any results
896
stmQuery.getMoreResults(Statement.CLOSE_ALL_RESULTS);
897                      }
898                   }
899                   finally
900                   {
901                       DatabaseUtils.closeStatement(stmQuery);
902                   }
903                   // We are using 2 connections so we need to make commitTransaction for particular
904
// connection. There will be better to have distributed connection manager.
905
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(con2);
906                }
907             }
908             catch (Throwable JavaDoc thr)
909             {
910                // We are using 2 connections so we need to do rollbackTransaction for particular
911
// connection.There will be better to have distributed connection manager.
912
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con2);
913                throw new Exception JavaDoc(thr);
914             }
915             finally
916             {
917                m_connectionFactory.returnConnection(con1);
918                m_connectionFactory.returnConnection(con2);
919             }
920          }
921       }
922    }
923
924    /**
925     * Test for requesting connection explictly by user and password. There are
926     * 2 data sources. It should be possible to switch them and retrieve connections
927     * from each one of them. Each data source has different user which creates
928     * different table and inserts some data to it and selects some data from it.
929     * These data should be different for both connections and it should not be
930     * possible to access the other table using incorrect connection.
931     *
932     * @throws Exception - an error has occured during test
933     */

934    public void testRequestConnectionFromTwoDataSourcesByUserAndPassword(
935    ) throws Exception JavaDoc
936    {
937       Connection JavaDoc con1 = null;
938       Connection JavaDoc con2 = null;
939       int testConCountDS1 = -1;
940       int testConCountDS2 = -1;
941       int iInsertCount = 0;
942       String JavaDoc testValueDS1 = "";
943       String JavaDoc testValueDS2 = "";
944
945       Statement JavaDoc createStatement = null;
946       PreparedStatement JavaDoc insertStatement = null;
947       Statement JavaDoc selectStatement = null;
948       ResultSet JavaDoc rsResults = null;
949
950
951       final String JavaDoc CREATE_TABLE1 = "create table REQ_CONN_TEST1 (TEST_VALUE varchar(20))";
952       final String JavaDoc DROP_TABLE1 = "drop table REQ_CONN_TEST1";
953       final String JavaDoc INSERT_VALUE1 = "insert into REQ_CONN_TEST1 (TEST_VALUE) values (?)";
954       final String JavaDoc SELECT_VALUE1 = "select * from REQ_CONN_TEST1";
955       final String JavaDoc CREATE_TABLE2 = "create table REQ_CONN_TEST2 (TEST_VALUE varchar(20))";
956       final String JavaDoc DROP_TABLE2 = "drop table REQ_CONN_TEST2";
957       final String JavaDoc INSERT_VALUE2 = "insert into REQ_CONN_TEST2 (TEST_VALUE) values (?)";
958       final String JavaDoc SELECT_VALUE2 = "select * from REQ_CONN_TEST2";
959       final String JavaDoc VALUE_DS1 = "test_value_DS1";
960       final String JavaDoc VALUE_DS2 = "test_value_DS2";
961
962       // at this moment there are added 2 data sources
963

964       // set to DS1, request connection from DS1 and get connection count for DS1
965
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
966       try
967       {
968          // Try to trequest connection using different user name only
969
// Request autocommit true since we are just reading data from the database
970
con1 = m_connectionFactory.requestConnection(true,
971                                        m_strUsername + "_diff", m_strPassword);
972          fail("The connection should have not been allocated.");
973       }
974       catch (OSSDatabaseAccessException daeExc)
975       {
976          // This exception is expected
977
assertNull("There should be not requested connection for incorrect username", con1);
978       }
979       finally
980       {
981          // In case the connection was retrieved, return it, this will also
982
// work if it is null
983
m_connectionFactory.returnConnection(con1);
984          con1 = null;
985       }
986       try
987       {
988          // Try to request connection using different password only
989
// Request autocommit true since we are just reading data from the database
990
con1 = m_connectionFactory.requestConnection(true,
991                                        m_strUsername, m_strPassword + "_diff");
992          fail("The connection should have not been allocated.");
993       }
994       catch (OSSDatabaseAccessException daeExc)
995       {
996          // This exception is expected
997
assertNull("There should be not requested connection for incorrect password", con1);
998       }
999       finally
1000      {
1001         // In case the connection was retrieved, return it, this will also
1002
// work if it is null
1003
m_connectionFactory.returnConnection(con1);
1004         con1 = null;
1005      }
1006      try
1007      {
1008         // Try to request connection using different usename and password
1009
// Request autocommit true since we are just reading data from the database
1010
con1 = m_connectionFactory.requestConnection(true,
1011                                                      m_strUsername + "_diff",
1012                                                      m_strPassword + "_diff");
1013         fail("The connection should have not been allocated.");
1014      }
1015      catch (OSSDatabaseAccessException daeExc)
1016      {
1017         // This exception is expected
1018
assertNull("There should be not requested connection for incorrect usernane " +
1019                    "and password", con1);
1020      }
1021      finally
1022      {
1023         // In case the connection was retrieved, return it, this will also
1024
// work if it is null
1025
m_connectionFactory.returnConnection(con1);
1026         con1 = null;
1027      }
1028
1029      try
1030      {
1031         // We have another user on the datasource ()there is used ADMIN for adding
1032
// datasources 1 and 2. For requesting connections in this test we are using
1033
// another 2 users.
1034
// Request autocommit false since we are modifying database
1035
con1 = m_connectionFactory.requestConnection(false, m_strUsername, m_strPassword);
1036         testConCountDS1 = m_connectionFactory.getRequestedConnectionCount();
1037         
1038         assertEquals("Incorrect number of connections for DataSource 1", 1, testConCountDS1);
1039
1040         // ==========================================
1041
// 1. Create table for DS1 and insert record
1042
// ==========================================
1043
try
1044         {
1045            try
1046            {
1047                // create table for DS1
1048
createStatement = con1.createStatement();
1049               createStatement.execute(CREATE_TABLE1);
1050               
1051               // insert value to the table
1052
insertStatement = con1.prepareStatement(INSERT_VALUE1);
1053               insertStatement.setString(1, VALUE_DS1);
1054               iInsertCount = insertStatement.executeUpdate();
1055               assertEquals("One record should have been inserted.",
1056                                   1, iInsertCount);
1057            }
1058            finally
1059            {
1060               DatabaseUtils.closeStatement(createStatement);
1061               DatabaseUtils.closeStatement(insertStatement);
1062               createStatement = null;
1063               insertStatement = null;
1064            }
1065            // We are using 2 connections so we need to make commitTransaction for particular
1066
// connection. There will be better to have distributed connection manager.
1067
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(con1);
1068         }
1069         catch (Throwable JavaDoc thr)
1070         {
1071            // We are using 2 connections so we need to do rollbackTransaction for particular
1072
// connection.There will be better to have distributed connection manager.
1073
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con1);
1074            throw new Exception JavaDoc(thr);
1075         }
1076
1077         // set to DS2, request connection from DS2 and get connection count for DS2
1078
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
1079         // request connection by username and password
1080
// Request autocommit false since we are modifying database
1081
con2 = m_connectionFactory.requestConnection(false, USERNAME_FOR_DS_2, m_strPassword);
1082         testConCountDS2 = m_connectionFactory.getRequestedConnectionCount();
1083         
1084         assertEquals("Incorrect number of connections for DataSource 1", 1, testConCountDS2);
1085
1086         // ==========================================
1087
// 1. Create table for DS2 and insert record
1088
// ==========================================
1089
try
1090         {
1091            try
1092            {
1093               // create table for DS1
1094
createStatement = con2.createStatement();
1095               createStatement.execute(CREATE_TABLE2);
1096               
1097               // insert value to the table
1098
insertStatement = con2.prepareStatement(INSERT_VALUE2);
1099               insertStatement.setString(1, VALUE_DS2);
1100               iInsertCount = insertStatement.executeUpdate();
1101               assertEquals("One record should have been inserted.",
1102                                   1, iInsertCount);
1103            }
1104            finally
1105            {
1106               DatabaseUtils.closeStatement(createStatement);
1107               DatabaseUtils.closeStatement(insertStatement);
1108               createStatement = null;
1109               insertStatement = null;
1110            }
1111            // We are using 2 connections so we need to make commitTransaction for particular
1112
// connection. There will be better to have distributed connection manager.
1113
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(con2);
1114         }
1115         catch (Throwable JavaDoc thr)
1116         {
1117            // We are using 2 connections so we need to do rollbackTransaction for particular
1118
// connection.There will be better to have distributed connection manager.
1119
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con2);
1120            throw new Exception JavaDoc(thr);
1121         }
1122
1123         // Now try to select from DS2 using this connection
1124
try
1125         {
1126            selectStatement = con2.createStatement();
1127            rsResults = selectStatement.executeQuery(SELECT_VALUE2);
1128            assertTrue("There should be selected value for DS2", rsResults.next());
1129            testValueDS2 = rsResults.getString(1);
1130            assertEquals("Incorrect value for data source 2", VALUE_DS2, testValueDS2);
1131
1132         }
1133         finally
1134         {
1135            DatabaseUtils.closeResultSetAndStatement(rsResults, selectStatement);
1136            rsResults = null;
1137            selectStatement = null;
1138         }
1139
1140         // set to DS1
1141
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
1142
1143         // Now try to select from DS1 using this connection
1144
try
1145         {
1146            selectStatement = con1.createStatement();
1147            rsResults = selectStatement.executeQuery(SELECT_VALUE1);
1148            assertTrue("There should be selected value for DS1", rsResults.next());
1149            testValueDS1 = rsResults.getString(1);
1150            assertEquals("Incorrect value for data source 1", VALUE_DS1, testValueDS1);
1151         }
1152         finally
1153         {
1154            DatabaseUtils.closeResultSetAndStatement(rsResults, selectStatement);
1155            rsResults = null;
1156            selectStatement = null;
1157         }
1158
1159         // At this point we know we have inserted correct records in particular
1160
// tables for particular data sources. Now try to retrieve data from TABLE 2
1161
// using data source 1 and retrieve data from TABLE 1 using data source 2.
1162
// Now try to select from DS1 using this connection
1163
try
1164         {
1165            selectStatement = con1.createStatement();
1166            // TODO: Bug: c3p0 if there is SQL Exception occured, c3p0 will explicitely
1167
// closed connection:
1168
// [c3p0] A PooledConnection died due to the following error!
1169
// PSQLException: ERROR: permission denied for relation req_conn_test2
1170
rsResults = selectStatement.executeQuery(SELECT_VALUE2);
1171            // we are expecting that rsResults will be null. Code retrieved data from
1172
// rsResults is for testing (debug) purposes
1173
if (rsResults.next())
1174            {
1175              testValueDS1 = rsResults.getString(1);
1176            }
1177            assertNull("The database by default doesn't isolate tables created by" +
1178                       " one user from tables created by other user since it should" +
1179                       " not be possible to select value from Table 2 for DS1",
1180                       rsResults);
1181         }
1182         catch (SQLException JavaDoc sqlExc)
1183         {
1184            DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con1);
1185            
1186            // This exception is expected, beacause there is not Table 2 for DS1
1187
// (Table 2 belongs to DS2)
1188
assertNull("There should not be selected value from Table 2 for DS1",
1189                       rsResults);
1190         }
1191         finally
1192         {
1193            DatabaseUtils.closeResultSetAndStatement(rsResults, selectStatement);
1194            rsResults = null;
1195            selectStatement = null;
1196         }
1197         
1198         // set to DS2
1199
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
1200
1201         try
1202         {
1203            selectStatement = con2.createStatement();
1204            rsResults = selectStatement.executeQuery(SELECT_VALUE1);
1205            if (rsResults.next())
1206            {
1207              testValueDS2 = rsResults.getString(1);
1208            }
1209
1210            assertNull("The database doesn't isolate tables created by one user" +
1211                       " from tables created by other user since it should not be" +
1212                       " possible to select value from Table 1 for DS2",
1213                       rsResults);
1214         }
1215         catch (SQLException JavaDoc sqlExc)
1216         {
1217            DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con2);
1218
1219            // This exception is expected, beacause there is not Table 1 for DS2
1220
// (Table 1 belongs to DS1)
1221
assertNull("There should not be selected value from Table 1 for DS2",
1222                        rsResults);
1223         }
1224         finally
1225         {
1226            DatabaseUtils.closeResultSetAndStatement(rsResults, selectStatement);
1227            rsResults = null;
1228            selectStatement = null;
1229         }
1230      }
1231      finally
1232      {
1233         Statement JavaDoc stmQuery = null;
1234
1235         try
1236         {
1237            // Execute this only if we allocated connection
1238
if (con1 != null)
1239            {
1240               // set to DS1
1241
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
1242            
1243               try
1244               {
1245                  stmQuery = con1.createStatement();
1246                  // drop table 1
1247
if (stmQuery.execute(DROP_TABLE1))
1248                  {
1249                     // Close any results
1250
stmQuery.getMoreResults(Statement.CLOSE_ALL_RESULTS);
1251                  }
1252                  // We are using 2 connections so we need to make commitTransaction for particular
1253
// connection. There will be better to have distributed connection manager.
1254
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(con1);
1255               }
1256               finally
1257               {
1258                   DatabaseUtils.closeStatement(stmQuery);
1259               }
1260            }
1261         }
1262         catch (Throwable JavaDoc thr)
1263         {
1264            // We are using 2 connections so we need to do rollbackTransaction for particular
1265
// connection.There will be better to have distributed connection manager.
1266
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con1);
1267            throw new Exception JavaDoc(thr);
1268         }
1269         finally
1270         {
1271            try
1272            {
1273               if (con2 != null)
1274               {
1275                  // set to DS2
1276
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
1277               
1278                  try
1279                  {
1280                     stmQuery = con2.createStatement();
1281                     // drop table 2
1282
if (stmQuery.execute(DROP_TABLE2))
1283                     {
1284                        // Close any results
1285
stmQuery.getMoreResults(Statement.CLOSE_ALL_RESULTS);
1286                     }
1287                  }
1288                  finally
1289                  {
1290                      DatabaseUtils.closeStatement(stmQuery);
1291                  }
1292                  // We are using 2 connections so we need to make commitTransaction for particular
1293
// connection. There will be better to have distributed connection manager.
1294
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(con2);
1295               }
1296            }
1297            catch (Throwable JavaDoc thr)
1298            {
1299               // We are using 2 connections so we need to do rollbackTransaction for particular
1300
// connection.There will be better to have distributed connection manager.
1301
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(con2);
1302               throw new Exception JavaDoc(thr);
1303            }
1304            finally
1305            {
1306               m_connectionFactory.returnConnection(con1);
1307               m_connectionFactory.returnConnection(con2);
1308            }
1309         }
1310      }
1311   }
1312
1313   /**
1314    * Test for requesting connection by user and password. There are 2 data sources.
1315    * There shoul be possible to switch them and retrieve connections from each one of them.
1316    * And select some data drom DB. These data should be different for both connections.
1317    *
1318    * @throws Exception - an error has occured during test
1319    */

1320   public void testRequestConnectionByUserAndPassword(
1321   ) throws Exception JavaDoc
1322   {
1323      Connection JavaDoc con1 = null;
1324      int testConCountDS1 = -1;
1325
1326      // at this moment there are added 2 data sources
1327

1328      // set to DS1, request connection from DS1 and get connection count for DS1
1329
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
1330      try
1331      {
1332         // Try to trequest connection using different user name only
1333
// Request autocommit true since we are just reading data from the database
1334
con1 = m_connectionFactory.requestConnection(true,
1335                                       m_strUsername + "_diff", m_strPassword);
1336         fail("The connection should have not been allocated.");
1337      }
1338      catch (OSSDatabaseAccessException daeExc)
1339      {
1340         // This exception is expected
1341
assertNull("There should be not requested connection for incorrect username", con1);
1342      }
1343      finally
1344      {
1345         // In case the connection was retrieved, return it, this will also
1346
// work if it is null
1347
m_connectionFactory.returnConnection(con1);
1348         con1 = null;
1349      }
1350      try
1351      {
1352         // TODO: Bug: Proxool: Here we request connection for user = bastatest
1353
// but an error will occur: User not found: BASTATEST_DIFF which shows as
1354
// SQLException below
1355
// Request autocommit true since we are just reading data from the database
1356
con1 = m_connectionFactory.requestConnection(true, m_strUsername, m_strPassword);
1357         testConCountDS1 = m_connectionFactory.getRequestedConnectionCount();
1358         
1359         assertEquals("Incorrect number of connections for DataSource 1", 1, testConCountDS1);
1360      }
1361      catch (OSSDatabaseAccessException ossExc)
1362      {
1363         // See the bug description above
1364
s_logger.log(Level.WARNING, "Unexpected exception has occured", ossExc);
1365         fail("Unexpected exception has occured: " + ossExc.getMessage());
1366      }
1367      finally
1368      {
1369         m_connectionFactory.returnConnection(con1);
1370      }
1371   }
1372
1373
1374   /**
1375    * Test for getting data source specified by name. There should be not changed to
1376    * default data source, only thing that will change will be maximal connection
1377    * count and connection count for specified data source.
1378    *
1379    * @throws Exception - an error has occured during test
1380    */

1381   
1382   public void testRequestConnectionCountByDataSource(
1383   ) throws Exception JavaDoc
1384   {
1385      Connection JavaDoc con1 = null;
1386      Connection JavaDoc con2 = null;
1387      int testReqConCount = -1;
1388      int testTotalReqConCount = -1;
1389
1390      try
1391      {
1392         // Check if there is set default data source 1.
1393
assertEquals("Incorrect default data source is specified",
1394                      DATASOURCE_NAME_1, m_connectionFactory.getDefaultDataSourceName());
1395
1396         // Check for total connection count
1397
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
1398         assertEquals("Incorrect initial total connection count.",
1399                      0, testTotalReqConCount);
1400
1401         // Check for connection count
1402
testReqConCount = m_connectionFactory.getRequestedConnectionCount();
1403         assertEquals("Incorrect initial connection count for data source 1.",
1404                      0, testReqConCount);
1405
1406         // Request connection from data source 2 (there should not be changed default data source)
1407
// Request autocommit true since we are just reading data from the database
1408
con2 = m_connectionFactory.requestConnection(true, DATASOURCE_NAME_2);
1409         assertTrue("Autocommit should be true for pooled connections.", con2.getAutoCommit());
1410         
1411         // Check if there is still default data source 1.
1412
assertEquals("There should be still datasource 1 specified as default",
1413                      DATASOURCE_NAME_1, m_connectionFactory.getDefaultDataSourceName());
1414
1415         // Check for total connection count
1416
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
1417         assertEquals("Incorrect total connection count after requesting connection " +
1418                      "from data source 2.", 1, testTotalReqConCount);
1419
1420         // Check for connection count of data source 1
1421
testReqConCount = m_connectionFactory.getRequestedConnectionCount();
1422         assertEquals("Incorrect connection count for data source 1.",
1423                      0, testReqConCount);
1424
1425         // Now set datasource 2 as default
1426
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
1427
1428         // Request connection from data source 1 (there should not be changed default data source)
1429
// Request autocommit true since we are just reading data from the database
1430
con1 = m_connectionFactory.requestConnection(true, DATASOURCE_NAME_1);
1431         assertTrue("Autocommit should be true for pooled connections.", con1.getAutoCommit());
1432
1433         // Check if there is still default data source 2.
1434
assertEquals("There should be still datasource 2 specified as default",
1435                      DATASOURCE_NAME_2, m_connectionFactory.getDefaultDataSourceName());
1436
1437         // Check for total connection count
1438
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
1439         assertEquals("Incorrect total connection count after requesting connection " +
1440                      "from data source 1.", 2, testTotalReqConCount);
1441
1442         // Check for connection count of data source 2
1443
testReqConCount = m_connectionFactory.getRequestedConnectionCount();
1444         assertEquals("Incorrect connection count for data source 2.",
1445                      1, testReqConCount);
1446
1447         // Now set again datasource 1 as default
1448
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
1449
1450         // Check for connection count of data source 1
1451
testReqConCount = m_connectionFactory.getRequestedConnectionCount();
1452         assertEquals("Incorrect connection count for data source 1.",
1453                      1, testReqConCount);
1454
1455      }
1456      finally
1457      {
1458         // return connections
1459
m_connectionFactory.returnConnection(con1);
1460         m_connectionFactory.returnConnection(con2);
1461      }
1462   }
1463
1464   /**
1465    * Test for getting data source specified by name. There should be not changed to
1466    * default data source, only thing that will change will be maximal connection
1467    * count and connection count for specified data source.
1468    *
1469    * @throws Exception - an error has occured during test
1470    */

1471   public void testRequestConnectionCountByDataSourceWithUserAndPasswd(
1472   ) throws Exception JavaDoc
1473   {
1474      Connection JavaDoc con1 = null;
1475      Connection JavaDoc con2 = null;
1476      int testReqConCount = -1;
1477      int testTotalReqConCount = -1;
1478
1479      try
1480      {
1481         // Check if there is set default data source 1.
1482
assertEquals("Incorrect default data source is specified",
1483                      DATASOURCE_NAME_1, m_connectionFactory.getDefaultDataSourceName());
1484
1485         // Check for total connection count
1486
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
1487         assertEquals("Incorrect initial total connection count.",
1488                      0, testTotalReqConCount);
1489
1490         // Check for connection count
1491
testReqConCount = m_connectionFactory.getRequestedConnectionCount();
1492         assertEquals("Incorrect initial connection count for data source 1.",
1493                      0, testReqConCount);
1494
1495         // Request connection from data source 2 (there should not be changed default data source)
1496
// Request autocommit true since we are just reading data from the database
1497
con2 = m_connectionFactory.requestConnection(true, DATASOURCE_NAME_2,
1498                                                      USERNAME_FOR_DS_2,
1499                                                      m_strPassword);
1500         assertTrue("Autocommit should be true for pooled connections.", con2.getAutoCommit());
1501         
1502         // Check if there is still default data source 1.
1503
assertEquals("There should be still datasource 1 specified as default",
1504                      DATASOURCE_NAME_1, m_connectionFactory.getDefaultDataSourceName());
1505
1506         // Check for total connection count
1507
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
1508         assertEquals("Incorrect total connection count after requesting connection " +
1509                      "from data source 2.", 1, testTotalReqConCount);
1510
1511         // Check for connection count of data source 1
1512
testReqConCount = m_connectionFactory.getRequestedConnectionCount();
1513         assertEquals("Incorrect connection count for data source 1.",
1514                      0, testReqConCount);
1515
1516         // Now set datasource 2 as default
1517
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_2);
1518
1519         // Request connection from data source 1 (there should not be changed default data source)
1520
// Request autocommit true since we are just reading data from the database
1521
con1 = m_connectionFactory.requestConnection(true, DATASOURCE_NAME_1,
1522                                                      m_strUsername,
1523                                                      m_strPassword);
1524         assertTrue("Autocommit should be true for pooled connections.", con1.getAutoCommit());
1525
1526         // Check if there is still default data source 2.
1527
assertEquals("There should be still datasource 2 specified as default",
1528                      DATASOURCE_NAME_2, m_connectionFactory.getDefaultDataSourceName());
1529
1530         // Check for total connection count
1531
testTotalReqConCount = m_connectionFactory.getTotalRequestedConnectionCount();
1532         assertEquals("Incorrect total connection count after requesting connection " +
1533                      "from data source 1.", 2, testTotalReqConCount);
1534
1535         // Check for connection count of data source 2
1536
testReqConCount = m_connectionFactory.getRequestedConnectionCount();
1537         assertEquals("Incorrect connection count for data source 2.",
1538                      1, testReqConCount);
1539
1540         // Now set again datasource 1 as default
1541
m_connectionFactory.setDefaultDataSourceName(DATASOURCE_NAME_1);
1542
1543         // Check for connection count of data source 1
1544
testReqConCount = m_connectionFactory.getRequestedConnectionCount();
1545         assertEquals("Incorrect connection count for data source 1.",
1546                      1, testReqConCount);
1547      }
1548      finally
1549      {
1550         // return connections
1551
m_connectionFactory.returnConnection(con1);
1552         m_connectionFactory.returnConnection(con2);
1553      }
1554   }
1555}
1556
Popular Tags