KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > columba > core > association > AssociationStore


1 package org.columba.core.association;
2
3 import java.io.File JavaDoc;
4 import java.sql.Connection JavaDoc;
5 import java.sql.DriverManager JavaDoc;
6 import java.sql.SQLException JavaDoc;
7 import java.sql.Statement JavaDoc;
8 import java.util.Collection JavaDoc;
9 import java.util.HashMap JavaDoc;
10 import java.util.LinkedList JavaDoc;
11 import java.util.List JavaDoc;
12 import java.util.Vector JavaDoc;
13 import java.util.logging.ConsoleHandler JavaDoc;
14 import java.util.logging.Handler JavaDoc;
15 import java.util.logging.Level JavaDoc;
16 import java.util.logging.Logger JavaDoc;
17
18 import javax.persistence.EntityManager;
19 import javax.persistence.EntityManagerFactory;
20 import javax.persistence.EntityTransaction;
21 import javax.persistence.Persistence;
22 import javax.persistence.PersistenceException;
23 import javax.persistence.Query;
24
25 import org.columba.core.association.api.IAssociation;
26 import org.columba.core.association.api.IAssociationStore;
27 import org.columba.core.config.DefaultConfigDirectory;
28
29 public class AssociationStore implements IAssociationStore, Runnable JavaDoc {
30
31     final static String JavaDoc ENTITY_MANAGER = "associations";
32
33     /** JDK 1.4+ logging framework logger, used for logging. */
34     private static final Logger JavaDoc LOG = Logger
35             .getLogger("org.columba.core.association.AssociationStore");
36
37     EntityManagerFactory factory;
38
39     EntityManager manager;
40
41     Connection JavaDoc conn;
42
43     static private AssociationStore instance;
44
45     /**
46      * private constructor for the singelton implementation
47      *
48      */

49     private AssociationStore() {
50         factory = null;
51         manager = null;
52         conn = null;
53     }
54
55     public void addAssociation(String JavaDoc serviceId, String JavaDoc metaDataId,
56             String JavaDoc itemId) {
57
58         // passive: if not initialized do it now
59
if (!isReady())
60             init();
61
62         // still not ready, exit!
63
if (!isReady())
64             return;
65
66         // transaction is needed for the underlying jpa architecture
67
EntityTransaction tx = manager.getTransaction();
68         tx.begin();
69         try {
70             IAssociation association = new Association(itemId, serviceId,
71                     metaDataId);
72             manager.persist(association);
73             tx.commit();
74         } catch (Exception JavaDoc ex) {
75             if (tx.isActive()) {
76                 tx.rollback();
77                 LOG
78                         .severe("AddAssociation: Exception while persisting new association! Will Rollback! "
79                                 + serviceId + " " + metaDataId + " " + itemId);
80             } else
81                 LOG
82                         .log(
83                                 Level.SEVERE,
84                                 "Got an Exception, but no Transaction active, so no Rollback!",
85                                 ex);
86         }
87     }
88
89     @SuppressWarnings JavaDoc("unchecked")
90     public Collection JavaDoc<IAssociation> getAllAssociations(String JavaDoc itemId) {
91
92         // passive: if not initialized do it now
93
if (!isReady())
94             init();
95
96         // still not ready, exit!
97
if (!isReady())
98             return new Vector JavaDoc<IAssociation>();
99
100         // transaction is needed for the underlying jpa architecture
101
EntityTransaction tx = manager.getTransaction();
102
103         // wait, if there is an active transaction
104
// TODO @author hubms retrycount!
105
while (tx.isActive())
106             ;
107
108         tx.begin();
109         Query query = manager
110                 .createQuery("select a from org.columba.core.association.Association a where a.itemId = '"
111                         + itemId + "'");
112         Collection JavaDoc<IAssociation> results = (Collection JavaDoc<IAssociation>) query
113                 .getResultList();
114         // for(IAssociation a : results) {
115
// System.out.println("got a association: " + a.getItemId() + " " +
116
// a.getMetaDataId() + " " + a.getServiceId());
117
// }
118
tx.commit();
119         return results;
120     }
121
122     @SuppressWarnings JavaDoc("unchecked")
123     public Collection JavaDoc<String JavaDoc> getAssociatedItems(String JavaDoc serviceId,
124             String JavaDoc metaDataId) {
125
126         // passive: if not initialized do it now
127
if (!isReady())
128             init();
129
130         // still not ready, exit!
131
if (!isReady())
132             return new Vector JavaDoc<String JavaDoc>();
133
134         // transaction is needed for the underlying jpa architecture
135
EntityTransaction tx = manager.getTransaction();
136         tx.begin();
137         Query query = manager
138                 .createQuery("select a from org.columba.core.association.Association a where a.serviceId = '"
139                         + serviceId
140                         + "' and a.metaDataId = '"
141                         + metaDataId
142                         + "'");
143         Collection JavaDoc<IAssociation> results = (Collection JavaDoc<IAssociation>) query
144                 .getResultList();
145         Collection JavaDoc<String JavaDoc> itemCollection = new LinkedList JavaDoc<String JavaDoc>();
146         for (IAssociation a : results) {
147             itemCollection.add(a.getItemId());
148         }
149         tx.commit();
150         return itemCollection;
151     }
152
153     /**
154      * starts the jpa manager starts the database
155      */

156     public void init() {
157
158         // disable logging for the startup
159
Handler JavaDoc[] handlers = Logger.getLogger("").getHandlers();
160         ConsoleHandler JavaDoc consolehandler = null;
161         Level JavaDoc level = null;
162         for (int index = 0; index < handlers.length; index++) {
163             // set console handler to OFF
164
if (handlers[index] instanceof ConsoleHandler JavaDoc) {
165                 level = handlers[index].getLevel();
166                 handlers[index].setLevel(Level.OFF);
167                 consolehandler = (ConsoleHandler JavaDoc) handlers[index];
168                 break;
169             }
170         }
171
172         //ShutdownManager.getInstance().register(this);
173

174         String JavaDoc connectionString = "jdbc:hsqldb:file:"
175                 + DefaultConfigDirectory.getInstance().getCurrentPath().getAbsolutePath()
176                 + File.separator + "associations";
177
178         // start HSQLDB
179
try {
180
181             // do not start a second time!
182
if (conn == null) {
183                 Class.forName("org.hsqldb.jdbcDriver").newInstance();
184                 conn = DriverManager.getConnection(connectionString, "sa", "");
185             }
186         } catch (InstantiationException JavaDoc e) {
187             LOG.severe("AssociationStore: Could not start the HSQLDB! " + e.getClass().getName()
188                     + ": " + e.getMessage());
189         } catch (IllegalAccessException JavaDoc e) {
190             LOG.severe("AssociationStore: Could not start the HSQLDB! " + e.getClass().getName()
191                     + ": " + e.getMessage());
192         } catch (ClassNotFoundException JavaDoc e) {
193             LOG.severe("AssociationStore: Could not start the HSQLDB! " + e.getClass().getName()
194                     + ": " + e.getMessage());
195         } catch (SQLException JavaDoc e) {
196             LOG.severe("AssociationStore: Could not start the HSQLDB! " + e.getClass().getName()
197                     + ": " + e.getMessage());
198         }
199
200         try {
201
202             // manually rewrite the connection url, because
203
// if there is no rewrite the database files are created
204
// in the starting directory, we don't want that!
205
HashMap JavaDoc<String JavaDoc, String JavaDoc> map = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
206             map.put("hibernate.connection.url", connectionString);
207             map.put("exclude-unlisted-classes", "true"); // refers to the
208
// entry in
209
// persistence.xml
210

211             // start JPA entity manager
212
if (factory == null)
213                 factory = Persistence.createEntityManagerFactory(
214                         ENTITY_MANAGER, map);
215
216             if (manager == null)
217                 manager = factory.createEntityManager(map);
218
219         } catch (PersistenceException pEx) {
220             LOG.severe("AssociationStore: Could not start the Entity manager! "
221                     + pEx.getMessage());
222         }
223
224         // restore log level
225
if (consolehandler != null)
226             consolehandler.setLevel(level);
227
228     }
229
230     public boolean isReady() {
231         return ((factory != null) && (manager != null) && (conn != null));
232     }
233
234     @SuppressWarnings JavaDoc("unchecked")
235     public void removeAssociation(String JavaDoc serviceId, String JavaDoc metaDataId,
236             String JavaDoc itemId) {
237
238         // passive: if not initialized do it now
239
if (!isReady())
240             init();
241
242         // still not ready, exit!
243
if (!isReady())
244             return;
245
246         EntityTransaction tx = manager.getTransaction();
247         tx.begin();
248         try {
249             Query query = manager
250                     .createQuery("select a from org.columba.core.association.Association a where a.itemId = '"
251                             + itemId
252                             + "' and a.serviceId = '"
253                             + serviceId
254                             + "'" + " and a.metaDataId = '" + metaDataId + "'");
255             if (query.getResultList().size() > 1) {
256                 // more than one item, very strange! duplicate entries! remove
257
// all
258
LOG
259                         .info("RemoveAssociation: Got more than one association, that is strange! We try to remove all!");
260                 for (Object JavaDoc row : query.getResultList())
261                     manager.remove(row);
262                 tx.commit();
263             } else if (query.getResultList().size() == 1) {
264                 manager.remove(query.getSingleResult());
265                 tx.commit();
266             } else {
267                 // no item exists in table
268
// -> nothing todo
269
}
270         } catch (Exception JavaDoc ex) {
271             if (tx.isActive()) {
272                 tx.rollback();
273                 LOG
274                         .severe("RemoveAssociation: Exception while removing association! Will Rollback! "
275                                 + serviceId + " " + metaDataId + " " + itemId);
276             } else {
277                 ex.printStackTrace();
278                 LOG
279                         .log(
280                                 Level.SEVERE,
281                                 "RemoveAssociation: Got an Exception, but no Transaction active, so no Rollback!",
282                                 ex);
283             }
284         }
285     }
286
287     @SuppressWarnings JavaDoc("unchecked")
288     public void removeItem(String JavaDoc itemId) {
289
290         // passive: if not initialized do it now
291
if (!isReady())
292             init();
293
294         // still not ready, exit!
295
if (!isReady())
296             return;
297
298         EntityTransaction tx = manager.getTransaction();
299         tx.begin();
300         try {
301             Query query = manager
302                     .createQuery("select a from org.columba.core.association.Association a where a.itemId = '"
303                             + itemId + "'");
304             List JavaDoc<Association> results = (List JavaDoc<Association>) query
305                     .getResultList();
306             for (Association a : results) {
307                 manager.remove(a);
308             }
309             tx.commit();
310         } catch (Exception JavaDoc ex) {
311             LOG.severe("RemoveItem: could not remove item" + ex.getMessage());
312             ex.printStackTrace();
313             tx.rollback();
314         }
315     }
316
317     public void shutdown() {
318
319         // shutdown hsql
320
try {
321             // if the database is not started, don't do it
322
if (conn != null) {
323                 Statement JavaDoc stmt = conn.createStatement();
324                 stmt.execute("SHUTDOWN");
325             }
326         } catch (SQLException JavaDoc e) {
327             LOG.severe("AssociationStore: Could not shutdwon the database! "
328                     + e.getClass().getName() + ": " + e.getMessage());
329         }
330
331         // shutdown entity manager
332
if (manager != null)
333             manager.close();
334
335         if (factory != null)
336             factory.close();
337     }
338
339     public static AssociationStore getInstance() {
340         if (instance == null) {
341             synchronized (AssociationStore.class) {
342                 if (instance == null)
343                     instance = new AssociationStore();
344             }
345         }
346         return instance;
347     }
348
349     public void run() {
350         shutdown();
351     }
352 }
353
Popular Tags