forked from spring-projects/spring-data-commons
/
CdiRepositoryBean.java
448 lines (396 loc) · 18.1 KB
/
CdiRepositoryBean.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/*
* Copyright 2011-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.repository.cdi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Alternative;
import javax.enterprise.inject.Stereotype;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.PassivationCapable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.data.repository.config.CustomRepositoryImplementationDetector;
import org.springframework.data.repository.config.RepositoryFragmentConfiguration;
import org.springframework.data.repository.core.support.RepositoryComposition.RepositoryFragments;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.repository.core.support.RepositoryFragment;
import org.springframework.data.util.Optionals;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Base class for {@link Bean} wrappers.
*
* @author Dirk Mahler
* @author Oliver Gierke
* @author Mark Paluchs
* @author Peter Rietzler
* @author Jens Schauder
* @author Christoph Strobl
* @author Ariel Carrera
*/
public abstract class CdiRepositoryBean<T> implements Bean<T>, PassivationCapable {
private static final Log logger = LogFactory.getLog(CdiRepositoryBean.class);
private static final CdiRepositoryConfiguration DEFAULT_CONFIGURATION = DefaultCdiRepositoryConfiguration.INSTANCE;
private final Set<Annotation> qualifiers;
private final Class<T> repositoryType;
private final CdiRepositoryContext context;
private final BeanManager beanManager;
private final String passivationId;
private transient @Nullable T repoInstance;
/**
* Creates a new {@link CdiRepositoryBean}.
* @param qualifiers must not be {@literal null}.
* @param repositoryType has to be an interface must not be {@literal null}.
* @param beanManager the CDI {@link BeanManager}, must not be {@literal null}.
*/
public CdiRepositoryBean(Set<Annotation> qualifiers, Class<T> repositoryType, BeanManager beanManager) {
this(qualifiers, repositoryType, beanManager,
new CdiRepositoryContext(CdiRepositoryBean.class.getClassLoader()));
}
/**
* Creates a new {@link CdiRepositoryBean}.
* @param qualifiers must not be {@literal null}.
* @param repositoryType has to be an interface must not be {@literal null}.
* @param beanManager the CDI {@link BeanManager}, must not be {@literal null}.
* @param detector detector for the custom repository implementations
* {@link CustomRepositoryImplementationDetector}.
*/
public CdiRepositoryBean(Set<Annotation> qualifiers, Class<T> repositoryType, BeanManager beanManager,
Optional<CustomRepositoryImplementationDetector> detector) {
Assert.notNull(qualifiers, "Qualifiers must not be null!");
Assert.notNull(beanManager, "BeanManager must not be null!");
Assert.notNull(repositoryType, "Repoitory type must not be null!");
Assert.isTrue(repositoryType.isInterface(), "RepositoryType must be an interface!");
this.qualifiers = qualifiers;
this.repositoryType = repositoryType;
this.beanManager = beanManager;
this.context = new CdiRepositoryContext(getClass().getClassLoader(), detector.orElseThrow(
() -> new IllegalArgumentException("CustomRepositoryImplementationDetector must be present!")));
this.passivationId = createPassivationId(qualifiers, repositoryType);
}
/**
* Creates a new {@link CdiRepositoryBean}.
* @param qualifiers must not be {@literal null}.
* @param repositoryType has to be an interface must not be {@literal null}.
* @param beanManager the CDI {@link BeanManager}, must not be {@literal null}.
* @param context CDI context encapsulating class loader, metadata scanning and
* fragment detection.
* @since 2.1
*/
public CdiRepositoryBean(Set<Annotation> qualifiers, Class<T> repositoryType, BeanManager beanManager,
CdiRepositoryContext context) {
Assert.notNull(qualifiers, "Qualifiers must not be null!");
Assert.notNull(beanManager, "BeanManager must not be null!");
Assert.notNull(repositoryType, "Repoitory type must not be null!");
Assert.isTrue(repositoryType.isInterface(), "RepositoryType must be an interface!");
this.qualifiers = qualifiers;
this.repositoryType = repositoryType;
this.beanManager = beanManager;
this.context = context;
this.passivationId = createPassivationId(qualifiers, repositoryType);
}
/**
* Creates a unique identifier for the given repository type and the given
* annotations.
* @param qualifiers must not be {@literal null} or contain {@literal null} values.
* @param repositoryType must not be {@literal null}.
* @return
*/
private String createPassivationId(Set<Annotation> qualifiers, Class<?> repositoryType) {
List<String> qualifierNames = new ArrayList<>(qualifiers.size());
for (Annotation qualifier : qualifiers) {
qualifierNames.add(qualifier.annotationType().getName());
}
Collections.sort(qualifierNames);
return StringUtils.collectionToDelimitedString(qualifierNames, ":") + ":" + repositoryType.getName();
}
@Override
@SuppressWarnings("rawtypes")
public Set<Type> getTypes() {
Set<Class> interfaces = new HashSet<>();
interfaces.add(this.repositoryType);
interfaces.addAll(Arrays.asList(this.repositoryType.getInterfaces()));
return new HashSet<>(interfaces);
}
/**
* Returns an instance of an the given {@link Bean}.
* @param bean the {@link Bean} about to create an instance for.
* @return the actual component instance.
* @see Bean#getTypes()
*/
protected <S> S getDependencyInstance(Bean<S> bean) {
return getDependencyInstance(bean, bean.getBeanClass());
}
/**
* Returns an instance of an the given {@link Bean} and allows to be specific about
* the type that is about to be created.
* @param bean the {@link Bean} about to create an instance for.
* @param type the expected type of the component instance created for that
* {@link Bean}. We need to hand this parameter explicitly as the {@link Bean} might
* carry multiple types but the primary one might not be the first, i.e. the one
* returned by {@link Bean#getBeanClass()}.
* @return the actual component instance.
* @see Bean#getTypes()
*/
@SuppressWarnings("unchecked")
protected <S> S getDependencyInstance(Bean<S> bean, Class<?> type) {
CreationalContext<S> creationalContext = this.beanManager.createCreationalContext(bean);
return (S) this.beanManager.getReference(bean, type, creationalContext);
}
/**
* Forces the initialization of bean target.
*/
public final void initialize() {
create(this.beanManager.createCreationalContext(this));
}
@Override
public final T create(@SuppressWarnings("null") CreationalContext<T> creationalContext) {
T repoInstance = this.repoInstance;
if (repoInstance != null) {
logger.debug(LogMessage.format("Returning eagerly created CDI repository instance for %s.",
this.repositoryType.getName()));
return repoInstance;
}
logger.debug(LogMessage.format("Creating CDI repository bean instance for %s.", this.repositoryType.getName()));
repoInstance = create(creationalContext, this.repositoryType);
this.repoInstance = repoInstance;
return repoInstance;
}
@Override
public void destroy(@SuppressWarnings("null") T instance,
@SuppressWarnings("null") CreationalContext<T> creationalContext) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Destroying bean instance %s for repository type '%s'.", instance.toString(),
this.repositoryType.getName()));
}
creationalContext.release();
}
@Override
public Set<Annotation> getQualifiers() {
return this.qualifiers;
}
@Override
public String getName() {
return this.repositoryType.getName();
}
@Override
public Set<Class<? extends Annotation>> getStereotypes() {
return Arrays.stream(this.repositoryType.getAnnotations()).map(Annotation::annotationType)
.filter(it -> it.isAnnotationPresent(Stereotype.class)).collect(Collectors.toSet());
}
@Override
public Class<?> getBeanClass() {
return this.repositoryType;
}
@Override
public boolean isAlternative() {
return this.repositoryType.isAnnotationPresent(Alternative.class);
}
@Override
public boolean isNullable() {
return false;
}
@Override
public Set<InjectionPoint> getInjectionPoints() {
return Collections.emptySet();
}
@Override
public Class<? extends Annotation> getScope() {
return ApplicationScoped.class;
}
@Override
public String getId() {
return this.passivationId;
}
/**
* Creates the actual component instance.
* @param creationalContext will never be {@literal null}.
* @param repositoryType will never be {@literal null}.
* @return
*/
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {
CdiRepositoryConfiguration cdiRepositoryConfiguration = lookupConfiguration(this.beanManager, this.qualifiers);
Optional<Bean<?>> customImplementationBean = getCustomImplementationBean(repositoryType,
cdiRepositoryConfiguration);
Optional<Object> customImplementation = customImplementationBean.map(this::getDependencyInstance);
return create(creationalContext, repositoryType, customImplementation);
}
/**
* Creates the actual component instance given a {@link RepositoryFactorySupport
* repository factory supplier} and the repository {@link Class type}. This method is
* an utility for to create a repository. This method will obtain a
* {@link RepositoryFactorySupport repository factory} and configure it with
* {@link CdiRepositoryConfiguration}.
* @param factorySupplier must not be {@literal null}.
* @param repositoryType must not be {@literal null}.
* @return
* @since 2.1
*/
protected T create(Supplier<? extends RepositoryFactorySupport> factorySupplier, Class<T> repositoryType) {
CdiRepositoryConfiguration configuration = lookupConfiguration(this.beanManager, this.qualifiers);
RepositoryFragments repositoryFragments = getRepositoryFragments(repositoryType, configuration);
RepositoryFactorySupport factory = factorySupplier.get();
applyConfiguration(factory, configuration);
return create(factory, repositoryType, repositoryFragments);
}
/**
* Lookup repository fragments for a {@link Class repository interface}.
* @param repositoryType must not be {@literal null}.
* @return the {@link RepositoryFragments}.
* @since 2.1
*/
protected RepositoryFragments getRepositoryFragments(Class<T> repositoryType) {
Assert.notNull(repositoryType, "Repository type must not be null!");
CdiRepositoryConfiguration cdiRepositoryConfiguration = lookupConfiguration(this.beanManager, this.qualifiers);
return getRepositoryFragments(repositoryType, cdiRepositoryConfiguration);
}
private RepositoryFragments getRepositoryFragments(Class<T> repositoryType,
CdiRepositoryConfiguration cdiRepositoryConfiguration) {
Optional<Bean<?>> customImplementationBean = getCustomImplementationBean(repositoryType,
cdiRepositoryConfiguration);
Optional<Object> customImplementation = customImplementationBean.map(this::getDependencyInstance);
List<RepositoryFragment<?>> repositoryFragments = findRepositoryFragments(repositoryType,
cdiRepositoryConfiguration);
RepositoryFragments customImplementationFragment = customImplementation.map(RepositoryFragments::just)
.orElseGet(RepositoryFragments::empty);
return RepositoryFragments.from(repositoryFragments).append(customImplementationFragment);
}
@SuppressWarnings("unchecked")
private List<RepositoryFragment<?>> findRepositoryFragments(Class<T> repositoryType,
CdiRepositoryConfiguration cdiRepositoryConfiguration) {
Stream<RepositoryFragmentConfiguration> fragmentConfigurations = this.context
.getRepositoryFragments(cdiRepositoryConfiguration, repositoryType);
return fragmentConfigurations.flatMap(it -> {
Class<Object> interfaceClass = (Class<Object>) lookupFragmentInterface(repositoryType,
it.getInterfaceName());
Class<?> implementationClass = this.context.loadClass(it.getClassName());
Optional<Bean<?>> bean = getBean(implementationClass, this.beanManager, this.qualifiers);
return Optionals.toStream(bean.map(this::getDependencyInstance)
.map(implementation -> RepositoryFragment.implemented(interfaceClass, implementation)));
}).collect(Collectors.toList());
}
private static Class<?> lookupFragmentInterface(Class<?> repositoryType, String interfaceName) {
return Arrays.stream(repositoryType.getInterfaces()).filter(it -> it.getName().equals(interfaceName))
.findFirst().orElseThrow(() -> new IllegalArgumentException(String.format("Did not find type %s in %s!",
interfaceName, Arrays.asList(repositoryType.getInterfaces()))));
}
/**
* Creates the actual component instance.
* @param creationalContext will never be {@literal null}.
* @param repositoryType will never be {@literal null}.
* @param customImplementation can be {@literal null}.
* @return
* @deprecated since 2.1, override {@link #create(CreationalContext, Class)} in which
* you create a repository factory and call
* {@link #create(RepositoryFactorySupport, Class, RepositoryFragments)}.
*/
@Deprecated
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType,
Optional<Object> customImplementation) {
throw new UnsupportedOperationException(
"You have to implement create(CreationalContext<T>, Class<T>, Optional<Object>) "
+ "in order to use custom repository implementations");
}
/**
* Looks up an instance of a {@link CdiRepositoryConfiguration}. In case the instance
* cannot be found within the CDI scope, a default configuration is used.
* @return an available CdiRepositoryConfiguration instance or a default
* configuration.
*/
protected CdiRepositoryConfiguration lookupConfiguration(BeanManager beanManager, Set<Annotation> qualifiers) {
return beanManager.getBeans(CdiRepositoryConfiguration.class, getQualifiersArray(qualifiers)).stream()
.findFirst().map(it -> (CdiRepositoryConfiguration) getDependencyInstance(it))
.orElse(DEFAULT_CONFIGURATION);
}
/**
* Try to lookup a custom implementation for a
* {@link org.springframework.data.repository.Repository}. Can only be used when a
* {@code CustomRepositoryImplementationDetector} is provided.
* @param repositoryType
* @param cdiRepositoryConfiguration
* @return the custom implementation instance or null
*/
private Optional<Bean<?>> getCustomImplementationBean(Class<?> repositoryType,
CdiRepositoryConfiguration cdiRepositoryConfiguration) {
return this.context.getCustomImplementationClass(repositoryType, cdiRepositoryConfiguration)
.flatMap(type -> getBean(type, this.beanManager, this.qualifiers));
}
/**
* Applies the configuration from {@link CdiRepositoryConfiguration} to
* {@link RepositoryFactorySupport} by looking up the actual configuration.
* @param repositoryFactory will never be {@literal null}.
* @since 2.1
*/
protected void applyConfiguration(RepositoryFactorySupport repositoryFactory) {
applyConfiguration(repositoryFactory, lookupConfiguration(this.beanManager, this.qualifiers));
}
/**
* Applies the configuration from {@link CdiRepositoryConfiguration} to
* {@link RepositoryFactorySupport} by looking up the actual configuration.
* @param repositoryFactory will never be {@literal null}.
* @param configuration will never be {@literal null}.
* @since 2.1
*/
protected static void applyConfiguration(RepositoryFactorySupport repositoryFactory,
CdiRepositoryConfiguration configuration) {
configuration.getEvaluationContextProvider().ifPresent(repositoryFactory::setEvaluationContextProvider);
configuration.getNamedQueries().ifPresent(repositoryFactory::setNamedQueries);
configuration.getQueryLookupStrategy().ifPresent(repositoryFactory::setQueryLookupStrategyKey);
configuration.getRepositoryBeanClass().ifPresent(repositoryFactory::setRepositoryBaseClass);
configuration.getRepositoryProxyPostProcessors().forEach(repositoryFactory::addRepositoryProxyPostProcessor);
configuration.getQueryCreationListeners().forEach(repositoryFactory::addQueryCreationListener);
}
/**
* Creates the actual repository instance.
* @param repositoryType will never be {@literal null}.
* @param repositoryFragments will never be {@literal null}.
* @return
*/
protected static <T> T create(RepositoryFactorySupport repositoryFactory, Class<T> repositoryType,
RepositoryFragments repositoryFragments) {
return repositoryFactory.getRepository(repositoryType, repositoryFragments);
}
private static Optional<Bean<?>> getBean(Class<?> beanType, BeanManager beanManager, Set<Annotation> qualifiers) {
return beanManager.getBeans(beanType, getQualifiersArray(qualifiers)).stream().findFirst();
}
private static Annotation[] getQualifiersArray(Set<Annotation> qualifiers) {
return qualifiers.toArray(new Annotation[qualifiers.size()]);
}
@Override
public String toString() {
return String.format("CdiRepositoryBean: type='%s', qualifiers=%s", this.repositoryType.getName(),
this.qualifiers.toString());
}
enum DefaultCdiRepositoryConfiguration implements CdiRepositoryConfiguration {
INSTANCE;
}
}