KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > dbobj > tests > DBObjectTest


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.core.dbobj.tests;
66
67 import com.jcorporate.expresso.core.dataobjects.jdbc.LobField;
68 import com.jcorporate.expresso.core.db.DBConnection;
69 import com.jcorporate.expresso.core.db.DBConnectionPool;
70 import com.jcorporate.expresso.core.db.DBException;
71 import com.jcorporate.expresso.core.db.TableCreator;
72 import com.jcorporate.expresso.core.db.exception.DBRecordNotFoundException;
73 import com.jcorporate.expresso.core.misc.ConfigManager;
74 import com.jcorporate.expresso.core.misc.ConfigurationException;
75 import com.jcorporate.expresso.core.misc.DateTime;
76 import com.jcorporate.expresso.core.misc.StringUtil;
77 import com.jcorporate.expresso.services.test.TestSystemInitializer;
78 import junit.framework.Test;
79 import junit.framework.TestCase;
80 import junit.framework.TestSuite;
81 import org.apache.log4j.Logger;
82
83 import java.util.ArrayList JavaDoc;
84 import java.util.Enumeration JavaDoc;
85 import java.util.Iterator JavaDoc;
86 import java.util.Vector JavaDoc;
87
88
89 /**
90  * A test case to verify the functions of DBObject.
91  */

92 public class DBObjectTest
93         extends TestCase {
94     private static Logger log = Logger.getLogger(DBObjectTest.class);
95
96     /**
97      * Constructs a test case with the given name.
98      *
99      * @param name The name of the test case
100      */

101     public DBObjectTest(String JavaDoc name) {
102         super(name);
103     } /* DBObjectTest(String) */
104
105
106     public static void main(String JavaDoc[] args)
107             throws Exception JavaDoc {
108
109         //Set the system properties we need
110
junit.textui.TestRunner.run(suite());
111         ConfigManager.destroy();
112     }
113
114     /**
115      * Sets up the fixture, for example, open a network connection.
116      * This method is called before a test is executed.
117      *
118      * @throws Exception upon error
119      */

120     public void setUp()
121             throws Exception JavaDoc {
122         TestSystemInitializer.setUp();
123
124         try {
125             ConfigManager.getContext(TestSystemInitializer.getTestContext());
126         } catch (ConfigurationException ce) {
127             fail(
128                     "Specified context to test:" + TestSystemInitializer.getTestContext() + " but couldn't find that context");
129         }
130
131         TestSchema ts = new TestSchema();
132         Vector JavaDoc v = TableCreator.getInstance().createAsNeeded(ts, TestSystemInitializer.getTestContext());
133
134         for (Enumeration JavaDoc ev = v.elements(); ev.hasMoreElements();) {
135             log.info((String JavaDoc) ev.nextElement());
136         }
137     } /* setUp() */
138
139
140     /**
141      * Tears down the fixture, for example, close a network connection.
142      * This method is called after a test is executed.
143      *
144      * @throws Exception upon error
145      */

146     public void tearDown()
147             throws Exception JavaDoc {
148         try {
149
150             /* Clean out the test tables */
151             Test1 test1List = new Test1();
152             test1List.setDataContext(TestSystemInitializer.getTestContext());
153
154             test1List.deleteAll();
155
156             Test2 test2List = new Test2();
157             test2List.setDataContext(TestSystemInitializer.getTestContext());
158             test2List.deleteAll();
159
160         } catch (DBException de) {
161             de.printStackTrace();
162             log.error(de);
163         }
164     } /* tearDown() */
165
166     /**
167      * Tests to make sure get/set fields is working properly Specifically
168      * we also test that fields are appropriately set for null values.
169      */

170     public void testGetSetFields() {
171         try {
172             Test1 oneTest = new Test1();
173             oneTest.setDataContext(TestSystemInitializer.getTestContext());
174             oneTest.setField("TestKey", "1");
175
176             String JavaDoc value = oneTest.getField("CharTest");
177             assertTrue("Should be getting blank from value",
178                     value == null || value.length() == 0);
179
180             value = oneTest.getField("DecimalTest");
181             assertTrue("Should be getting blank from value",
182                     value == null || value.length() == 0);
183
184             value = oneTest.getField("IntTest");
185             assertTrue("Should be getting blank from value",
186                     value == null || value.length() == 0);
187
188             int testInt = oneTest.getFieldInt("IntTest");
189             assertTrue("Must get zero for blank field IntTest", testInt == 0);
190
191             boolean testBoolean = oneTest.getFieldBoolean("BooleanTest");
192             assertTrue("Must get false for blank field BooleanTest", testBoolean == false);
193
194             java.util.Date JavaDoc dt = oneTest.getFieldDate("DateTest");
195             assertTrue("Should get null date for blank field", dt == null);
196
197             float fl = oneTest.getFieldFloat("FloatTest");
198             assertTrue("Should get zero back for a blank float field", fl == 0.0);
199
200             value = oneTest.getFieldDecimalFormatted("DecimalTest", "######");
201             assertTrue("Should get null back for decimal formatted", value == null);
202
203
204             oneTest.setField("TextTest", "abcdefg");
205             oneTest.setField("BooleanTest", true);
206             oneTest.setField("CharTest", "abcd");
207             oneTest.setField("DecimalTest", "3");
208             oneTest.setField("FloatTest", "3.141");
209             oneTest.setField("IntTest", 123985);
210             oneTest.setField("VarCharTest", "lmnop");
211             oneTest.setField("DateTest", com.jcorporate.expresso.core.misc
212                     .DateTime.getDateForDB());
213
214
215             value = oneTest.getField("CharTest");
216             assertTrue("Should be getting abcd from CharTest got"
217                     + value + " instead", value.equals("abcd"));
218
219             value = oneTest.getField("DecimalTest");
220             assertTrue("Should be getting 3 from value got + " + value + " instead",
221                     value.equals("3"));
222
223             testInt = oneTest.getFieldInt("IntTest");
224             assertTrue("Must get 123985 for blank field IntTest got "
225                     + testInt + " instead", testInt == 123985);
226
227             testBoolean = oneTest.getFieldBoolean("BooleanTest");
228             assertTrue("Must get true for set field BooleanTest", testBoolean = true);
229
230             dt = oneTest.getFieldDate("DateTest");
231             assertTrue("Should not get a null date for set field", dt != null);
232
233             fl = oneTest.getFieldFloat("FloatTest");
234
235             assertTrue("Should get 3.141 for float value got " + fl + " instead",
236                     java.lang.Math.abs(fl - 3.141) < .001);
237
238         } catch (DBException ex) {
239             ex.printStackTrace();
240             fail("Caught exception testing update support" + ex.getMessage());
241         }
242     }
243
244
245     /**
246      * Test Adding the object to the database. We also test adding duplicate
247      * keys to the database
248      */

249     public void testAdd() {
250
251         try {
252
253             /* Add a record */
254             Test1 oneTest = new Test1();
255             oneTest.setDataContext(TestSystemInitializer.getTestContext());
256             oneTest.setField("TestKey", "1");
257             oneTest.setField("DateTest", "1999-10-01");
258             oneTest.setField("BooleanTest", true);
259             oneTest.setField("CharTest", "abcd");
260             oneTest.setField("DecimalTest", "3");
261             oneTest.setField("FloatTest", "3.141");
262             oneTest.setField("IntTest", 123985);
263             oneTest.setField("VarCharTest", "lmnop");
264
265             oneTest.add();
266             oneTest.clear();
267         } catch (DBException ce) {
268             log.error(ce);
269             fail("DB exception occurred - see log");
270         }
271         /* Try to add a duplicate - make sure it fails */
272         try {
273
274             /* Add a duplicate record */
275             Test1 oneTest = new Test1();
276             oneTest.setDataContext(TestSystemInitializer.getTestContext());
277             oneTest.setField("TestKey", "1");
278             log.warn(
279                     "About to throw intentional exception having to do with duplicate key. \nIgnore this dup-key exception.");
280             oneTest.add();
281             fail("Test add should have thrown exception on duplicate key here");
282         } catch (DBException ce) {
283
284             /* Do nothing here - it's good that we throw */
285         }
286
287         try {
288             Test1 oneTest = new Test1();
289             oneTest.setDataContext(TestSystemInitializer.getTestContext());
290             oneTest.setField("TestKey", "1");
291             oneTest.retrieve();
292         } catch (DBException ce) {
293             log.error(ce);
294             fail("DB exception occurred on retrieve test - see log");
295         }
296         try {
297             Test1 oneTest = new Test1();
298             oneTest.setDataContext(TestSystemInitializer.getTestContext());
299             oneTest.setField("TestKey", "1");
300
301             if (!oneTest.find()) {
302                 fail("DB exception occurred on find test - see log");
303             }
304         } catch (DBException ce) {
305             ce.printStackTrace();
306             log.error(ce);
307             fail("DB exception occurred on find test - see log");
308         }
309     }
310
311     /**
312      * Tests to make sure that we can work with custom where clauses and nothing
313      * breaks.
314      */

315     public void testCustomWhereClause() {
316         try {
317             /* Add a record */
318             Test1 oneTest = new Test1();
319             oneTest.setDataContext(TestSystemInitializer.getTestContext());
320             oneTest.setField("TestKey", "1");
321             oneTest.add();
322
323             oneTest.clear();
324             oneTest.setCustomWhereClause("TESTKEY = 1");
325             boolean found = oneTest.find();
326             assertTrue("Must find a record", found == true);
327
328             oneTest.clear();
329             oneTest.setCustomWhereClause("TESTKEY = 1");
330             int numRecords = oneTest.count();
331             assertTrue("Must have one record in the database table", numRecords == 1);
332         } catch (DBException ce) {
333             log.error(ce);
334             fail("DB exception occurred - see log");
335         }
336
337     }
338
339     /**
340      * Tests retrieve We also make sure that the exceptions we expect to be
341      * thrown are thrown... such as for bogus key values, keys not set.
342      */

343     public void testRetrieve() {
344         try {
345             /* Add a record */
346             Test1 oneTest = new Test1();
347             oneTest.setDataContext(TestSystemInitializer.getTestContext());
348             oneTest.setField("TestKey", "1");
349             oneTest.add();
350
351             oneTest.clear();
352             oneTest.setField("TestKey", "1");
353             oneTest.retrieve();
354             assertTrue("Should have proper return value for testkey",
355                     "1".equals(oneTest.getField("TestKey")));
356
357
358             oneTest.clear();
359             oneTest.setField("TestKey", "232");
360             try {
361                 oneTest.retrieve();
362                 fail("Retrieve for bogus key should have thrown DBRecordNotFoundException");
363             } catch (DBRecordNotFoundException ex) {
364                 //we're ok here.
365
}
366
367             oneTest.clear();
368             try {
369                 oneTest.retrieve();
370                 fail("Retrieve with no keys set should have thrown an exception");
371             } catch (DBException dbe) {
372                 //we're ok if we get here.
373
}
374         } catch (DBException ce) {
375             log.error(ce);
376             fail("DB exception occurred - see log");
377         }
378     }
379
380     /**
381      * Tests the 'setFieldsToRetrieve()' functionality.
382      */

383     public void testFieldsToRetrieve() {
384         try {
385             /* Add a record */
386             Test1 oneTest = new Test1();
387             oneTest.setDataContext(TestSystemInitializer.getTestContext());
388             oneTest.setField("TestKey", "1");
389             oneTest.setField("IntTest", 24);
390             oneTest.setField("FloatTest", "3.141592");
391             oneTest.add();
392
393             oneTest.clear();
394             oneTest.setField("TestKey", "1");
395             oneTest.setFieldsToRetrieve("TestKey|IntTest");
396             oneTest.retrieve();
397             assertTrue("Should have proper return value for testkey",
398                     "1".equals(oneTest.getField("TestKey")));
399
400             assertTrue("Should have retrieved TestInt field:",
401                     24 == oneTest.getFieldInt("IntTest"));
402
403             assertTrue("Should not have retrieved FloatTest:",
404                     oneTest.getDataField("FloatTest").isNull());
405
406             //Now make sure clear() properly resets the fields to retrieve
407
oneTest.clear();
408             oneTest.setField("TestKey", "1");
409             oneTest.clearFieldsToRetrieve();
410             oneTest.retrieve();
411             assertTrue("Should have proper return value for testkey",
412                     "1".equals(oneTest.getField("TestKey")));
413
414             assertTrue("Should have retrieved TestInt field:",
415                     24 == oneTest.getFieldInt("IntTest"));
416
417             assertTrue("Should have retrieved FloatTest:",
418                     !oneTest.getDataField("FloatTest").isNull());
419
420
421         } catch (DBException ce) {
422             log.error(ce);
423             fail("DB exception occurred - see log");
424         }
425
426     }
427
428     /**
429      * This test demonstrates/tests the basic functionality for Text-based
430      * data fields. You set and retrieve the text data as usual and the
431      * underlying framework saves/retrieves the CLOB field when you want it.
432      */

433     public void testCLOBSupport() {
434         final String JavaDoc testString = "LONG Character Update Test";
435         final String JavaDoc testKey = "1";
436         try {
437             Test1 oneTest = new Test1();
438             oneTest.setDataContext(TestSystemInitializer.getTestContext());
439             oneTest.setField("TestKey", testKey);
440             oneTest.setField("TextTest", testString);
441             oneTest.add();
442
443             oneTest.clear();
444             oneTest.setField("TestKey", testKey);
445             oneTest.retrieve();
446             String JavaDoc fieldData = oneTest.getField("TextTest");
447             assertTrue("CLOB Field data must not be null", fieldData != null);
448
449             assertTrue("CLOB field data must be equal to the original data. Got "
450                     + fieldData + " instead", testString.equals(fieldData));
451
452         } catch (Throwable JavaDoc t) {
453             t.printStackTrace();
454             fail("Caught exception testing CLOB Support: " + t.getMessage());
455         }
456     }
457
458     /**
459      * This test makes sure that special characters such as backslashes
460      * or single quotes get properly escaped so we read them back properly
461      */

462     public void testSpecialCharacters() {
463         final String JavaDoc testString = "' \\ abcdefg";
464         final String JavaDoc testKey = "1";
465
466         try {
467             Test1 oneTest = new Test1();
468             oneTest.setDataContext(TestSystemInitializer.getTestContext());
469             oneTest.setField("TestKey", testKey);
470             oneTest.setField("VarCharTest", testString);
471             oneTest.setField("CharTest", testString);
472             oneTest.add();
473
474             oneTest.clear();
475             oneTest.setField("TestKey", testKey);
476             oneTest.retrieve();
477             String JavaDoc fieldData = oneTest.getField("VarCharTest");
478             assertTrue("Varchar Field data must not be null", fieldData != null);
479
480             assertTrue("Varchar field data must be equal to the original data. Got "
481                     + fieldData + " instead", testString.equals(fieldData));
482             fieldData = oneTest.getField("CharTest");
483             assertTrue("CharTest Field data must not be null", fieldData != null);
484
485             assertTrue("CharTest field data must be equal to the original data. Got "
486                     + fieldData + " instead", testString.equals(fieldData));
487         } catch (Exception JavaDoc ex) {
488             ex.printStackTrace();
489             fail("Caught exception processing Special Characters "
490                     + ex.getMessage());
491         }
492
493     }
494
495
496     /**
497      * Test Transaction Capabilities
498      */

499     public void testTransactions() {
500         try {
501             DBConnectionPool pool = DBConnectionPool.getInstance(TestSystemInitializer.getTestContext());
502             DBConnection oneConnection = pool.getConnection("Test Transaction");
503             if (!oneConnection.supportsTransactions()) {
504                 log.warn("Cannot test transactions because this DB does not support them.");
505                 oneConnection.release();
506                 return;
507             }
508
509
510             try {
511
512                 // before test, make sure no object exists in db (during autocommit)
513
Test1 test1 = new Test1(oneConnection);
514                 test1.setField("TestKey", 1);
515                 if (test1.find()) test1.delete();
516
517                 //
518
// turn on transaction
519
//
520
oneConnection.setAutoCommit(false);
521
522                 // add item during transaction
523
test1 = new Test1(oneConnection);
524                 test1.setField("TestKey", 1);
525                 test1.setField("TextTest", "Long Test");
526                 test1.add();
527
528                 // different object
529
Test2 test2 = new Test2(oneConnection);
530                 test2.setField("TestKey", 1);
531                 test2.add();
532
533                 //
534
// ok, rollback, which should remove objects
535
//
536
oneConnection.rollback();
537
538                 assertTrue(test1.count() == 0);
539                 assertTrue(test2.count() == 0);
540
541                 //
542
//Now add and commit.
543
//
544
test1.setField("TestKey", 1);
545                 test1.setField("TextTest", "Long Test");
546                 test1.add();
547
548                 test2.setField("TestKey", 1);
549                 test2.add();
550                 oneConnection.commit();
551                 assertTrue(test1.count() == 1);
552                 assertTrue(test2.count() == 1);
553
554                 //
555
//Try clear, retrieve, update, clear, retrieve, update
556
//
557
test1.clear();
558                 test1.setField("TestKey", 1);
559                 test1.retrieve();
560
561                 test1.setField("TextTest", "Some other value");
562                 test1.update();
563
564                 test1.clear();
565                 test1.setField("TestKey", 1);
566                 test1.setField("TextTest", "Yet another Value");
567                 test1.update();
568
569                 test1.clear();
570                 test1.setField("TestKey", 1);
571                 test1.retrieve();
572
573
574             } catch (DBException dbe) {
575                 try {
576                     oneConnection.rollback();
577                 } catch (DBException ex) {
578                     log.error("Error rolling back transaction");
579                 }
580                 dbe.printStackTrace();
581                 fail("Caught DBException attempting to execute statements");
582             } finally {
583                 pool.release(oneConnection);
584             }
585
586         } catch (Exception JavaDoc ex) {
587             ex.printStackTrace();
588             fail("Caught exception processing TestTransaction "
589                     + ex.getMessage());
590         }
591     }
592
593     /**
594      * This test demonstrates/tests the basic functionality for binary-based
595      * data fields. You must use the saveBinaryField as a separate method rather
596      * than setField.
597      */

598     public void testBLOBSupport() {
599         final Integer JavaDoc testInt = new Integer JavaDoc(-3544);
600         final String JavaDoc testKey = "1";
601         try {
602             java.io.ByteArrayOutputStream JavaDoc bos = new java.io.ByteArrayOutputStream JavaDoc(128);
603             java.io.ObjectOutputStream JavaDoc oos = new java.io.ObjectOutputStream JavaDoc(bos);
604             oos.writeObject(testInt);
605             byte buffer[] = bos.toByteArray();
606
607
608             Test1 oneTest = new Test1();
609             oneTest.setDataContext(TestSystemInitializer.getTestContext());
610             oneTest.setField("TestKey", testKey);
611             oneTest.add();
612             oneTest.saveBinaryField("BinaryTest", buffer);
613
614             oneTest.clear();
615             oneTest.setField("TestKey", testKey);
616             LobField query = new LobField();
617             query.setCriteria(oneTest);
618             java.io.InputStream JavaDoc is = query.getBlobStream("BinaryTest");
619             assertTrue("Blob Input stream data must not be null", is != null);
620
621             java.io.ObjectInputStream JavaDoc ois = new java.io.ObjectInputStream JavaDoc(is);
622             Object JavaDoc o = ois.readObject();
623             assertTrue("Read object must not be null", o != null);
624             assertTrue("Read object must be of type java.lang.Integer", o instanceof Integer JavaDoc);
625             Integer JavaDoc i = (Integer JavaDoc) o;
626             assertTrue("Binary field data must be equal to original data. Got " + i.intValue() +
627                     " instead of " + testInt.intValue(), i.intValue() == testInt.intValue());
628
629
630         } catch (Throwable JavaDoc t) {
631             t.printStackTrace();
632             fail("Caught exception testing BLOB Support: " + t.getMessage());
633         }
634     }
635
636     /**
637      * Tests to make sure that after setting a null integer and adding it to the
638      * database, that the field is still null after a retrieval.
639      */

640     public void testNullFields() {
641         try {
642             /* Add a record */
643             Test1 oneTest = new Test1();
644             oneTest.setDataContext(TestSystemInitializer.getTestContext());
645             oneTest.setField("TestKey", "1");
646             oneTest.add();
647             oneTest.clear();
648
649             oneTest.setField("TestKey", "1");
650             if (!oneTest.find()) {
651                 fail("Unable to locate record we just updated");
652             }
653
654             assertTrue("Test Integer field must be null", oneTest.isFieldNull("IntTest"));
655             assertTrue("NumericTest field must be null", oneTest.isFieldNull("NumericTest"));
656             assertTrue("BigIntTestfield must be null", oneTest.isFieldNull("BigIntTest"));
657             assertTrue("BooleanTest must be null", oneTest.isFieldNull("BooleanTest"));
658             assertTrue("CharTest field must be null", oneTest.isFieldNull("CharTest"));
659             assertTrue("DateTest field must be null", oneTest.isFieldNull("DateTest"));
660             assertTrue("DecimalTest field must be null", oneTest.isFieldNull("DecimalTest"));
661             assertTrue("DoubleTest field must be null", oneTest.isFieldNull("DoubleTest"));
662             assertTrue("FloatTest field must be null", oneTest.isFieldNull("FloatTest"));
663             assertTrue("RealTest field must be null", oneTest.isFieldNull("RealTest"));
664             assertTrue("SmallIntTest field must be null", oneTest.isFieldNull("SmallIntTest"));
665             assertTrue("TimeTest field must be null", oneTest.isFieldNull("TimeTest"));
666             assertTrue("TimeStampTest field must be null", oneTest.isFieldNull("TimeStampTest"));
667             assertTrue("DateTimeTest field must be null", oneTest.isFieldNull("DateTimeTest"));
668             assertTrue("TinyIntTest field must be null", oneTest.isFieldNull("TinyIntTest"));
669             assertTrue("VarCharTest field must be null", oneTest.isFieldNull("VarCharTest"));
670             assertTrue("TextTest field must be null", oneTest.isFieldNull("TextTest"));
671             assertTrue("AutoIncTest field must NOT be null", !oneTest.isFieldNull("AutoIncTest"));
672
673             oneTest.setField("NumericTest", "3.1415");
674             oneTest.clear();
675             oneTest.setField("TestKey", "1");
676             //This is invalid because after we've done an update to a field that
677
//doesn't do autoinc'ing we lose data.
678
// oneTest.update(); //We do this update to clear the cache.
679
oneTest.removeFromCache(oneTest);
680             oneTest.clear();
681             oneTest.setField("TestKey", "1");
682             oneTest.retrieve();
683             assertTrue("Test Integer field must be null", oneTest.isFieldNull("IntTest"));
684             assertTrue("NumericTest field must be null", oneTest.isFieldNull("NumericTest"));
685             assertTrue("BigIntTestfield must be null", oneTest.isFieldNull("BigIntTest"));
686             assertTrue("BooleanTest must be null", oneTest.isFieldNull("BooleanTest"));
687             assertTrue("CharTest field must be null", oneTest.isFieldNull("CharTest"));
688             assertTrue("DateTest field must be null", oneTest.isFieldNull("DateTest"));
689             assertTrue("DecimalTest field must be null", oneTest.isFieldNull("DecimalTest"));
690             assertTrue("DoubleTest field must be null", oneTest.isFieldNull("DoubleTest"));
691             assertTrue("FloatTest field must be null", oneTest.isFieldNull("FloatTest"));
692             assertTrue("RealTest field must be null", oneTest.isFieldNull("RealTest"));
693             assertTrue("SmallIntTest field must be null", oneTest.isFieldNull("SmallIntTest"));
694             assertTrue("TimeTest field must be null", oneTest.isFieldNull("TimeTest"));
695             assertTrue("TimeStampTest field must be null", oneTest.isFieldNull("TimeStampTest"));
696             assertTrue("DateTimeTest field must be null", oneTest.isFieldNull("DateTimeTest"));
697             assertTrue("TinyIntTest field must be null", oneTest.isFieldNull("TinyIntTest"));
698             assertTrue("VarCharTest field must be null", oneTest.isFieldNull("VarCharTest"));
699             assertTrue("TextTest field must be null", oneTest.isFieldNull("TextTest"));
700             assertTrue("AutoIncTest field must NOT be null", !oneTest.isFieldNull("AutoIncTest"));
701
702
703             oneTest.delete();
704         } catch (DBException ex) {
705             ex.printStackTrace();
706             fail("Caught exception testing null Integer" + ex.getMessage());
707         }
708
709     }
710
711     public void testNullValues() {
712         String JavaDoc resourceId = null;
713         try {
714             log.info("Test null values");
715             Test1 resource = new Test1();
716             resource.setDataContext(TestSystemInitializer.getTestContext());
717             resource.setField("TestKey", 1);
718             resource.setField("CharTest", "FZI");
719             resource.setField("DateTimeTest",
720                     DateTime.getDateTimeForDB(resource.getDataContext()));
721             resource.add();
722             resourceId = resource.getField("TestKey");
723             resource = new Test1();
724             resource.setDataContext(TestSystemInitializer.getTestContext());
725             resource.setField("TestKey", resourceId);
726             resource.retrieve();
727             assertTrue(resource.isFieldNull("VarCharTest"));
728             assertTrue(resource.isFieldNull("IntTest"));
729             resource.retrieve();
730             assertTrue(resource.isFieldNull("VarCharTest"));
731             assertTrue(resource.isFieldNull("IntTest"));
732             resource.addOrUpdate();
733             resource = new Test1();
734             resource.setDataContext(TestSystemInitializer.getTestContext());
735             resource.setField("TestKey", resourceId);
736             resource.retrieve();
737             assertTrue(resource.isFieldNull("VarCharTest"));
738             assertTrue(resource.isFieldNull("IntTest"));
739             resource.setField("VarCharTest", "Hi!");
740             resource.addOrUpdate();
741             resource.retrieve();
742             assertFalse(resource.isFieldNull("VarCharTest"));
743             assertTrue(resource.isFieldNull("IntTest"));
744             resource.setField("VarCharTest", (String JavaDoc) null);
745             resource.addOrUpdate();
746             resource.retrieve();
747             assertTrue(resource.isFieldNull("VarCharTest"));
748             assertTrue(resource.isFieldNull("IntTest"));
749         } catch (Exception JavaDoc e) {
750             log.error(e);
751             fail("Exception occured:" + e.getMessage());
752         }
753     }
754
755
756     /**
757      * Tests the DBObject update routine.
758      */

759     public void testUpdate() {
760         try {
761             /* Add a record */
762             Test1 oneTest = new Test1();
763             oneTest.setDataContext(TestSystemInitializer.getTestContext());
764             oneTest.setField("TestKey", "1");
765             oneTest.add();
766
767             oneTest.setField("TextTest", "abcdefg");
768             oneTest.setField("BooleanTest", true);
769             oneTest.setField("CharTest", "abcd");
770             oneTest.setField("DecimalTest", "3");
771             oneTest.setField("FloatTest", "3.141");
772             oneTest.setField("IntTest", 123985);
773             oneTest.setField("VarCharTest", "lmnop");
774             oneTest.setField("DateTest", "1999-10-01");
775             oneTest.update();
776
777             //Make sure it really was there.
778
oneTest.clear();
779             oneTest.setField("TestKey", "1");
780             if (!oneTest.find()) {
781                 fail("Unable to locate record we just updated");
782             }
783             oneTest.delete();
784         } catch (DBException ex) {
785             ex.printStackTrace();
786             fail("Caught exception testing update support" + ex.getMessage());
787         }
788
789     }
790
791     /**
792      * This function tests adding blank dates since some databases don't tolerate
793      * it very well.
794      */

795     public void testDateAdd() {
796         final String JavaDoc testStringValue = "";
797         final String JavaDoc testKey = "1";
798         try {
799             Test1 oneTest = new Test1();
800             oneTest.setDataContext(TestSystemInitializer.getTestContext());
801             oneTest.setField("TestKey", testKey);
802             oneTest.setField("DateTest", testStringValue);
803             oneTest.add();
804
805             oneTest.clear();
806             oneTest.setField("TestKey", testKey);
807             oneTest.retrieve();
808
809             String JavaDoc fieldData = oneTest.getField("DateTest");
810             assertTrue(fieldData.equals(testStringValue));
811
812         } catch (Throwable JavaDoc t) {
813             t.printStackTrace();
814             fail("Caught exception testing CLOB Support: " + t.getMessage());
815         }
816     }
817
818     public void testDateSetField() {
819         final String JavaDoc testKey = "1";
820         try {
821             Test1 oneTest = new Test1();
822             oneTest.setDataContext(TestSystemInitializer.getTestContext());
823             oneTest.setField("TestKey", testKey);
824             oneTest.setField("DateTest", new java.util.Date JavaDoc());
825             oneTest.setField("DateTimeTest", new java.util.Date JavaDoc());
826             oneTest.setField("TimeTest", new java.util.Date JavaDoc());
827             oneTest.add();
828
829             oneTest.clear();
830             oneTest.setField("TestKey", testKey);
831             oneTest.retrieve();
832
833             System.out.println("Date: " + oneTest.getField("DateTest"));
834             System.out.println("DateTime: " + oneTest.getField("DateTimeTest"));
835             System.out.println("Time: " + oneTest.getField("TimeTest"));
836 // assertTrue(fieldData.equals(testStringValue));
837

838         } catch (Throwable JavaDoc t) {
839             t.printStackTrace();
840             fail("Caught exception testing CLOB Support: " + t.getMessage());
841         }
842     }
843
844
845     /**
846      * This test case throws a batch of range strings into some search and
847      * retrieve calls to see if we can get improper sql generated and thus
848      * throw an exception
849      */

850     public void testRangeStrings() {
851         try {
852             Test1 oneTest = new Test1();
853             oneTest.setDataContext(TestSystemInitializer.getTestContext());
854             oneTest.setField("IntTest", "> 0");
855             oneTest.find();
856
857             oneTest.clear();
858             oneTest.setField("IntTest", ">= 0");
859             oneTest.find();
860
861             oneTest.clear();
862             oneTest.setField("IntTest", "<= 0");
863             oneTest.find();
864
865             oneTest.clear();
866             oneTest.setField("IntTest", "< 0");
867             oneTest.find();
868
869             oneTest.clear();
870             oneTest.setField("IntTest", ">= 0");
871             oneTest.find();
872
873             oneTest.clear();
874             oneTest.setField("IntTest", "IN (0,1)");
875             oneTest.find();
876
877             oneTest.clear();
878             oneTest.setField("DateTest", "BETWEEN '1988-03-01' AND '2036-01-01'");
879             oneTest.find();
880
881
882             //Added 2/18/04 - breaking >'date value'
883
oneTest.clear();
884             oneTest.setField("DateTest",
885                     ">" + "'"
886                     + DateTime.getDateForDB(new java.util.Date JavaDoc(), TestSystemInitializer.getTestContext()) + "'");
887             oneTest.find();
888
889             oneTest.clear();
890             oneTest.setField("DateTest",
891                     "<" + "'"
892                     + DateTime.getDateForDB(new java.util.Date JavaDoc(), TestSystemInitializer.getTestContext()) + "'");
893             oneTest.find();
894
895             oneTest.clear();
896             oneTest.setField("DateTest",
897                     "> " + "'"
898                     + DateTime.getDateForDB(new java.util.Date JavaDoc(), TestSystemInitializer.getTestContext()) + "'");
899             oneTest.find();
900
901             oneTest.clear();
902             oneTest.setField("DateTest",
903                     "<= " + "'"
904                     + DateTime.getDateForDB(new java.util.Date JavaDoc(), TestSystemInitializer.getTestContext()) + "'");
905             oneTest.find();
906
907             oneTest.clear();
908             oneTest.setField("SmallIntTest", ">= 3");
909             oneTest.setField("TinyIntTest", "< 1");
910             oneTest.find();
911
912         } catch (DBException ex) {
913             ex.printStackTrace();
914             fail("Caught Exception testing range strings: " + ex.getMessage());
915         }
916
917     }
918
919     /**
920      * Test case that tries to set bad ranges to trip up the field range parser
921      */

922     public void testBadRangeStrings() {
923
924         try {
925             Test1 oneTest = new Test1();
926             oneTest.setDataContext(TestSystemInitializer.getTestContext());
927             oneTest.setField("IntTest", "> '10402'");
928             try {
929                 oneTest.find();
930                 fail("Should have thrown an exception");
931             } catch (DBException ex1) {
932
933             }
934
935             oneTest.clear();
936             oneTest.setField("IntTest", ">= ';SELECT * FROM USERSTABLE'");
937             try {
938                 oneTest.find();
939                 fail("Should have thrown an exception");
940             } catch (DBException ex2) {
941             }
942
943             oneTest.clear();
944             oneTest.setField("IntTest", "10;");
945             try {
946                 oneTest.find();
947                 fail("Should have thrown an exception");
948             } catch (DBException ex3) {
949             }
950
951             oneTest.clear();
952             oneTest.setField("VarCharTest", "<10'';");
953             try {
954                 oneTest.find();
955                 fail("Should have thrown an exception");
956             } catch (DBException ex3) {
957             }
958
959
960         } catch (DBException ex) {
961             ex.printStackTrace();
962             fail("Caught Exception testing range strings: " + ex.getMessage());
963         }
964
965     }
966
967
968     /**
969      * Tests batch add and compares it's performance to the equivalant of
970      * adding x man records through <code>DBObject.add();</code>
971      */

972     public void testBatchAdd() {
973         final int arraySize = 20;
974         Test1 objects[] = new Test1[arraySize];
975         ArrayList JavaDoc addObjects = new ArrayList JavaDoc(arraySize);
976         long startTime = 0;
977         long endTime = 0;
978
979         try {
980             for (int i = 0; i < arraySize; i++) {
981                 objects[i] = new Test1();
982                 objects[i].setDataContext(TestSystemInitializer.getTestContext());
983                 objects[i].setField("TestKey", Integer.toString(i));
984                 objects[i].setField("VarCharTest", Integer.toString(i));
985                 objects[i].setField("DateTest", "1999-10-01");
986                 objects[i].setField("BooleanTest", true);
987                 objects[i].setField("CharTest", "abcd");
988                 objects[i].setField("DecimalTest", "3");
989                 objects[i].setField("FloatTest", "3.141");
990                 objects[i].setField("IntTest", 123985);
991                 addObjects.add(objects[i]);
992             }
993
994             //
995
//
996
//For a test, we compare it to adding normally
997
//
998
//
999
startTime = System.currentTimeMillis();
1000            for (Iterator JavaDoc i = addObjects.iterator(); i.hasNext();) {
1001                Test1 oneObj = (Test1) i.next();
1002                oneObj.add();
1003            }
1004            endTime = System.currentTimeMillis();
1005            System.out.println("\nTime it took to add " + arraySize +
1006                    " objects through DBObject.add(): " +
1007                    (endTime - startTime) + " ms.");
1008
1009            //Now remove everything from the database
1010
Test1 deleter = new Test1();
1011            deleter.setDataContext(TestSystemInitializer.getTestContext());
1012
1013            deleter.deleteAll();
1014
1015
1016            com.jcorporate.expresso.core.dataobjects.jdbc.JDBCExecutor
1017                    executor = new com.jcorporate.expresso.core.dataobjects.jdbc.JDBCExecutor();
1018            startTime = System.currentTimeMillis();
1019            executor.addBatch(addObjects);
1020            endTime = System.currentTimeMillis();
1021            System.out.println("Time it took to add " + arraySize +
1022                    " objects through JDBCExecutor.addBatch(): " +
1023                    (endTime - startTime) + " ms.");
1024        } catch (Exception JavaDoc ex) {
1025            ex.printStackTrace();
1026            fail("Caught exception testing batch update support" + ex.getMessage());
1027        }
1028
1029    }
1030
1031    /**
1032     * Tests the JDBC Executor Batch Update Capabilities.
1033     */

1034    public void testBatchUpdate() {
1035        final int arraySize = 20;
1036        Test1 objects[] = new Test1[arraySize];
1037        ArrayList JavaDoc updateObjects = new ArrayList JavaDoc(arraySize);
1038        long startTime = 0;
1039        long endTime = 0;
1040
1041        try {
1042            //
1043
//Setup Add a batch of objects to the database
1044
//
1045
for (int i = 0; i < arraySize; i++) {
1046                objects[i] = new Test1();
1047                objects[i].setDataContext(TestSystemInitializer.getTestContext());
1048                objects[i].setField("TestKey", Integer.toString(i));
1049                objects[i].setField("DateTest", "1999-10-01");
1050                objects[i].setField("BooleanTest", true);
1051                objects[i].setField("CharTest", "abcd");
1052                objects[i].setField("DecimalTest", "3");
1053                objects[i].setField("FloatTest", "3.141");
1054                objects[i].setField("IntTest", 123985);
1055                objects[i].add();
1056                updateObjects.add(objects[i]);
1057            }
1058
1059
1060            //
1061
//Ok, now iterate through and let's tweak some values
1062
//
1063
for (int i = 0; i < arraySize; i++) {
1064                objects[i].setField("VarCharTest", Integer.toString(i));
1065            }
1066
1067            //
1068
//For a test, we compare it to updating normally
1069
//
1070
startTime = System.currentTimeMillis();
1071            for (int i = 0; i < arraySize; i++) {
1072                objects[i].update();
1073            }
1074            endTime = System.currentTimeMillis();
1075
1076            System.out.println("\nTime it took to update " + arraySize +
1077                    " objects through DBObject.update(): " +
1078                    (endTime - startTime) + " ms.");
1079
1080            for (int i = 0; i < arraySize; i++) {
1081                objects[i].setField("VarCharTest", Integer.toString(-1 * i));
1082                objects[i].setField("DateTest", "1999-10-02");
1083            }
1084
1085            com.jcorporate.expresso.core.dataobjects.jdbc.JDBCExecutor
1086                    executor = new com.jcorporate.expresso.core.dataobjects.jdbc.JDBCExecutor();
1087            startTime = System.currentTimeMillis();
1088            executor.updateBatch(updateObjects);
1089            endTime = System.currentTimeMillis();
1090            System.out.println("Time it took to update " + arraySize +
1091                    " objects through JDBCExecutor.updateBatch(): " +
1092                    (endTime - startTime) + " ms.");
1093        } catch (Exception JavaDoc ex) {
1094            ex.printStackTrace();
1095            fail("Caught exception testing batch update support" + ex.getMessage());
1096        }
1097
1098    }
1099
1100    /**
1101     * test the proper handling of large chunks of text using Clob (as mapped by expresso-config.xml)
1102     * with 40K, 80K, 120K, 160K, 200K chars
1103     */

1104    public void testLargeText() {
1105        try {
1106            Test1 setter = null;
1107
1108            for (int i = 1; i < 5; i++) {
1109                String JavaDoc teststr = StringUtil.repeatString("0123456789", 4000 * i);
1110                setter = new Test1();
1111                setter.setDataContext(TestSystemInitializer.getTestContext());
1112                setter.setField("TestKey", 1);
1113                log.warn("Set CLOB field to " + teststr.length() + " chars.");
1114                boolean found = setter.find();
1115
1116                setter.setField("ClobTest", teststr);
1117                if (found)
1118                    setter.update();
1119                else
1120                    setter.add();
1121
1122                Test1 getter = new Test1();
1123                getter.setDataContext(TestSystemInitializer.getTestContext());
1124                getter.setField("TestKey", 1);
1125                getter.retrieve();
1126
1127// assertTrue("Clob is empty" , getter.getField("ClobTest").length() > 0);
1128
assertEquals(teststr.length(), getter.getField("ClobTest").length());
1129
1130            }
1131
1132            setter.clear();
1133            setter.setField("TestKey", 1);
1134            setter.delete();
1135        } catch (DBException e) {
1136            log.error("DBException!", e);
1137            fail("Exception occured:" + e.getMessage());
1138        }
1139    }
1140
1141    public void testResourceTransaction() {
1142        String JavaDoc resourceId = null;
1143        DBConnectionPool myPool = null;
1144        DBConnection myConnection = null;
1145        try {
1146            try {
1147                myPool =
1148                        DBConnectionPool.getInstance(TestSystemInitializer.getTestContext());
1149                myConnection = myPool.getConnection();
1150                if (!myConnection.supportsTransactions()) {
1151                    log.warn("Cannot test transactions because this DB does not support them.");
1152                    return;
1153                }
1154                myConnection.setAutoCommit(false);
1155                log.info("Add a resource");
1156                Test1 resource = new Test1(myConnection);
1157                resource.setField("TestKey", 1);
1158                resource.add();
1159                myConnection.commit();
1160                log.info("Try to delete and after that add the resource");
1161                resource = new Test1(myConnection);
1162                resource.deleteAll();
1163                resource.clear();
1164                resource.setField("TestKey", 2);
1165                resource.add();
1166                myConnection.commit();
1167            } catch (DBException e) {
1168                log.error("DBException!", e);
1169                if (myConnection != null)
1170                    myConnection.rollback();
1171                fail("Exception occured:" + e.getMessage());
1172            } finally {
1173                if (myPool != null) {
1174                    myPool.release(myConnection);
1175                }
1176            }
1177        } catch (DBException e) {
1178            log.error("DBException!", e);
1179            fail("Exception occured:" + e.getMessage());
1180        }
1181
1182
1183        try {
1184            log.info("Delete resource:" + resourceId);
1185            Test1 resource = new Test1();
1186            resource.setDataContext(TestSystemInitializer.getTestContext());
1187            resource.deleteAll();
1188        } catch (Exception JavaDoc e) {
1189            log.error(e);
1190            fail("Exception occured:" + e.getMessage());
1191        }
1192    }
1193
1194    public void testDefaultValues() throws DBException {
1195        Test2 test2 = new Test2();
1196        assertEquals("This is a test", test2.getMetaData().getDefaultValue("Descrip"));
1197    }
1198
1199
1200    /**
1201     * Define the suite of tests that verify each function of the cache
1202     *
1203     * @return an instantiated test suite
1204     */

1205    public static Test suite() {
1206        TestSuite suite = new TestSuite(DBObjectTest.class);
1207
1208        return suite;
1209    } /* suite() */
1210
1211} /* DBObjectTest */
1212
Popular Tags