-
Notifications
You must be signed in to change notification settings - Fork 53
/
Utilities.java
executable file
·2324 lines (1930 loc) · 83.2 KB
/
Utilities.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) 2012, 2024 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2021 Payara Services Ltd.
*
* 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.jvnet.hk2.internal;
import org.aopalliance.intercept.ConstructorInterceptor;
import org.aopalliance.intercept.MethodInterceptor;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.inject.Qualifier;
import jakarta.inject.Scope;
import jakarta.inject.Singleton;
import org.glassfish.hk2.api.ActiveDescriptor;
import org.glassfish.hk2.api.ClassAnalyzer;
import org.glassfish.hk2.api.Context;
import org.glassfish.hk2.api.ContractIndicator;
import org.glassfish.hk2.api.Descriptor;
import org.glassfish.hk2.api.DescriptorType;
import org.glassfish.hk2.api.DescriptorVisibility;
import org.glassfish.hk2.api.DynamicConfigurationListener;
import org.glassfish.hk2.api.DynamicConfigurationService;
import org.glassfish.hk2.api.ErrorService;
import org.glassfish.hk2.api.ErrorType;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.api.Filter;
import org.glassfish.hk2.api.HK2Loader;
import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.InstanceLifecycleListener;
import org.glassfish.hk2.api.InterceptionService;
import org.glassfish.hk2.api.MethodParameter;
import org.glassfish.hk2.api.MultiException;
import org.glassfish.hk2.api.PerLookup;
import org.glassfish.hk2.api.Proxiable;
import org.glassfish.hk2.api.ProxyCtl;
import org.glassfish.hk2.api.ProxyForSameScope;
import org.glassfish.hk2.api.Rank;
import org.glassfish.hk2.api.Self;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.Unproxiable;
import org.glassfish.hk2.api.Unqualified;
import org.glassfish.hk2.api.UseProxy;
import org.glassfish.hk2.api.ValidationService;
import org.glassfish.hk2.api.Visibility;
import org.glassfish.hk2.api.messaging.SubscribeTo;
import org.glassfish.hk2.utilities.BuilderHelper;
import org.glassfish.hk2.utilities.NamedImpl;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
import org.glassfish.hk2.utilities.reflection.ClassReflectionHelper;
import org.glassfish.hk2.utilities.reflection.Constants;
import org.glassfish.hk2.utilities.reflection.MethodWrapper;
import org.glassfish.hk2.utilities.reflection.Pretty;
import org.glassfish.hk2.utilities.reflection.ParameterizedTypeImpl;
import org.glassfish.hk2.utilities.reflection.ReflectionHelper;
import org.glassfish.hk2.utilities.reflection.ScopeInfo;
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;
import org.jvnet.hk2.annotations.Service;
/**
* This class contains a set of static utilities useful
* for implementing HK2
*
* @author jwells
*
*/
public class Utilities {
private final static String USE_SOFT_REFERENCE_PROPERTY = "org.jvnet.hk2.properties.useSoftReference";
private final static ReentrantLock lock = new ReentrantLock();
final static boolean USE_SOFT_REFERENCE;
static {
USE_SOFT_REFERENCE = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return Boolean.parseBoolean(System.getProperty(USE_SOFT_REFERENCE_PROPERTY, "true"));
}
});
}
private final static AnnotationInformation DEFAULT_ANNOTATION_INFORMATION = new AnnotationInformation(
Collections.<Annotation>emptySet(),
false,
false,
null);
/**
* Returns the class analyzer with the given name
*
* @param sli The ServiceLocator to search in. May not be null
* @param analyzerName The name of the analyzer (may be null for the default analyzer)
* @param errorCollector A non-null collector of exceptions
* @return The ClassAnalyzer corresponding to the name, or null if none was found
*/
public static ClassAnalyzer getClassAnalyzer(
ServiceLocatorImpl sli,
String analyzerName,
Collector errorCollector) {
return sli.getAnalyzer(analyzerName, errorCollector);
}
/**
* Gets the constructor given the implClass and analyzer. Checks service output
*
* @param implClass The implementation class (not null)
* @param analyzer The analyzer (not null)
* @param collector A collector for errors (not null)
* @return null on failure (collector will have failures), non-null on success
*/
public static <T> Constructor<T> getConstructor(Class<T> implClass, ClassAnalyzer analyzer, Collector collector) {
Constructor<T> element = null;
try {
element = analyzer.getConstructor(implClass);
}
catch (MultiException me) {
collector.addMultiException(me);
return element;
}
catch (Throwable th) {
collector.addThrowable(th);
return element;
}
if (element == null) {
collector.addThrowable(new AssertionError("null return from getConstructor method of analyzer " +
analyzer + " for class " + implClass.getName()));
return element;
}
final Constructor<T> result = element;
AccessController.doPrivileged(new PrivilegedAction<Object>(){
@Override
public Object run() {
result.setAccessible(true);
return null;
}
});
return element;
}
/**
* Gets the initializer methods from the given class and analyzer. Checks service output
*
* @param implClass the non-null impl class
* @param analyzer the non-null analyzer
* @param collector for gathering errors
* @return a non-null set (even in error cases, check the collector)
*/
public static Set<Method> getInitMethods(Class<?> implClass, ClassAnalyzer analyzer, Collector collector) {
Set<Method> retVal;
try {
retVal = analyzer.getInitializerMethods(implClass);
}
catch (MultiException me) {
collector.addMultiException(me);
return Collections.emptySet();
}
catch (Throwable th) {
collector.addThrowable(th);
return Collections.emptySet();
}
if (retVal == null) {
collector.addThrowable(new AssertionError("null return from getInitializerMethods method of analyzer " +
analyzer + " for class " + implClass.getName()));
return Collections.emptySet();
}
return retVal;
}
/**
* Gets the initializer fields from the given class and analyzer. Checks service output
*
* @param implClass the non-null impl class
* @param analyzer the non-null analyzer
* @param collector for gathering errors
* @return a non-null set (even in error cases, check the collector)
*/
public static Set<Field> getInitFields(Class<?> implClass, ClassAnalyzer analyzer, Collector collector) {
Set<Field> retVal;
try {
retVal = analyzer.getFields(implClass);
}
catch (MultiException me) {
collector.addMultiException(me);
return Collections.emptySet();
}
catch (Throwable th) {
collector.addThrowable(th);
return Collections.emptySet();
}
if (retVal == null) {
collector.addThrowable(new AssertionError("null return from getFields method of analyzer " +
analyzer + " for class " + implClass.getName()));
return Collections.emptySet();
}
return retVal;
}
/**
* Gets the post construct from the analyzer, checking output
*
* @param implClass The non-null implementation class
* @param analyzer The non-null analyzer
* @param collector The non-null error collector
* @return The possibly null post-construct method (check the collector for errors)
*/
public static Method getPostConstruct(Class<?> implClass, ClassAnalyzer analyzer, Collector collector) {
try {
return analyzer.getPostConstructMethod(implClass);
}
catch (MultiException me) {
collector.addMultiException(me);
return null;
}
catch (Throwable th) {
collector.addThrowable(th);
return null;
}
}
/**
* Gets the preDestroy from the analyzer, checking output
*
* @param implClass The non-null implementation class
* @param analyzer The non-null analyzer
* @param collector The non-null error collector
* @return The possibly null pre-destroy method (check the collector for errors)
*/
public static Method getPreDestroy(Class<?> implClass, ClassAnalyzer analyzer, Collector collector) {
try {
return analyzer.getPreDestroyMethod(implClass);
}
catch (MultiException me) {
collector.addMultiException(me);
return null;
}
catch (Throwable th) {
collector.addThrowable(th);
return null;
}
}
/**
* This utility will return the proper implementation class, taking into account that the
* descriptor may be a factory
*
* @param descriptor The descriptor (reified and not null) that will be used to find the
* implementation
*
* @return The real implementation class
*/
public static Class<?> getFactoryAwareImplementationClass(ActiveDescriptor<?> descriptor) {
if (descriptor.getDescriptorType().equals(DescriptorType.CLASS)) {
return descriptor.getImplementationClass();
}
return getFactoryProductionClass(descriptor);
}
/**
* Checks that the incoming lookup type is not improper in some way
*
* @param checkMe class to check
*/
public static void checkLookupType(Class<?> checkMe) {
if (!checkMe.isAnnotation()) return;
// If it is in annotation we need to ensure it is either a
// scope or a qualifier
if (checkMe.isAnnotationPresent(Scope.class)) return;
if (checkMe.isAnnotationPresent(Qualifier.class)) return;
throw new IllegalArgumentException("Lookup type " + checkMe + " must be a scope or annotation");
}
/**
* Converts the type to its java form, or returns the original
*
* @param type The type to convert
* @return The translated type or the type itself
*/
public static Class<?> translatePrimitiveType(Class<?> type) {
Class<?> translation = Constants.PRIMITIVE_MAP.get(type);
if (translation == null) return type;
return translation;
}
/**
* Calls the list of error services for the list of errors
*
* @param results the results
* @param callThese the services to call
*/
public static void handleErrors(NarrowResults results, LinkedList<ErrorService> callThese) {
Collector collector = new Collector();
for (ErrorResults errorResult : results.getErrors()) {
for (ErrorService eService : callThese) {
try {
eService.onFailure(new ErrorInformationImpl(
ErrorType.FAILURE_TO_REIFY,
errorResult.getDescriptor(),
errorResult.getInjectee(),
errorResult.getMe()));
} catch (MultiException me) {
for (Throwable th : me.getErrors()) {
collector.addThrowable(th);
}
} catch (Throwable th) {
collector.addThrowable(th);
}
}
}
collector.throwIfErrors();
}
/**
* Loads the class using the loader from the given descriptor or the
* classloader of the utilities class otherwise
*
* @param loadMe The fully qualified class name
* @param fromMe The descriptor to use for the loader
* @param collector The error collector to fill in if this returns null
* @return null on failure to load (the failure will be added to the collector)
*/
public static Class<?> loadClass(String loadMe, Descriptor fromMe, Collector collector) {
HK2Loader loader = fromMe.getLoader();
if (loader == null) {
ClassLoader cl = Utilities.class.getClassLoader();
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
}
try {
return cl.loadClass(loadMe);
} catch (Throwable th) {
collector.addThrowable(th);
return null;
}
}
try {
return loader.loadClass(loadMe);
} catch (Throwable th) {
if (th instanceof MultiException) {
MultiException me = (MultiException) th;
for (Throwable th2 : me.getErrors()) {
collector.addThrowable(th2);
}
} else {
collector.addThrowable(th);
}
return null;
}
}
/**
* Load the given class for the given injectee.
*
* @param implementation the impl class name string
* @param injectee the injectee
*
* @return The class represented by this implementation and injectee
*/
public static Class<?> loadClass(String implementation, Injectee injectee) {
ClassLoader loader;
if (injectee != null) {
AnnotatedElement parent = injectee.getParent();
if (parent instanceof Constructor) {
loader = ((Constructor<?>) parent).getDeclaringClass().getClassLoader();
} else if (parent instanceof Method) {
loader = ((Method) parent).getDeclaringClass().getClassLoader();
} else if (parent instanceof Field) {
loader = ((Field) parent).getDeclaringClass().getClassLoader();
} else {
loader = injectee.getClass().getClassLoader();
}
} else {
loader = Utilities.class.getClassLoader();
}
try {
return loader.loadClass(implementation);
} catch (Throwable th) {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl != null) {
try {
return ccl.loadClass(implementation);
}
catch (Throwable th2) {
MultiException me = new MultiException(th);
me.addError(th2);
throw me;
}
}
throw new MultiException(th);
}
}
/**
* Will return the class of the injection resolver annotation type, or null if
* no injection resolver annotation can be found
*
* @param desc The reified descriptor to find the injection resolution on
* @return The annotation type for this injection resolver
*/
@SuppressWarnings("unchecked")
public static Class<? extends Annotation> getInjectionResolverType(ActiveDescriptor<?> desc) {
for (Type advertisedType : desc.getContractTypes()) {
Class<?> rawClass = ReflectionHelper.getRawClass(advertisedType);
if (!InjectionResolver.class.equals(rawClass)) continue;
// Found the InjectionResolver
if (!(advertisedType instanceof ParameterizedType)) {
return null;
}
Type firstType = ReflectionHelper.getFirstTypeArgument(advertisedType);
if (!(firstType instanceof Class)) {
return null;
}
Class<?> retVal = (Class<?>) firstType;
if (!Annotation.class.isAssignableFrom(retVal)) {
return null;
}
return (Class<? extends Annotation>) retVal;
}
return null;
}
/**
* This method returns the class associated with the type of the factory.
*
* @param descriptor The descriptor (reified and not null) that will be used to find the implementation.
* @return the CLASS version of what the factory produces. Will not be null.
* @throws MultiException if there was an error analyzing the class.
*/
private static Class<?> getFactoryProductionClass(ActiveDescriptor<?> descriptor) {
Class<?> factoryClass = descriptor.getImplementationClass();
Type factoryProvidedType = getFactoryProductionType(factoryClass);
Class<?> retVal = ReflectionHelper.getRawClass(factoryProvidedType);
if (retVal == null && descriptor.getContractTypes().size() == 1) {
// If the type was not resolved from a generic type, try to use
// contract type if only one was registered.
Type contract = descriptor.getContractTypes().iterator().next();
retVal = ReflectionHelper.getRawClass(contract);
}
if (retVal == null) {
throw new MultiException(new AssertionError("Could not find true produced type of factory "
+ factoryClass.getName()));
}
return retVal;
}
/**
* This method returns the type produced by a factory class
*
* @param factoryClass The non-null factory class. May not be null
* @return the type version of what the factory produces. Will
* not be null
* @throws MultiException if there was an error analyzing the class
*/
public static Type getFactoryProductionType(Class<?> factoryClass) {
Set<Type> factoryTypes = ReflectionHelper.getTypeClosure(factoryClass,
Collections.singleton(Factory.class.getName()));
ParameterizedType parameterizedType = (ParameterizedType) factoryTypes.iterator().next();
Type factoryProvidedType = parameterizedType.getActualTypeArguments()[0];
return factoryProvidedType;
}
/**
* Checks to be sure the Factory class is ok
*
* @param factoryClass the class to check
* @param collector the exception collector
*/
public static void checkFactoryType(Class<?> factoryClass, Collector collector) {
for (Type type : factoryClass.getGenericInterfaces()) {
Class<?> rawClass = ReflectionHelper.getRawClass(type);
if (rawClass == null) continue;
if (!Factory.class.equals(rawClass)) continue;
Type firstType = ReflectionHelper.getFirstTypeArgument(type);
if (firstType instanceof WildcardType) {
// This should not be possible
collector.addThrowable(new IllegalArgumentException("The class " +
Pretty.clazz(factoryClass) + " has a Wildcard as its type"));
}
}
}
private static boolean hasContract(Class<?> clazz) {
if (clazz == null) return false;
// We give this one for free, to speed up performance
if (clazz.isAnnotationPresent(Contract.class)) return true;
for (Annotation clazzAnnotation : clazz.getAnnotations()) {
if (clazzAnnotation.annotationType().isAnnotationPresent(ContractIndicator.class)) {
return true;
}
}
return false;
}
private static Set<Type> getAutoAdvertisedTypes(Type t) {
LinkedHashSet<Type> retVal = new LinkedHashSet<Type>();
retVal.add(t);
Class<?> rawClass = ReflectionHelper.getRawClass(t);
if (rawClass == null) return retVal;
ContractsProvided provided = rawClass.getAnnotation(ContractsProvided.class);
if (provided != null) {
// Need to clear the retVal, since even the parent class may not be
// in the provided set
retVal.clear();
for (Class<?> providedContract : provided.value()) {
retVal.add(providedContract);
}
return retVal;
}
Set<Type> allTypes = ReflectionHelper.getAllTypes(t);
for (Type candidate : allTypes) {
if (hasContract(ReflectionHelper.getRawClass(candidate))) {
retVal.add(candidate);
}
}
return retVal;
}
/**
* Creates a reified automatically generated descriptor
*
* @param clazz The class to create the desciptor for
* @param locator The service locator for whom we are creating this
* @return A reified active descriptor
*
* @throws MultiException if there was an error in the class
* @throws IllegalArgumentException If the class is null
* @throws IllegalStateException If the name could not be determined from the Named annotation
*/
public static <T> AutoActiveDescriptor<T> createAutoDescriptor(Class<T> clazz, ServiceLocatorImpl locator)
throws MultiException, IllegalArgumentException, IllegalStateException {
if (clazz == null) throw new IllegalArgumentException();
Collector collector = new Collector();
ClazzCreator<T> creator;
Set<Annotation> qualifiers;
Set<Type> contracts;
Class<? extends Annotation> scope;
String name;
Boolean proxy = null;
Boolean proxyForSameScope = null;
String analyzerName;
String serviceMetadata = null;
// Qualifiers naming dance
String serviceName = null;
Service serviceAnno = clazz.getAnnotation(Service.class);
if (serviceAnno != null) {
if(!"".equals(serviceAnno.name())) {
serviceName = serviceAnno.name();
}
if (!"".equals(serviceAnno.metadata())) {
serviceMetadata = serviceAnno.metadata();
}
}
qualifiers = ReflectionHelper.getQualifierAnnotations(clazz);
name = ReflectionHelper.getNameFromAllQualifiers(qualifiers, clazz);
if (serviceName != null && name != null) {
// They must match
if (!serviceName.equals(name)) {
throw new IllegalArgumentException("The class " + clazz.getName() + " has an @Service name of " + serviceName +
" and has an @Named value of " + name +" which names do not match");
}
}
else if (name == null && serviceName != null) {
name = serviceName;
}
qualifiers = getAllQualifiers(clazz, name, collector); // Fixes the @Named qualifier if it has no value
contracts = getAutoAdvertisedTypes(clazz);
ScopeInfo scopeInfo = getScopeInfo(clazz, null, collector);
scope = scopeInfo.getAnnoType();
analyzerName = locator.getPerLocatorUtilities().getAutoAnalyzerName(clazz);
creator = new ClazzCreator<T>(locator, clazz);
Map<String, List<String>> metadata = new HashMap<String, List<String>>();
if (serviceMetadata != null) {
try {
ReflectionHelper.readMetadataMap(serviceMetadata, metadata);
}
catch (IOException ioe) {
// If we can not read it, someone else may have
// a different metadata parser
metadata.clear();
ReflectionHelper.parseServiceMetadataString(serviceMetadata, metadata);
}
}
collector.throwIfErrors();
if (scopeInfo.getScope() != null) {
BuilderHelper.getMetadataValues(scopeInfo.getScope(), metadata);
}
for (Annotation qualifier : qualifiers) {
BuilderHelper.getMetadataValues(qualifier, metadata);
}
UseProxy useProxy = clazz.getAnnotation(UseProxy.class);
if (useProxy != null) {
proxy = useProxy.value();
}
ProxyForSameScope pfss = clazz.getAnnotation(ProxyForSameScope.class);
if (pfss != null) {
proxyForSameScope = pfss.value();
}
DescriptorVisibility visibility = DescriptorVisibility.NORMAL;
Visibility vi = clazz.getAnnotation(Visibility.class);
if (vi != null) {
visibility = vi.value();
}
int rank = BuilderHelper.getRank(clazz);
AutoActiveDescriptor<T> retVal = new AutoActiveDescriptor<T>(
clazz,
creator,
contracts,
scope,
name,
qualifiers,
visibility,
rank,
proxy,
proxyForSameScope,
analyzerName,
metadata,
DescriptorType.CLASS,
clazz);
retVal.setScopeAsAnnotation(scopeInfo.getScope());
creator.initialize(retVal, analyzerName, collector);
collector.throwIfErrors();
return retVal;
}
/**
* Creates a reified automatically generated descriptor
*
* @param parentClazz The class to create the desciptor for
* @param locator The service locator for whom we are creating this
* @return A reified active descriptor
*
* @throws MultiException if there was an error in the class
* @throws IllegalArgumentException If the class is null
* @throws IllegalStateException If the name could not be determined from the Named annotation
*/
public static <T> AutoActiveDescriptor<T> createAutoFactoryDescriptor(Class<T> parentClazz, ActiveDescriptor<?> factoryDescriptor, ServiceLocatorImpl locator)
throws MultiException, IllegalArgumentException, IllegalStateException {
if (parentClazz == null) throw new IllegalArgumentException();
Collector collector = new Collector();
Type factoryProductionType = Utilities.getFactoryProductionType(parentClazz);
Method provideMethod = Utilities.getFactoryProvideMethod(parentClazz);
if (provideMethod == null) {
collector.addThrowable(new IllegalArgumentException("Could not find the provide method on the class " + parentClazz.getName()));
// Guaranteed to throw
collector.throwIfErrors();
}
FactoryCreator<T> creator;
Set<Annotation> qualifiers;
Set<Type> contracts;
Class<? extends Annotation> scope;
String name;
Boolean proxy = null;
Boolean proxyForSameScope = null;
qualifiers = ReflectionHelper.getQualifierAnnotations(provideMethod);
name = ReflectionHelper.getNameFromAllQualifiers(qualifiers, provideMethod);
contracts = getAutoAdvertisedTypes(factoryProductionType);
ScopeInfo scopeInfo = getScopeInfo(provideMethod, null, collector);
scope = scopeInfo.getAnnoType();
creator = new FactoryCreator<T>(locator, factoryDescriptor);
collector.throwIfErrors();
Map<String, List<String>> metadata = new HashMap<String, List<String>>();
if (scopeInfo.getScope() != null) {
BuilderHelper.getMetadataValues(scopeInfo.getScope(), metadata);
}
for (Annotation qualifier : qualifiers) {
BuilderHelper.getMetadataValues(qualifier, metadata);
}
UseProxy useProxy = provideMethod.getAnnotation(UseProxy.class);
if (useProxy != null) {
proxy = useProxy.value();
}
ProxyForSameScope pfss = provideMethod.getAnnotation(ProxyForSameScope.class);
if (pfss != null) {
proxyForSameScope = pfss.value();
}
DescriptorVisibility visibility = DescriptorVisibility.NORMAL;
Visibility vi = provideMethod.getAnnotation(Visibility.class);
if (vi != null) {
visibility = vi.value();
}
int rank = 0;
Rank ranking = provideMethod.getAnnotation(Rank.class);
if (ranking != null) {
rank = ranking.value();
}
AutoActiveDescriptor<T> retVal = new AutoActiveDescriptor<T>(
factoryDescriptor.getImplementationClass(),
creator,
contracts,
scope,
name,
qualifiers,
visibility,
rank,
proxy,
proxyForSameScope,
null, // provide methods do not have analyzers
metadata,
DescriptorType.PROVIDE_METHOD,
null);
retVal.setScopeAsAnnotation(scopeInfo.getScope());
collector.throwIfErrors();
return retVal;
}
/**
* Pre Destroys the given object
*
* @param preMe pre destroys the thing
* @param locator The non-null service locator associated with the operation (for finding the strategy)
* @param strategy The strategy to use for analyzing the class
*/
public static void justPreDestroy(Object preMe, ServiceLocatorImpl locator, String strategy) {
if (preMe == null) throw new IllegalArgumentException();
Collector collector = new Collector();
ClassAnalyzer analyzer = getClassAnalyzer(locator, strategy, collector);
collector.throwIfErrors();
collector.throwIfErrors();
Class<?> baseClass = preMe.getClass();
Method preDestroy = getPreDestroy(baseClass, analyzer, collector);
collector.throwIfErrors();
if (preDestroy == null) return;
try {
ReflectionHelper.invoke(preMe, preDestroy, new Object[0], locator.getNeutralContextClassLoader());
} catch (Throwable e) {
throw new MultiException(e);
}
}
/**
* Post constructs the given object
*
* @param postMe post constructs the thing
* @param locator The non-null service locator associated with the operation (for finding the strategy)
* @param strategy The strategy to use for analyzing the class
*/
public static void justPostConstruct(Object postMe, ServiceLocatorImpl locator, String strategy) {
if (postMe == null) throw new IllegalArgumentException();
Collector collector = new Collector();
ClassAnalyzer analyzer = getClassAnalyzer(locator, strategy, collector);
collector.throwIfErrors();
Class<?> baseClass = postMe.getClass();
Method postConstruct = getPostConstruct(baseClass, analyzer, collector);
collector.throwIfErrors();
if (postConstruct == null) return;
try {
ReflectionHelper.invoke(postMe, postConstruct, new Object[0], locator.getNeutralContextClassLoader());
} catch (Throwable e) {
throw new MultiException(e);
}
}
/**
* Just injects this one method
* @param injectMe
* @param method
* @param locator
* @param givenValues
*/
public static Object justAssistedInject(Object injectMe, Method method, ServiceLocatorImpl locator, ServiceHandle<?> root, MethodParameter... givenValues) {
if (injectMe == null || method == null) {
throw new IllegalArgumentException("injectMe=" + injectMe + " method=" + method);
}
if (givenValues == null) givenValues = new MethodParameter[0];
int numParameters = method.getParameterTypes().length;
Map<Integer, MethodParameter> knownValues = new HashMap<Integer, MethodParameter>();
for (MethodParameter mp : givenValues) {
int index = mp.getParameterPosition();
if (knownValues.containsKey(index)) {
throw new IllegalArgumentException("The given values contain more than one value for index " + index);
}
knownValues.put(index, mp);
if ((index < 0) || (index >= numParameters)) {
throw new IllegalArgumentException("Index of " + mp + " is out of range of the method parameters " + method);
}
}
List<SystemInjecteeImpl> injectees = Utilities.getMethodInjectees(injectMe.getClass(), method, null, knownValues);
Object args[] = new Object[numParameters];
for (int lcv = 0; lcv < injectees.size(); lcv++) {
SystemInjecteeImpl injectee = injectees.get(lcv);
if (injectee == null) {
MethodParameter mp = knownValues.get(lcv);
if (mp == null) {
throw new AssertionError("Error getting values " + lcv + " method=" + method + " injectMe=" + injectMe + " knownValues=" + knownValues);
}
args[lcv] = mp.getParameterValue();
}
else {
InjectionResolver<?> resolver = locator.getPerLocatorUtilities().getInjectionResolver(locator, injectee);
args[lcv] = resolver.resolve(injectee, root);
}
}
try {
return ReflectionHelper.invoke(injectMe, method, args, locator.getNeutralContextClassLoader());
}
catch (MultiException me) {
throw me;
}
catch (Throwable e) {
throw new MultiException(e);
}
}
/**
* Just injects the thing, doesn't try to do anything else
* @param injectMe The object to inject into
* @param locator The locator to find the injection points with
* @param strategy The strategy to use for analyzing the class
*/
public static void justInject(Object injectMe, ServiceLocatorImpl locator, String strategy) {
if (injectMe == null) throw new IllegalArgumentException();
Collector collector = new Collector();
ClassAnalyzer analyzer = getClassAnalyzer(locator, strategy, collector);
collector.throwIfErrors();
Class<?> baseClass = injectMe.getClass();
Set<Field> fields = Utilities.getInitFields(baseClass, analyzer, collector);
Set<Method> methods = Utilities.getInitMethods(baseClass, analyzer, collector);
collector.throwIfErrors();
for (Field field : fields) {
InjectionResolver<?> resolver = locator.getPerLocatorUtilities().getInjectionResolver(locator, field);
List<SystemInjecteeImpl> injecteeFields = Utilities.getFieldInjectees(baseClass, field, null);
validateSelfInjectees(null, injecteeFields, collector);
collector.throwIfErrors();
Injectee injectee = injecteeFields.get(0);
Object fieldValue = resolver.resolve(injectee, null);
try {
ReflectionHelper.setField(field, injectMe, fieldValue);
}
catch (MultiException me) {
throw me;
}
catch (Throwable th) {
throw new MultiException(th);