source: VirtualCollectionRegistry/trunk/VirtualCollectionRegistry/src/main/java/eu/clarin/cmdi/virtualcollectionregistry/DataStore.java @ 241

Last change on this file since 241 was 241, checked in by oschonef, 14 years ago
  • change logging to slf4j
  • update slf4j to 1.5.11
  • Property svn:eol-style set to native
File size: 1.6 KB
Line 
1package eu.clarin.cmdi.virtualcollectionregistry;
2
3import java.util.Map;
4
5import javax.persistence.EntityManager;
6import javax.persistence.EntityManagerFactory;
7import javax.persistence.EntityTransaction;
8import javax.persistence.Persistence;
9
10import org.slf4j.Logger;
11import org.slf4j.LoggerFactory;
12
13public class DataStore {
14        private class ThreadLocalEntityManager extends ThreadLocal<EntityManager> {
15                protected EntityManager initialValue() {
16                        if (emf == null) {
17                                throw new InternalError("JPA not initalizied correctly");
18                        }
19                        return emf.createEntityManager();
20                }
21        } // inner class ThreadLocalEntityManager
22        private static final Logger logger =
23                LoggerFactory.getLogger(DataStore.class);
24        private final EntityManagerFactory emf;
25        private final ThreadLocalEntityManager em = new ThreadLocalEntityManager();
26
27        DataStore(Map<String, String> config)
28                throws VirtualCollectionRegistryException {
29                try {
30                        emf = Persistence.createEntityManagerFactory(
31                                        "VirtualCollectionStore", config);
32                } catch (Exception e) {
33                        logger.error("error initializing data store", e);
34                        throw new VirtualCollectionRegistryException("error initializing",
35                                        e);
36                }
37                logger.debug("data store was successfully initialized");
38        }
39
40        public void destroy() throws VirtualCollectionRegistryException {
41                if (emf != null) {
42                        emf.close();
43                }
44        }
45
46        public EntityManager getEntityManager() {
47                return em.get();
48        }
49       
50        public void closeEntityManager() {
51                EntityManager manager = em.get();
52                if (manager != null) {
53                        em.remove();
54                        EntityTransaction tx = manager.getTransaction();
55                        if (tx.isActive()) {
56                                tx.rollback();
57                        }
58                        manager.close();
59                }
60        }
61
62} // class DataStore
Note: See TracBrowser for help on using the repository browser.