View Javadoc
1   package org.itracker;
2   
3   import org.apache.log4j.Logger;
4   import org.dbunit.database.DatabaseConfig;
5   import org.dbunit.database.DatabaseConnection;
6   import org.dbunit.dataset.CompositeDataSet;
7   import org.dbunit.dataset.IDataSet;
8   import org.dbunit.dataset.xml.XmlDataSet;
9   import org.dbunit.ext.hsqldb.HsqldbDataTypeFactory;
10  import org.dbunit.operation.DatabaseOperation;
11  import org.hibernate.Session;
12  import org.hibernate.SessionFactory;
13  import org.itracker.core.resources.ITrackerResources;
14  import org.itracker.core.resources.ITrackerResourcesProvider;
15  import org.itracker.model.Language;
16  import org.itracker.persistence.dao.LanguageDAO;
17  import org.itracker.util.NamingUtilites;
18  import org.junit.After;
19  import org.junit.Before;
20  import org.springframework.orm.hibernate3.SessionHolder;
21  import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
22  import org.springframework.test.context.ContextConfiguration;
23  import org.springframework.transaction.support.TransactionSynchronizationManager;
24  
25  import javax.naming.Context;
26  import javax.naming.InitialContext;
27  import javax.naming.NameNotFoundException;
28  import javax.naming.NamingException;
29  import javax.sql.DataSource;
30  import java.sql.SQLException;
31  import java.util.*;
32  
33  @ContextConfiguration("/application-context.xml")
34  public abstract class AbstractDependencyInjectionTest extends
35          org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests {
36  
37      private static final Logger log = Logger
38              .getLogger(AbstractDependencyInjectionSpringContextTests.class);
39      private DataSource dataSource;
40      public ClassLoader classLoader;
41      public IDataSet dataSet;
42      private SessionFactory sessionFactory;
43      private HashSet<String> definedLocales;
44  
45      protected AbstractDependencyInjectionTest() {
46          classLoader = getClass().getClassLoader();
47      }
48  
49  
50      @Before
51      public void initDatabase() throws Exception {
52          log.debug("initDatabase");
53          log.info("setting up " + getClass());
54          sessionFactory = (SessionFactory) applicationContext
55                  .getBean("sessionFactory");
56          Session session = sessionFactory.openSession();
57          TransactionSynchronizationManager.bindResource(sessionFactory,
58                  new SessionHolder(session));
59  
60          dataSet = getDataSet();
61          DatabaseConnection dbConnection = null;
62          try {
63  
64              resetConfiguration();
65  
66              dbConnection = new DatabaseConnection(getDataSource().getConnection());
67              dbConnection.getConfig().setProperty(
68                      DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
69                      new HsqldbDataTypeFactory());
70  
71              if (dataSet != null) {
72                  DatabaseOperation.CLEAN_INSERT.execute(dbConnection, dataSet);
73              }
74  
75              if (!dbConnection.getConnection().getAutoCommit()) {
76                  dbConnection.getConnection().commit();
77              }
78          } catch (Exception e) {
79              log.error("onSetUp: failed to set up datasets", e);
80              throw e;
81          } finally {
82              if (null != dbConnection) {
83                  try {
84                      dbConnection.close();
85                  } catch (SQLException e) {
86                      log.warn("onSetUp: failed to close connection", e);
87                  }
88              }
89          }
90          onSetUp();
91      }
92  
93  
94      @After
95      public void closeDatabase() throws Exception {
96          onTearDown();
97          log.debug("closeDatabase");
98          DatabaseConnection dbConnection = null;
99          try {
100             dbConnection = new DatabaseConnection(getDataSource()
101                     .getConnection());
102 
103             if (dataSet != null) {
104                 DatabaseOperation.DELETE_ALL.execute(dbConnection, dataSet);
105             }
106 
107             if (!dbConnection.getConnection().getAutoCommit()) {
108                 dbConnection.getConnection().commit();
109             }
110 
111         } catch (Exception e) {
112             log.error("onTearDown: failed to tear down datasets", e);
113             throw e;
114         } finally {
115             TransactionSynchronizationManager.unbindResource(sessionFactory);
116 
117             if (null != dbConnection) {
118                 try {
119                     dbConnection.close();
120                 } catch (SQLException e) {
121                     log.warn("onTearDown: failed to close connection", e);
122                 }
123             }
124         }
125     }
126 
127     private Properties getLanguageProperties(String locale) {
128         final LanguageDAO dao = (LanguageDAO) applicationContext.getBean("languageDAO");
129         final List<Language> languages = dao.findByLocale(locale);
130         final Properties properties = new Properties();
131         for (Language language : languages) {
132             properties.setProperty(language.getResourceKey(), language.getResourceValue());
133         }
134         return properties;
135     }
136 
137     @Deprecated
138     public void onSetUp() throws Exception {
139         // this does nothing
140         log.debug("onSetUp called " + getClass());
141     }
142 
143     @Deprecated
144     public void onTearDown() throws Exception {
145         // this does nothing
146         log.debug("onTearDown called " + getClass());
147     }
148 
149     public String getProperty(String name) {
150         String value = null;
151         final String jndiPropertiesOverridePrefix = getConfigurationProperties().getProperty("jndi_override_prefix", "java:comp/env/itracker");
152         if (null != jndiPropertiesOverridePrefix) {
153 
154             if (logger.isDebugEnabled()) {
155 
156                 logger.debug("getProperty: looking up '" + name
157                         + "' from jndi context "
158                         + jndiPropertiesOverridePrefix);
159 
160 
161             }
162             try {
163                 value = (String) NamingUtilites.lookup(new InitialContext(),
164                         jndiPropertiesOverridePrefix + "/" + name);
165                 if (null == value) {
166                     if (logger.isDebugEnabled()) {
167                         logger.debug("getProperty: value not found in jndi: " + name);
168                     }
169                 }
170             } catch (Exception e) {
171                 logger.debug("getProperty: caught exception looking up value for " + name, e);
172             }
173 
174         }
175 
176         if (null == value) {
177             value = getConfigurationProperties().getProperty(name, null);
178         }
179         if (logger.isDebugEnabled()) {
180             logger.debug("getProperty: returning " + value + " for name: " + name);
181         }
182         return value;
183     }
184 
185 
186     private Set<String> getDefinedLocales() {
187         final HashSet<String> definedLocales = new HashSet<>();
188 
189         String definedLocalesString;
190 
191         definedLocalesString = getConfigurationProperties().getProperty("available_locales", ITrackerResources.getDefaultLocale());
192 
193         if (definedLocalesString != null) {
194             StringTokenizer token = new StringTokenizer(definedLocalesString, ",");
195             while (token.hasMoreTokens()) {
196                 String locale = token.nextToken();
197                 if (locale.length() == 5 && locale.indexOf('_') == 2) {
198                     definedLocales.add(locale.substring(0, 2));
199                 }
200                 definedLocales.add(locale);
201             }
202         }
203         return definedLocales;
204     }
205 
206     public void initializeLocale(String locale) {
207         ITrackerResources.clearBundle(ITrackerResources.getLocale(locale));
208     }
209 
210     public void initializeAllLanguages() {
211         initializeLocale(ITrackerResources.BASE_LOCALE);
212         Set<String> definedLocales = getDefinedLocales();
213 
214 
215         for (String locale : definedLocales) {
216             initializeLocale(locale);
217         }
218     }
219 
220     private Properties getConfigurationProperties() {
221         return (Properties) applicationContext.getBean("configurationProperties");
222 
223     }
224 
225     protected void resetConfiguration() {
226 
227         synchronized (ITrackerResources.class) {
228             if (ITrackerResources.isInitialized()) {
229                 return;
230             }
231             final Hashtable<Locale, Properties> properties = new Hashtable<>(getDefinedLocales().size());
232             for (String locale : getDefinedLocales()) {
233                 final Properties p = getLanguageProperties(locale);
234                 properties.put(ITrackerResources.getLocale(locale), p);
235             }
236 
237             ITrackerResources.setConfigurationService(new ITrackerResourcesProvider() {
238                 @Override
239                 public Properties getLanguageProperties(Locale locale) {
240                     if (!properties.contains(locale)) {
241                         properties.put(locale, AbstractDependencyInjectionTest
242                                 .this.getLanguageProperties(locale.toString()));
243                     }
244                     return properties.get(locale);
245                 }
246 
247                 @Override
248                 public String getLanguageEntry(String key, Locale locale) {
249 
250                     return getLanguageProperties(locale).getProperty(key);
251                 }
252 
253                 @Override
254                 public String getProperty(String name, String defaultValue) {
255                     return getConfigurationProperties().getProperty(name, defaultValue);
256                 }
257             });
258             initializeAllLanguages();
259 
260         }
261     }
262 
263     private IDataSet getDataSet() throws Exception {
264         final String[] aDataSet = getDataSetFiles();
265         final IDataSet[] dataSets = new IDataSet[aDataSet.length];
266 
267         for (int i = 0; i < aDataSet.length; i++) {
268             dataSets[i] = new XmlDataSet(classLoader
269                     .getResourceAsStream(aDataSet[i]));
270         }
271         return new CompositeDataSet(dataSets);
272     }
273 
274     /**
275      * must make sure, that the order is correct, so no constraints will be
276      * violated.
277      */
278     protected abstract String[] getDataSetFiles();
279 
280     public DataSource getDataSource() {
281         if (null == this.dataSource) {
282             this.dataSource = (DataSource) applicationContext.getBean("dataSource");
283         }
284         return dataSource;
285     }
286 
287     public void setDataSource(DataSource dataSource) {
288         this.dataSource = dataSource;
289     }
290 
291 
292 }