KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > persistence > core > BaseDAOTestCase


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

16 package com.blandware.atleap.persistence.core;
17
18 import junit.framework.TestCase;
19 import org.apache.commons.beanutils.BeanUtils;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.springframework.context.ApplicationContext;
23 import org.springframework.context.support.ClassPathXmlApplicationContext;
24 import org.springframework.util.ClassUtils;
25 import org.springframework.transaction.support.TransactionSynchronizationManager;
26 import org.springframework.orm.hibernate3.SessionHolder;
27 import org.springframework.orm.hibernate3.SessionFactoryUtils;
28 import org.springframework.dao.DataAccessResourceFailureException;
29 import org.hibernate.SessionFactory;
30 import org.hibernate.Session;
31 import org.hibernate.FlushMode;
32 import org.hibernate.Hibernate;
33
34 import java.util.Enumeration JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.MissingResourceException JavaDoc;
38 import java.util.ResourceBundle JavaDoc;
39
40 /**
41  * <p>Abstract base testcase for testing DAO. Provides facility for logging and
42  * methods for maintenance of Hibernate session lifecycle</p>
43  * <p><a HREF="BaseDAOTestCase.java.htm"><i>View Source</i></a></p>
44  *
45  * @author Matt Raible <a HREF="mailto:matt@raibledesigns.com">&lt;matt@raibledesigns.com&gt;</a>
46  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
47  * @version $Revision: 1.6 $ $Date: 2006/03/16 11:09:44 $
48  */

49 public abstract class BaseDAOTestCase extends TestCase {
50     protected final Log log = LogFactory.getLog(getClass());
51     protected final static ApplicationContext ctx;
52     protected ResourceBundle JavaDoc rb;
53
54     /**
55      * Session factory to use in test cases
56      */

57     protected SessionFactory sessionFactory;
58
59     /**
60      * Participation flag to determine, was session factory already bound to synchronization manager or not
61      */

62     private boolean participate;
63
64     /**
65      * Hibernate's session
66      */

67     private Session session;
68
69     // This static block ensures that Spring's BeanFactory is only loaded
70
// once for all tests
71
static {
72         String JavaDoc pkg = ClassUtils.classPackageAsResourcePath(BaseDAOTestCase.class);
73         /*
74             Description of files, which are used to create context instance:
75             1. First path points to applicationContext-resources.xml, which is located in the same dir as
76                the current file
77             2. Second path will add applicationContext-*.xml files, which are rest in the
78                 META-INF subdirectory of dao/gen directory, which in its turn is located in
79                 the project output directory. See target "package-dao" in the application build file to make
80                 it clear for you
81         */

82
83         String JavaDoc[] paths = {"classpath*:/" + pkg + "/applicationContext-*.xml",
84                 "classpath*:META-INF/applicationContext-*.xml"};
85         ctx = new ClassPathXmlApplicationContext(paths);
86     }
87
88
89     public BaseDAOTestCase() {
90         // Since a ResourceBundle is not required for each class, just
91
// do a simple check to see if one exists
92
String JavaDoc className = this.getClass().getName();
93
94         try {
95             rb = ResourceBundle.getBundle(className);
96         } catch ( MissingResourceException JavaDoc mre ) {
97             //log.warn("No resource bundle found for: " + className);
98
}
99     }
100
101     protected void setUp() throws Exception JavaDoc {
102         // open session
103
sessionFactory = lookupSessionFactory();
104         session = null;
105         participate = false;
106         if ( TransactionSynchronizationManager.hasResource(sessionFactory) ) {
107             // do not modify the Session: just set the participate flag
108
participate = true;
109         } else {
110             if ( log.isDebugEnabled() ) {
111                 log.debug("Opening temporary Hibernate session in test case");
112             }
113             session = getSession(sessionFactory);
114             session.setFlushMode(FlushMode.AUTO);
115             TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
116         }
117     }
118
119     protected void tearDown() throws Exception JavaDoc {
120         //close session
121
if ( !participate ) {
122             TransactionSynchronizationManager.unbindResource(sessionFactory);
123             if ( log.isDebugEnabled() ) {
124                 log.debug("Closing temporary Hibernate session in test case");
125             }
126             closeSession(session, sessionFactory);
127         }
128     }
129
130     /**
131      * Looks up the SessionFactory that this filter should use.
132      * <p>The default implementation looks for a bean with the specified name
133      * in Spring's root application context.
134      *
135      * @return the SessionFactory to use
136      * @see #getSessionFactoryBeanName
137      */

138     protected SessionFactory lookupSessionFactory() {
139         if ( log.isDebugEnabled() ) {
140             log.debug("Using session factory '" + getSessionFactoryBeanName() + "' for StartupListener");
141         }
142         return (SessionFactory) ctx.getBean(getSessionFactoryBeanName());
143     }
144
145     /**
146      * Returns the bean name of the SessionFactory to fetch from Spring's
147      * root application context.
148      *
149      * @return session factory bean name
150      */

151     protected String JavaDoc getSessionFactoryBeanName() {
152         return "sessionFactory";
153     }
154
155     /**
156      * Gets a Session for the SessionFactory that this listener uses.
157      * Note that this just applies in single session mode!
158      * <p>The default implementation delegates to SessionFactoryUtils'
159      * getSession method and sets the Session's flushMode to NEVER.
160      * <p>Can be overridden in subclasses for creating a Session with a custom
161      * entity interceptor or JDBC exception translator.
162      *
163      * @param sessionFactory the SessionFactory that this listener uses
164      * @return the Session to use
165      * @throws org.springframework.dao.DataAccessResourceFailureException
166      * if the Session could not be created
167      * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean)
168      * @see org.hibernate.FlushMode#NEVER
169      */

170     protected Session getSession(SessionFactory sessionFactory)
171             throws DataAccessResourceFailureException {
172         Session session = SessionFactoryUtils.getSession(sessionFactory, true);
173         session.setFlushMode(FlushMode.NEVER);
174         return session;
175     }
176
177     /**
178      * Closes the given Session.
179      * Note that this just applies in single session mode!
180      * <p>The default implementation delegates to SessionFactoryUtils'
181      * closeSessionIfNecessary method.
182      * <p>Can be overridden in subclasses, e.g. for flushing the Session before
183      * closing it. See class-level javadoc for a discussion of flush handling.
184      * Note that you should also override getSession accordingly, to set
185      * the flush mode to something else than NEVER.
186      *
187      * @param session the Session used for filtering
188      * @param sessionFactory the SessionFactory that this filter uses
189      */

190     protected void closeSession(Session session, SessionFactory sessionFactory) {
191         SessionFactoryUtils.releaseSession(session, sessionFactory);
192     }
193
194     /**
195      * Utility method to populate a javabean-style object with values
196      * from a Properties file
197      *
198      * @param obj bean to populate with properties
199      * @return populated bean
200      * @throws Exception
201      */

202     protected Object JavaDoc populate(Object JavaDoc obj) throws Exception JavaDoc {
203         // loop through all the beans methods and set its properties from
204
// its .properties file
205
Map JavaDoc map = new HashMap JavaDoc();
206
207         for ( Enumeration JavaDoc keys = rb.getKeys(); keys.hasMoreElements(); ) {
208             String JavaDoc key = (String JavaDoc) keys.nextElement();
209             map.put(key, rb.getString(key));
210         }
211
212         BeanUtils.copyProperties(obj, map);
213
214         return obj;
215     }
216 }
217
Popular Tags