1 package org.controlhaus.hibernate.util;
2
3 import java.lang.reflect.Method;
4 import java.sql.Connection;
5
6 import junit.framework.TestCase;
7
8 import net.sf.hibernate.Session;
9
10 import org.apache.beehive.controls.api.bean.Control;
11 import org.apache.beehive.controls.api.context.ControlBeanContext;
12 import org.apache.beehive.controls.runtime.bean.ControlContainerContext;
13 import org.controlhaus.hibernate.HibernateControl;
14
15 /***
16 * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a>
17 * @since Nov 5, 2004
18 */
19 public class AbstractHibernateTest
20 extends TestCase
21 {
22 public final static String SETUP_SQL = "hibernate.setupSql";
23 public final static String TEARDOWN_SQL = "hibernate.teardownSql";
24
25 private ControlContainerContext context;
26 private Connection conn;
27
28 @Control HibernateControl hibernate;
29
30 public void setUp() throws Exception
31 {
32 super.setUp();
33
34 context = new ControlContainerContext();
35
36 Class top = getClass();
37 while ( top != null )
38 {
39 initializeClass( top );
40 top = top.getSuperclass();
41 }
42
43 String filename = System.getProperty(SETUP_SQL);
44
45 if ( filename != null )
46 {
47 try
48 {
49 insertSqlFile(filename);
50 }
51 catch ( Exception e )
52 {
53 e.printStackTrace();
54 }
55 }
56 }
57
58 protected void initializeClass( Class clazz )
59 throws Exception
60 {
61 try
62 {
63 Class init = getClass().getClassLoader().loadClass(
64 clazz.getName() + "ClientInitializer" );
65
66 Method m = init.getMethod("initialize",
67 new Class[]
68 {
69 ControlBeanContext.class,
70 clazz
71 } );
72
73 m.invoke( null, new Object[] { context, this } );
74 }
75 catch ( ClassNotFoundException cnfe )
76 {
77
78 }
79 }
80
81 protected void insertSqlFile( String filename ) throws Exception
82 {
83 if ( hibernate == null )
84 throw new RuntimeException("AbstractHibernateTest was not initialized!");
85
86 Session sess = hibernate.getSessionFactory().openSession();
87 conn = sess.connection();
88 System.out.println("Loading SQL " + filename);
89 BatchSqlCommandRunner runner = new BatchSqlCommandRunner(conn);
90 runner.runCommands( filename );
91
92 sess.close();
93 }
94
95 public void tearDown() throws Exception
96 {
97 String filename = System.getProperty(TEARDOWN_SQL);
98
99 if ( filename != null )
100 {
101 try
102 {
103 insertSqlFile(filename);
104 }
105 catch ( Exception e )
106 {
107 e.printStackTrace();
108 }
109 }
110
111 conn = null;
112
113 super.tearDown();
114 }
115
116 public ControlContainerContext getContext()
117 {
118 return context;
119 }
120 }