BrightSide Workbench Full Report + Source Code
DaoFactory.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2011 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 package org.turro.jpa;
19 
20 import java.io.File;
21 import java.util.Date;
22 import java.util.HashMap;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25 import javax.persistence.EntityManager;
26 import javax.persistence.EntityManagerFactory;
27 import javax.persistence.Persistence;
28 import javax.persistence.PersistenceUnit;
29 import javax.persistence.Query;
30 import org.amic.util.file.FileSelector;
31 import org.amic.util.file.FileUtil;
32 import org.turro.string.Strings;
33 import org.turro.action.IElephantCloseable;
34 import org.turro.annotation.ElephantCloseable;
35 import org.turro.elephant.context.ElephantContext;
36 import org.turro.jpa.config.JpaConfig;
37 
42 @ElephantCloseable
43 public class DaoFactory implements IElephantCloseable {
44 
45  private static final HashMap<String, EntityManager> cachedEMs= new HashMap<>();
46  private static final HashMap<String, Long> lastAccessEMs= new HashMap<>();
47  private static final long CLEAR_CACHE = 2000L, CLOSE_CACHE = 360000L;
48 
49  @PersistenceUnit
50  private EntityManagerFactory emf = null;
51 
52  private String pu, conf;
53 
54  public EntityManager createEntityManager(String pu, String conf) {
55  EntityManagerFactory factory = getFactory(pu, conf);
56  if(factory != null) {
57  return factory.createEntityManager();
58  }
59  return null;
60  }
61 
62  //TODO: return to EM per session
63  @Deprecated
64  public synchronized EntityManager createCachedEntityManager(String pu, String conf) {
65  EntityManager cachedEM = cachedEMs.get(pu);
66  Long lastAccess = lastAccessEMs.get(pu);
67  Long time = new Date().getTime();
68  if(lastAccess == null) lastAccess = time;
69  EntityManagerFactory factory = getFactory(pu, conf);
70  if(factory != null) {
71  if(cachedEM == null || !(cachedEM.isOpen())) {
72  cachedEM = factory.createEntityManager();
73  } else if(time > lastAccess + CLEAR_CACHE) {
74  cachedEM.clear();
75  } else if(time > lastAccess + CLOSE_CACHE) {
76  try {
77  cachedEM.close();
78  } finally {
79  cachedEM = factory.createEntityManager();
80  }
81  }
82  lastAccessEMs.put(pu, time);
83  cachedEMs.put(pu, cachedEM);
84  return cachedEM;
85  }
86  return null;
87  }
88 
89  public EntityManagerFactory getEmf() {
90  return emf;
91  }
92 
93  private synchronized EntityManagerFactory getFactory(String pu, String conf) {
94  if(emf == null) {
95  doCreateFactory(pu, conf);
96  }
97  return emf;
98  }
99 
100  private void doCreateFactory(String pu1, String conf1) {
101  this.pu = pu1;
102  this.conf = conf1;
103 // Properties properties = new Properties();
104 // HibernateConfig hc = (HibernateConfig) HeadlessApplication.getInstance()
105 // .getImplementation("IHibernateConfig_" + this.conf);
106 // if(hc != null) hc.updateProperties(properties);
107  emf = Persistence.createEntityManagerFactory(this.pu, JpaConfig.from(pu1, conf1));
108  FileSelector fs = new FileSelector(ElephantContext.getRealPath("/WEB-INF/_autoupdate"), conf1 + "\\_.*\\.sql");
109  if(fs.getFiles() != null && fs.getFiles().length > 0) {
110  EntityManager em = emf.createEntityManager();
111  try {
112  for(File f : fs.getFiles()) {
113  em.getTransaction().begin();
114  try {
115  // skip comments
116  for(String sql : FileUtil.getContent(f, "UTF-8", ";", new String[] {"--","/*"})) {
117  if(!Strings.isBlank(sql)) {
118  // remove final ;
119  String execSql = sql.substring(0, sql.length() - 1);
120  try {
121  // ensure \' escaping
122  Query q = em.createNativeQuery(execSql.replaceAll("\\\\'", "''"));
123  q.executeUpdate();
124  } catch(Exception ex) {
125  Logger.getLogger(DaoFactory.class.getName()).log(Level.FINEST, ElephantContext.logMsg("AutoUpdate:" + f.getName() + ":" + sql), ex);
126  }
127  }
128  }
129  em.getTransaction().commit();
130  } catch (Exception ex) {
131  if(em.getTransaction().isActive()) {
132  em.getTransaction().rollback();
133  }
134  Logger.getLogger(DaoFactory.class.getName()).log(Level.FINEST, ElephantContext.logMsg("AutoUpdate:" + f.getName()), ex);
135  } finally {
136  FileUtil.deleteFile(f);
137  }
138  }
139  } finally {
140  em.close();
141  }
142  }
143  }
144 
145  public void close() {
146  if(emf != null) emf.close();
147  }
148 
149  @Override
150  public void closeElephant() {
151  close();
152  cachedEMs.values().forEach((em) -> {
153  em.close();
154  });
155  }
156 
157 }
EntityManagerFactory getEmf()
Definition: DaoFactory.java:89
EntityManager createEntityManager(String pu, String conf)
Definition: DaoFactory.java:54
synchronized EntityManager createCachedEntityManager(String pu, String conf)
Definition: DaoFactory.java:64