-
Notifications
You must be signed in to change notification settings - Fork 14
/
DefaultPersistenceProviderResolver.java
249 lines (213 loc) · 8.74 KB
/
DefaultPersistenceProviderResolver.java
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/**
* Copyright (C) 2023 Czech Technical University in Prague
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.jopa.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
/**
* Default implementation of the {@link PersistenceProviderResolver}, threadsafe.
* <p>
* Uses service loading mechanism ({@link ServiceLoader#load(Class, ClassLoader)} using the current context thread's class loader) to discover {@link PersistenceProvider} implementations on the classpath.
* <p>
* Code based on JPA specification implementation.
*/
public class DefaultPersistenceProviderResolver implements PersistenceProviderResolver {
private static final Logger LOG = LoggerFactory.getLogger(DefaultPersistenceProviderResolver.class);
/**
* Queue for reference objects referring to class loaders or persistence providers.
*/
private static final ReferenceQueue<?> referenceQueue = new ReferenceQueue<>();
/**
* Available providers cached by CacheKey to ensure there is no potential for provider visibility issues.
*/
private final HashMap<CacheKey, PersistenceProviderReference> providers = new HashMap<>();
public List<PersistenceProvider> getPersistenceProviders() {
// Before we do the real loading work, see whether we need to
// do some cleanup: If references to class loaders or
// persistence providers have been nulled out, remove all related
// information from the cache.
processQueue();
final ClassLoader loader = getContextClassLoader();
final CacheKey cacheKey = new CacheKey(loader);
PersistenceProviderReference providersReferent = providers.get(cacheKey);
if (providersReferent != null) {
return providersReferent.get();
}
List<PersistenceProvider> loadedProviders = new ArrayList<>();
Iterator<PersistenceProvider> ipp = ServiceLoader.load(PersistenceProvider.class, loader).iterator();
try {
loadProvider(ipp).ifPresent(loadedProviders::add);
} catch (ServiceConfigurationError sce) {
LOG.warn("Unable to load PersistenceProvider implementation via service loader.", sce);
}
if (loadedProviders.isEmpty()) {
LOG.warn("No valid providers found.");
}
providersReferent = new PersistenceProviderReference(loadedProviders, referenceQueue, cacheKey);
providers.put(cacheKey, providersReferent);
return loadedProviders;
}
private Optional<PersistenceProvider> loadProvider(Iterator<PersistenceProvider> ipp) {
try {
return Optional.of(ipp.next());
} catch (ServiceConfigurationError sce) {
LOG.warn("Unable to load PersistenceProvider implementation via service loader.", sce);
return Optional.empty();
}
}
/**
* Remove garbage collected cache keys & providers.
*/
private void processQueue() {
CacheKeyReference ref;
while ((ref = (CacheKeyReference) referenceQueue.poll()) != null) {
providers.remove(ref.getCacheKey());
}
}
/**
* Wraps <code>Thread.currentThread().getContextClassLoader()</code> into a doPrivileged block if security manager is present
*/
private static ClassLoader getContextClassLoader() {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
} else {
return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> Thread.currentThread()
.getContextClassLoader());
}
}
/**
* Clear all cached providers
*/
public void clearCachedProviders() {
providers.clear();
}
/**
* The common interface to get a CacheKey implemented by
* LoaderReference and PersistenceProviderReference.
*/
private interface CacheKeyReference {
CacheKey getCacheKey();
}
/**
* Key used for cached persistence providers. The key checks
* the class loader to determine if the persistence providers
* is a match to the requested one. The loader may be null.
*/
private class CacheKey implements Cloneable {
/* Weak Reference to ClassLoader */
private LoaderReference loaderRef;
/* Cached Hashcode */
private int hashCodeCache;
CacheKey(ClassLoader loader) {
if (loader == null) {
this.loaderRef = null;
} else {
loaderRef = new LoaderReference(loader, referenceQueue, this);
}
calculateHashCode();
}
ClassLoader getLoader() {
return (loaderRef != null) ? loaderRef.get() : null;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || !getClass().equals(other.getClass())) {
return false;
}
final CacheKey otherEntry = (CacheKey) other;
// quick check to see if they are not equal
if (hashCodeCache != otherEntry.hashCodeCache) {
return false;
}
// are refs (both non-null) or (both null)?
if (loaderRef == null) {
return otherEntry.loaderRef == null;
}
ClassLoader loader = loaderRef.get();
// With a null reference we can no longer find out which class loader was referenced; so treat it as unequal
return (otherEntry.loaderRef != null) && (loader != null) && (loader == otherEntry.loaderRef.get());
}
@Override
public int hashCode() {
return hashCodeCache;
}
private void calculateHashCode() {
ClassLoader loader = getLoader();
if (loader != null) {
hashCodeCache = loader.hashCode();
}
}
public Object clone() {
try {
CacheKey clone = (CacheKey) super.clone();
if (loaderRef != null) {
clone.loaderRef = new LoaderReference(loaderRef.get(), referenceQueue, clone);
}
return clone;
} catch (CloneNotSupportedException e) {
// this should never happen
throw new InternalError(e);
}
}
public String toString() {
return "CacheKey[" + getLoader() + ")]";
}
}
/**
* References to class loaders are weak references, so that they can be
* garbage collected when nobody else is using them. The DefaultPersistenceProviderResolver
* class has no reason to keep class loaders alive.
*/
private class LoaderReference extends WeakReference<ClassLoader> implements CacheKeyReference {
private final CacheKey cacheKey;
@SuppressWarnings("unchecked")
LoaderReference(ClassLoader referent, ReferenceQueue q, CacheKey key) {
super(referent, q);
cacheKey = key;
}
public CacheKey getCacheKey() {
return cacheKey;
}
}
/**
* References to persistence provider are soft references so that they can be garbage
* collected when they have no hard references.
*/
private class PersistenceProviderReference extends SoftReference<List<PersistenceProvider>> implements CacheKeyReference {
private final CacheKey cacheKey;
@SuppressWarnings("unchecked")
PersistenceProviderReference(List<PersistenceProvider> referent, ReferenceQueue q, CacheKey key) {
super(referent, q);
cacheKey = key;
}
public CacheKey getCacheKey() {
return cacheKey;
}
}
}