-
Notifications
You must be signed in to change notification settings - Fork 53
/
ProvidesListener.java
1106 lines (954 loc) · 38.5 KB
/
ProvidesListener.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2020 TechEmpower. All rights reserved.
* Copyright (c) 2024 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.hk2.extras.provides;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jakarta.inject.Inject;
import jakarta.inject.Scope;
import jakarta.inject.Singleton;
import org.glassfish.hk2.api.ActiveDescriptor;
import org.glassfish.hk2.api.ContractIndicator;
import org.glassfish.hk2.api.Descriptor;
import org.glassfish.hk2.api.DynamicConfiguration;
import org.glassfish.hk2.api.DynamicConfigurationListener;
import org.glassfish.hk2.api.DynamicConfigurationService;
import org.glassfish.hk2.api.Filter;
import org.glassfish.hk2.api.MultiException;
import org.glassfish.hk2.api.PerLookup;
import org.glassfish.hk2.api.Self;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
import org.glassfish.hk2.utilities.reflection.ReflectionHelper;
import org.glassfish.hk2.utilities.reflection.TypeChecker;
import org.jvnet.hk2.annotations.Contract;
import org.jvnet.hk2.annotations.ContractsProvided;
import org.jvnet.hk2.annotations.Optional;
/**
* Enables the {@link Provides} annotation.
*
* <p>Only one {@link ProvidesListener} instance may be registered with each
* {@link ServiceLocator}.
*/
@Singleton
public class ProvidesListener implements DynamicConfigurationListener {
private final ServiceLocator locator;
private final ProvidersSeen seen = new ProvidersSeen();
private static final ReentrantLock slock = new ReentrantLock();
private static final Object UNIQUE = new Object() {};
@Inject
public ProvidesListener(ServiceLocator locator) {
this.locator = Objects.requireNonNull(locator);
// Two listeners registered with the same locator could cause a feedback
// loop since they can't share the cache of the providers they have seen.
// Defend against this by disallowing the second listener.
slock.lock();
try {
if (locator.getService(UNIQUE.getClass()) != null) {
throw new IllegalStateException(
"There is already a "
+ getClass().getSimpleName()
+ " registered with this locator");
}
ServiceLocatorUtilities.addOneConstant(locator, UNIQUE);
} finally {
slock.unlock();
}
}
/**
* Matches services whose {@linkplain Descriptor#getImplementation()
* implementation} classes are scanned for {@link Provides} annotations.
*
* <p>The default filter matches all services. Override this method to permit
* a smaller subset of services. For example:
*
* <pre>
* @Singleton
* public class FilteredProvidesListener extends ProvidesListener {
* @Inject
* public FilteredProvidesListener(ServiceLocator locator) {
* super(locator);
* }
*
* @Override
* protected Filter getFilter() {
* return d -> d.getImplementation().startsWith("com.example.");
* }
* }
* </pre>
*/
protected Filter getFilter() {
return any -> true;
}
/**
* Called when an invalid {@link Provides} annotation is found.
*
* <p>The default implementation of this method does nothing. Override this
* method to consume the reported information. For example:
*
* <pre>
* @Singleton
* public class LoggingProvidesListener extends ProvidesListener {
* private final Logger logger = LoggerFactory.getLogger(getClass());
*
* @Inject
* public LoggingProvidesListener(ServiceLocator locator) {
* super(locator);
* }
*
* @Override
* protected void onInvalidProvidesAnnotation(
* ActiveDescriptor<?> providerDescriptor,
* Provides providesAnnotation,
* AnnotatedElement annotatedElement,
* String message) {
*
* logger.error(message);
* }
* }
* </pre>
*
* <p>If this method does not throw an exception, then after calling this
* method, this listener will ignore this {@link Provides} annotation —
* registering no new {@link ActiveDescriptor} on its behalf — and this
* listener will continue to scan this provider and other providers for other
* {@link Provides} annotations.
*
* <p>If this method does throw an exception, then the behavior of this
* listener from this point forward is undefined.
*
* @param providerDescriptor the descriptor of the service that contains this
* {@link Provides} annotation
* @param providesAnnotation the {@link Provides} annotation on the method or
* field
* @param annotatedElement the method or field that is annotated with {@link
* Provides}
* @param message a message explaining why this {@link Provides} annotation
* is invalid
*/
protected void onInvalidProvidesAnnotation(
ActiveDescriptor<?> providerDescriptor,
Provides providesAnnotation,
AnnotatedElement annotatedElement,
String message) {
Objects.requireNonNull(providerDescriptor);
Objects.requireNonNull(providesAnnotation);
Objects.requireNonNull(annotatedElement);
Objects.requireNonNull(message);
// Do nothing.
}
@Override
public void configurationChanged() {
Filter filter = getFilter();
Set<ActiveDescriptor<?>> providers = new LinkedHashSet<>();
for (ActiveDescriptor<?> provider : locator.getDescriptors(filter))
providers.add(locator.reifyDescriptor(provider));
seen.retainAll(providers);
DynamicConfigurationService configurationService =
locator.getService(DynamicConfigurationService.class);
DynamicConfiguration configuration =
configurationService.createDynamicConfiguration();
int added = 0;
for (ActiveDescriptor<?> provider : providers)
added += addDescriptors(provider, Collections.emptySet(), configuration);
if (added > 0)
configuration.commit();
}
/**
* Adds descriptors for each of the methods and fields annotated with {@link
* Provides} in the specified service. Recursively discovers {@link Provides}
* annotations in the implementations of the added descriptors.
*
* <p>This method is idempotent.
*
* @param providerDescriptor the descriptor of the service which may contain
* {@link Provides} annotations
* @param ancestors when this method is invoked recursively, the set of
* provider {@linkplain ActiveDescriptor#getImplementationClass()
* implementation classes} that were examined leading to the discovery
* of this provider
* @param configuration the configuration to be modified with new descriptors
* @return the number of descriptors added as a result of the call
*/
private int addDescriptors(ActiveDescriptor<?> providerDescriptor,
Set<Class<?>> ancestors,
DynamicConfiguration configuration) {
Objects.requireNonNull(providerDescriptor);
Objects.requireNonNull(ancestors);
Objects.requireNonNull(configuration);
if (!seen.add(providerDescriptor))
return 0;
List<ActiveDescriptor<?>> added = new ArrayList<>();
Class<?> providerClass = providerDescriptor.getImplementationClass();
Type providerType = providerDescriptor.getImplementationType();
methodLoop:
for (Method method : providerClass.getMethods()) {
Provides providesAnnotation = method.getAnnotation(Provides.class);
if (providesAnnotation == null)
continue;
if (!seen.add(providerDescriptor, method))
continue;
Class<?> providedClass = method.getReturnType();
if (!Modifier.isStatic(method.getModifiers())
&& (providedClass == providerClass || ancestors.contains(providedClass))) {
onInvalidProvidesAnnotation(
providerDescriptor,
providesAnnotation,
method,
"@" + Provides.class.getSimpleName()
+ " method would form an infinite loop of providers.\n"
+ "\tMethod: " + method + "\n"
+ "\tClasses in loop: "
+ Stream.concat(ancestors.stream(),
Stream.of(providerClass, providedClass))
.map(c -> c.getName())
.collect(Collectors.joining(" -> "))
+ "\n");
continue;
}
Type providedType =
TypeUtils.resolveType(
providerType,
method.getGenericReturnType());
if (TypeUtils.containsTypeVariable(providedType)) {
onInvalidProvidesAnnotation(
providerDescriptor,
providesAnnotation,
method,
"@" + Provides.class.getSimpleName()
+ " method return type contains an unresolvable type variable.\n"
+ "\tMethod: " + method + "\n"
+ "\tMethod owner type: " + providerType.getTypeName() + "\n"
+ "\tDeclared method return type: " + method.getGenericReturnType() + "\n"
+ "\tResolved method return type: " + providedType.getTypeName() + "\n");
continue;
}
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
Type parameterType =
TypeUtils.resolveType(
providerType,
parameter.getParameterizedType());
if (TypeUtils.containsTypeVariable(parameterType)) {
onInvalidProvidesAnnotation(
providerDescriptor,
providesAnnotation,
method,
"@" + Provides.class.getSimpleName()
+ " method parameter type contains an unresolvable type variable.\n"
+ "\tMethod: " + method + "\n"
+ "\tMethod owner type: " + providerType.getTypeName() + "\n"
+ "\tParameter index: " + i + "\n"
+ "\tDeclared parameter type: " + parameter.getParameterizedType() + "\n"
+ "\tResolved parameter type: " + parameterType + "\n");
continue methodLoop;
}
}
Set<Type> contracts =
getContracts(
providesAnnotation,
providedType);
Annotation scopeAnnotation =
getScopeAnnotation(
providerDescriptor,
method,
contracts);
AtomicReference<ActiveDescriptor<?>> self = new AtomicReference<>();
Function<ServiceHandle<?>, Object> createFunction;
if (Modifier.isStatic(method.getModifiers()))
createFunction =
getCreateFunctionFromStaticMethod(
method,
providerType,
self,
locator);
else
createFunction =
getCreateFunctionFromInstanceMethod(
method,
providerType,
providerDescriptor,
self,
locator);
Consumer<Object> disposeFunction =
getDisposeFunction(
providerDescriptor,
providesAnnotation,
method,
providedClass,
providedType,
providerClass,
providerType,
self,
locator);
if (disposeFunction == null) {
onInvalidProvidesAnnotation(
providerDescriptor,
providesAnnotation,
method,
"@" + Provides.class.getSimpleName()
+ " method specifies an invalid dispose method.\n"
+ "\tMethod: " + method + "\n"
+ "\tMethod owner type: " + providerType.getTypeName() + "\n"
+ "\tDispose method: " + providesAnnotation.disposeMethod() + "\n"
+ "\tDisposal handled by: " + providesAnnotation.disposalHandledBy() + "\n"
+ "\tPossible causes:\n"
+ "\t\tThere is no method with the specified name.\n"
+ "\t\tThe specified method is not public.\n"
+ "\t\tDisposal is handled by the provided instance and...\n"
+ "\t\t\tthe specified method is static.\n"
+ "\t\t\tthe specified method does not have zero parameters.\n"
+ "\t\tDisposal is handled by the provider and...\n"
+ "\t\t\tthe specified method does not have at least one parameter.\n"
+ "\t\t\tone of the method parameter types contains an unresolved type variable.\n"
+ "\t\t\tthe type of the first parameter is not a supertype of the provided service.\n"
+ "\t\t\tmore than one method matches the specifications.\n");
continue;
}
ActiveDescriptor<?> newDescriptor =
configuration.addActiveDescriptor(
new ProvidesDescriptor<>(
method,
providedClass,
providedType,
contracts,
scopeAnnotation,
createFunction,
disposeFunction));
self.set(newDescriptor);
added.add(newDescriptor);
}
for (Field field : providerClass.getFields()) {
Provides providesAnnotation = field.getAnnotation(Provides.class);
if (providesAnnotation == null)
continue;
if (!seen.add(providerDescriptor, field))
continue;
Class<?> providedClass = field.getType();
if (!Modifier.isStatic(field.getModifiers())
&& (providedClass == providerClass || ancestors.contains(providedClass))) {
onInvalidProvidesAnnotation(
providerDescriptor,
providesAnnotation,
field,
"@" + Provides.class.getSimpleName()
+ " field would form an infinite loop of providers.\n"
+ "\tField: " + field + "\n"
+ "\tClasses in loop: "
+ Stream.concat(ancestors.stream(),
Stream.of(providerClass, providedClass))
.map(c -> c.getName())
.collect(Collectors.joining(" -> "))
+ "\n");
continue;
}
Type providedType =
TypeUtils.resolveType(
providerType,
field.getGenericType());
if (TypeUtils.containsTypeVariable(providedType)) {
onInvalidProvidesAnnotation(
providerDescriptor,
providesAnnotation,
field,
"@" + Provides.class.getSimpleName()
+ " field type contains an unresolvable type variable.\n"
+ "\tField: " + field + "\n"
+ "\tField owner type: " + providerType.getTypeName() + "\n"
+ "\tDeclared field type: " + field.getGenericType().getTypeName() + "\n"
+ "\tResolved field type: " + providedType.getTypeName() + "\n");
continue;
}
Set<Type> contracts =
getContracts(
providesAnnotation,
providedType);
Annotation scopeAnnotation =
getScopeAnnotation(
providerDescriptor,
field,
contracts);
Function<ServiceHandle<?>, Object> createFunction;
if (Modifier.isStatic(field.getModifiers()))
createFunction =
getCreateFunctionFromStaticField(
field,
locator);
else
createFunction =
getCreateFunctionFromInstanceField(
providerDescriptor,
field,
locator);
// There is no automatic disposal for fields.
Consumer<Object> disposeFunction = instance -> {};
ActiveDescriptor<?> newDescriptor =
configuration.addActiveDescriptor(
new ProvidesDescriptor<>(
field,
providedClass,
providedType,
contracts,
scopeAnnotation,
createFunction,
disposeFunction));
added.add(newDescriptor);
}
if (added.isEmpty())
return 0;
int addedCount = added.size();
Set<Class<?>> newAncestors = new LinkedHashSet<>(ancestors);
newAncestors.add(providerClass);
for (ActiveDescriptor<?> newDescriptor : added)
addedCount += addDescriptors(newDescriptor, newAncestors, configuration);
return addedCount;
}
/**
* Returns the set of contracts defined by a method or field that is annotated
* with {@link Provides}.
*
* @param providesAnnotation the {@link Provides} annotation on the method or
* field
* @param providedType the {@link Method#getGenericReturnType()} of the
* annotated method or the {@link Field#getGenericType()} of the
* annotated field
*/
private static Set<Type> getContracts(Provides providesAnnotation,
Type providedType) {
Objects.requireNonNull(providesAnnotation);
Objects.requireNonNull(providedType);
if (providesAnnotation.contracts().length > 0)
return Arrays.stream(providesAnnotation.contracts())
.collect(
Collectors.collectingAndThen(
Collectors.toSet(),
set -> Collections.unmodifiableSet(set)));
// This block of code reproduces the behavior of
// org.jvnet.hk2.internal.Utilities#getAutoAdvertisedTypes(Type)
Class<?> rawClass = ReflectionHelper.getRawClass(providedType);
if (rawClass == null)
return Collections.singleton(providedType);
ContractsProvided explicit = rawClass.getAnnotation(ContractsProvided.class);
if (explicit != null)
return Arrays.stream(explicit.value())
.collect(
Collectors.collectingAndThen(
Collectors.toSet(),
set -> Collections.unmodifiableSet(set)));
return Stream.concat(Stream.of(providedType),
ReflectionHelper.getAllTypes(providedType)
.stream()
.filter(t -> isContract(t)))
.collect(
Collectors.collectingAndThen(
Collectors.toSet(),
set -> Collections.unmodifiableSet(set)));
}
/**
* Returns {@code true} if the specified type is a contract.
*/
private static boolean isContract(Type type) {
Objects.requireNonNull(type);
// This block of code reproduces the behavior of
// org.jvnet.hk2.internal.Utilities#hasContract(Class)
Class<?> rawClass = ReflectionHelper.getRawClass(type);
if (rawClass == null)
return false;
if (rawClass.isAnnotationPresent(Contract.class))
return true;
for (Annotation annotation : rawClass.getAnnotations())
if (annotation.annotationType().isAnnotationPresent(ContractIndicator.class))
return true;
return false;
}
/**
* Returns the scope annotation for a method or field that is annotated with
* {@link Provides}.
*
* @param providerDescriptor the descriptor of the service that defines the
* method or field, in case the scope of that service is relevant
* @param providerMethodOrField the method or field that is annotated with
* {@link Provides}
* @param providedContracts the contracts provided by the method or field
*/
private static <T extends AccessibleObject & Member> Annotation
getScopeAnnotation(ActiveDescriptor<?> providerDescriptor,
T providerMethodOrField,
Set<Type> providedContracts) {
Objects.requireNonNull(providerDescriptor);
Objects.requireNonNull(providerMethodOrField);
Objects.requireNonNull(providedContracts);
for (Annotation annotation : providerMethodOrField.getAnnotations())
if (annotation.annotationType().isAnnotationPresent(Scope.class))
return annotation;
for (Type contract : providedContracts) {
Class<?> rawClass = ReflectionHelper.getRawClass(contract);
if (rawClass != null)
for (Annotation annotation : rawClass.getAnnotations())
if (annotation.annotationType().isAnnotationPresent(Scope.class))
return annotation;
}
if (!Modifier.isStatic(providerMethodOrField.getModifiers())) {
Annotation providerScopeAnnotation =
providerDescriptor.getScopeAsAnnotation();
if (providerScopeAnnotation != null)
return providerScopeAnnotation;
}
return ServiceLocatorUtilities.getPerLookupAnnotation();
}
/**
* Returns a function that creates instances of services by invoking a static
* method that is annotated with {@link Provides}.
*
* @param method the static method that is annotated with {@link Provides}
* @param providerType the type of the service that defines the method
* @param self supplies the descriptor of the service provided by the method
* @param locator the service locator
*/
private static Function<ServiceHandle<?>, Object>
getCreateFunctionFromStaticMethod(Method method,
Type providerType,
AtomicReference<ActiveDescriptor<?>> self,
ServiceLocator locator) {
Objects.requireNonNull(method);
Objects.requireNonNull(providerType);
Objects.requireNonNull(self);
Objects.requireNonNull(locator);
return (ServiceHandle<?> root) -> {
Object[] arguments =
Arrays.stream(method.getParameters())
.map(
parameter -> {
if (isSelf(parameter))
return self.get();
return InjectUtils.serviceFromParameter(
parameter,
providerType,
root,
locator);
})
.toArray(length -> new Object[length]);
if (!canAccess(method, null))
method.setAccessible(true);
Object provided;
try {
provided = method.invoke(null, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new MultiException(e);
}
return provided;
};
}
/**
* Returns a function that creates instances of services by invoking an
* instance method that is annotated with {@link Provides}.
*
* @param method the instance method that is annotated with {@link Provides}
* @param providerType the type of the service that defines the method
* @param providerDescriptor the descriptor of the service that defines the
* method
* @param self supplies the descriptor of the service provided by the method
* @param locator the service locator
*/
private static Function<ServiceHandle<?>, Object>
getCreateFunctionFromInstanceMethod(Method method,
Type providerType,
ActiveDescriptor<?> providerDescriptor,
AtomicReference<ActiveDescriptor<?>> self,
ServiceLocator locator) {
Objects.requireNonNull(providerDescriptor);
Objects.requireNonNull(providerType);
Objects.requireNonNull(method);
Objects.requireNonNull(self);
Objects.requireNonNull(locator);
return (ServiceHandle<?> root) -> {
Object[] arguments =
Arrays.stream(method.getParameters())
.map(
parameter -> {
if (isSelf(parameter))
return self.get();
return InjectUtils.serviceFromParameter(
parameter,
providerType,
root,
locator);
})
.toArray(length -> new Object[length]);
Object provider =
locator.getService(providerDescriptor, root, null);
Objects.requireNonNull(provider);
if (!canAccess(method, provider))
method.setAccessible(true);
Object provided;
try {
provided = method.invoke(provider, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new MultiException(e);
}
return provided;
};
}
/**
* Returns a function that creates instances of services by reading a static
* field that is annotated with {@link Provides}.
*
* @param field the static field that is annotated with {@link Provides}
* @param locator the service locator
*/
private static Function<ServiceHandle<?>, Object>
getCreateFunctionFromStaticField(Field field, ServiceLocator locator) {
Objects.requireNonNull(field);
Objects.requireNonNull(locator);
return (ServiceHandle<?> root) -> {
if (!canAccess(field, null))
field.setAccessible(true);
Object provided;
try {
provided = field.get(null);
} catch (IllegalAccessException e) {
throw new MultiException(e);
}
return provided;
};
}
/**
* Returns a function that creates instances of services by reading an
* instance field that is annotated with {@link Provides}.
*
* @param providerDescriptor the descriptor of the service that defines the
* field
* @param field the instance field that is annotated with {@link Provides}
* @param locator the service locator
*/
private static Function<ServiceHandle<?>, Object>
getCreateFunctionFromInstanceField(ActiveDescriptor<?> providerDescriptor,
Field field,
ServiceLocator locator) {
Objects.requireNonNull(providerDescriptor);
Objects.requireNonNull(field);
Objects.requireNonNull(locator);
return (ServiceHandle<?> root) -> {
Object provider = locator.getService(providerDescriptor, root, null);
Objects.requireNonNull(provider);
if (!canAccess(field, provider))
field.setAccessible(true);
Object provided;
try {
provided = field.get(provider);
} catch (IllegalAccessException e) {
throw new MultiException(e);
}
return provided;
};
}
/**
* Returns a function that disposes of instances of services that were
* retrieved from a method annotated with {@link Provides}. Returns {@code
* null} if the {@link Provides} annotation has a non-empty {@link
* Provides#disposeMethod()} and the method it specifies is not found.
*
* @param providerDescriptor the descriptor of the service that defines the
* method
* @param providesAnnotation the {@link Provides} annotation on the method
* @param providerMethod the method that is annotated with {@link Provides}
* @param providedClass the {@link Method#getReturnType()} ()}
* @param providedType the {@link Method#getGenericReturnType()}
* @param providerClass the class of the service that defines the method
* @param providerType the type of the service that defines the method
* @param self supplies the descriptor of the service provided by the method
* @param locator the service locator
*/
private static <T extends AccessibleObject & Member> /*@Nullable*/ Consumer<Object>
getDisposeFunction(ActiveDescriptor<?> providerDescriptor,
Provides providesAnnotation,
Method providerMethod,
Class<?> providedClass,
Type providedType,
Class<?> providerClass,
Type providerType,
AtomicReference<ActiveDescriptor<?>> self,
ServiceLocator locator) {
Objects.requireNonNull(providerDescriptor);
Objects.requireNonNull(providesAnnotation);
Objects.requireNonNull(providerMethod);
Objects.requireNonNull(providedClass);
Objects.requireNonNull(providedType);
Objects.requireNonNull(providerClass);
Objects.requireNonNull(providerType);
Objects.requireNonNull(self);
Objects.requireNonNull(locator);
if (providesAnnotation.disposeMethod().isEmpty())
return instance -> {
if (instance != null)
locator.preDestroy(instance);
};
switch (providesAnnotation.disposalHandledBy()) {
case PROVIDED_INSTANCE: {
Method disposeMethod =
Arrays.stream(providedClass.getMethods())
.filter(method -> method.getName().equals(providesAnnotation.disposeMethod()))
.filter(method -> !Modifier.isStatic(method.getModifiers()))
.filter(method -> method.getParameterCount() == 0)
.findAny()
.orElse(null);
if (disposeMethod == null)
return null;
return instance -> {
if (instance == null)
return;
if (!canAccess(disposeMethod, instance))
disposeMethod.setAccessible(true);
try {
disposeMethod.invoke(instance);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new MultiException(e);
}
};
}
case PROVIDER: {
Set<Method> disposeMethods =
Arrays.stream(providerClass.getMethods())
.filter(method -> method.getName().equals(providesAnnotation.disposeMethod()))
.filter(method -> method.getParameterCount() >= 1)
.filter(method -> {
int indexOfArgumentToDispose = 0;
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
Type parameterType =
TypeUtils.resolveType(
providerType,
parameter.getParameterizedType());
// TODO: Additional type information is being supplied by
// the provided type, and that could theoretically
// resolve type variables in the generic parameter
// types of this method.
if (i == indexOfArgumentToDispose
&& !TypeChecker.isRawTypeSafe(parameterType,
providedType))
return false;
if (TypeUtils.containsTypeVariable(parameterType))
return false;
}
return true;
})
.collect(
Collectors.collectingAndThen(
Collectors.toSet(),
set -> Collections.unmodifiableSet(set)));
if (disposeMethods.size() != 1)
return null;
Method disposeMethod = disposeMethods.iterator().next();
return instance -> {
if (instance == null)
return;
List<ServiceHandle<?>> perLookupHandles = new ArrayList<>();
try {
int indexOfArgumentToDispose = 0;
Parameter[] parameters = disposeMethod.getParameters();
Object[] arguments = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (i == indexOfArgumentToDispose)
arguments[i] = instance;
else if (isSelf(parameters[i]))
arguments[i] = self.get();
else {
ServiceHandle<?> parameterHandle =
InjectUtils.serviceHandleFromParameter(
parameters[i],
providerType,
locator);
if (parameterHandle == null)
arguments[i] = null;
else {
if (isPerLookup(parameterHandle))
perLookupHandles.add(parameterHandle);
arguments[i] = parameterHandle.getService();
}
}
}
if (Modifier.isStatic(disposeMethod.getModifiers())) {
if (!canAccess(disposeMethod, null))
disposeMethod.setAccessible(true);
try {
disposeMethod.invoke(null, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new MultiException(e);
}
return;
}
ServiceHandle<?> providerHandle =
locator.getServiceHandle(providerDescriptor);
if (isPerLookup(providerHandle))
perLookupHandles.add(providerHandle);
Object provider = providerHandle.getService();
Objects.requireNonNull(provider);
if (!canAccess(disposeMethod, provider))
disposeMethod.setAccessible(true);
try {
disposeMethod.invoke(provider, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new MultiException(e);
}
} finally {
for (ServiceHandle<?> handle : perLookupHandles)
handle.close();
}
};
}
}
throw new AssertionError(
"Unknown "
+ Provides.DisposalHandledBy.class.getSimpleName()
+ " value: "
+ providesAnnotation.disposalHandledBy());
}
/**
* Returns {@code true} if the specified service handle has {@link PerLookup}
* scope.
*/
private static boolean isPerLookup(ServiceHandle<?> handle) {
Objects.requireNonNull(handle);
return handle.getActiveDescriptor().getScopeAnnotation() == PerLookup.class;
}
/**
* Returns {@code true} if the specified parameter is a {@link Self} injection
* point.
*/
private static boolean isSelf(Parameter parameter) {
Objects.requireNonNull(parameter);
return parameter.isAnnotationPresent(Self.class)
&& parameter.getType() == ActiveDescriptor.class
&& !parameter.isAnnotationPresent(Optional.class)