forked from jenkinsci/database-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPersistenceService.java
More file actions
83 lines (72 loc) · 2.72 KB
/
Copy pathPersistenceService.java
File metadata and controls
83 lines (72 loc) · 2.72 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
package org.jenkinsci.plugins.database.jpa;
import hudson.Extension;
import jenkins.model.Jenkins;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.jenkinsci.plugins.database.Database;
import org.jenkinsci.plugins.database.GlobalDatabaseConfiguration;
import org.jvnet.hudson.annotation_indexer.Index;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
/**
* Creates {@link EntityManagerFactory}.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class PersistenceService {
@Inject
private Jenkins jenkins;
@Inject
GlobalDatabaseConfiguration globalDatabaseConfiguration;
private final AtomicReference<EMFCache<Database>> globalCache = new AtomicReference<>();
public EntityManagerFactory createEntityManagerFactory(DataSource dataSource, List<Class> classes) {
return new HibernatePersistenceProvider().createContainerEntityManagerFactory(new PersistenceUnitInfoImpl(
dataSource, classes, jenkins.pluginManager.uberClassLoader), null);
}
/**
* Obtains a fully configured {@link EntityManagerFactory} for connecting
* to {@linkplain GlobalDatabaseConfiguration global database}.
*
* @return
* null if there's no global database configured yet.
*/
@CheckForNull
public EntityManagerFactory getGlobalEntityManagerFactory() throws SQLException, IOException {
Database db = globalDatabaseConfiguration.getDatabase();
if (db==null) {
close(globalCache.getAndSet(null));
return null;
}
EMFCache<Database> c = globalCache.get();
if (c==null || c.cacheKey !=db) {
List<Class> classes = new ArrayList<Class>();
for (Class cls : Index.list(GlobalTable.class,jenkins.pluginManager.uberClassLoader,Class.class))
classes.add(cls);
// set the new one, and close the old one if any
close(globalCache.getAndSet(c = new EMFCache<Database>(createEntityManagerFactory(db.getDataSource(), classes), db)));
}
return c.factory;
}
private void close(EMFCache<?> v) {
if (v!=null)
v.factory.close();
}
/**
* For atomic update for {@link EntityManagerFactory}.
*/
static class EMFCache<K> {
final K cacheKey;
final EntityManagerFactory factory;
EMFCache(EntityManagerFactory factory, K cacheKey) {
this.factory = factory;
this.cacheKey = cacheKey;
}
}
}