forked from Ericsson/CodeCompass
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEMFactory.java
More file actions
96 lines (79 loc) · 2.63 KB
/
EMFactory.java
File metadata and controls
96 lines (79 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package model;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.spi.PersistenceUnitTransactionType;
import java.util.Arrays;
import java.util.HashMap;
import java.util.logging.Level;
import static logger.Logger.LOGGER;
import static org.eclipse.persistence.config.PersistenceUnitProperties.*;
public class EMFactory {
private final EntityManagerFactory emf;
public EMFactory(String rawDbContext, boolean dropAndCreateTables) {
this.emf =
Persistence.createEntityManagerFactory(
"ParserPU",
initProperties(rawDbContext, dropAndCreateTables)
);
if (dropAndCreateTables) {
emf.getMetamodel().getEntities().forEach(
e ->
LOGGER.log(
Level.INFO,
String.join(" ", "Dropping table", e.getName())
)
);
}
}
public EntityManager createEntityManager()
{
return emf.createEntityManager();
}
private HashMap<String, Object> initProperties(
String rawDbContext, boolean dropAndCreateTables)
{
HashMap<String, Object> properties = new HashMap<>();
String[] splitByColon = rawDbContext.split(":");
String dbType = splitByColon[0];
String contextString = splitByColon[1];
boolean isSqlite = dbType.equals("sqlite");
String driver =
isSqlite ? "org.sqlite.JDBC" : "org.postgresql.Driver";
String[] contextList = contextString.split(";");
HashMap<String, String> contextMap = new HashMap<>();
if (dropAndCreateTables) {
properties.put("eclipselink.ddl-generation", "drop-and-create-tables");
} else {
properties.put("eclipselink.ddl-generation", "create-tables");
}
properties.put(
TRANSACTION_TYPE,
PersistenceUnitTransactionType.RESOURCE_LOCAL.name()
);
Arrays.stream(contextList).forEach(c -> {
String[] splitContext = c.split("=");
contextMap.put(splitContext[0], splitContext[1]);
});
String connString =
isSqlite ?
"jdbc:" + "sqlite" + ":/" +
contextMap.get("database")
.replaceFirst("^~", System.getProperty("user.home"))
:
"jdbc:" + "postgresql" + "://" +
contextMap.get("host") + ":" +
contextMap.get("port") + "/" +
contextMap.get("database");
properties.put(JDBC_DRIVER, driver);
properties.put(JDBC_URL, connString);
if (!isSqlite) {
properties.put(JDBC_USER, contextMap.get("user"));
properties.put(JDBC_PASSWORD, contextMap.get("password"));
}
return properties;
}
public EntityManagerFactory getEmf() {
return emf;
}
}