下面列出了org.springframework.data.domain.SliceImpl#org.jboss.jandex.ClassInfo 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private boolean requiresValidation(MethodInfo method) {
if (method.annotations().isEmpty()) {
// This method has no annotations of its own: look for inherited annotations
ClassInfo clazz = method.declaringClass();
String methodName = method.name().toString();
for (Map.Entry<DotName, Set<String>> validatedMethod : inheritedAnnotationsToBeValidated.entrySet()) {
if (clazz.interfaceNames().contains(validatedMethod.getKey())
&& validatedMethod.getValue().contains(methodName)) {
return true;
}
}
return false;
}
for (DotName consideredAnnotation : consideredAnnotations) {
if (method.hasAnnotation(consideredAnnotation)) {
return true;
}
}
return false;
}
private List<CloudFunctionBuildItem> registerFunctions(BuildProducer<UnremovableBeanBuildItem> unremovableBeans,
Collection<ClassInfo> functions,
GoogleCloudFunctionInfo.FunctionType functionType) {
List<CloudFunctionBuildItem> buildItems = new ArrayList<>();
for (ClassInfo classInfo : functions) {
String className = classInfo.name().toString();
unremovableBeans.produce(UnremovableBeanBuildItem.beanClassNames(className));
List<AnnotationInstance> annotationInstances = classInfo.annotations().get(DOTNAME_NAMED);
CloudFunctionBuildItem buildItem = new CloudFunctionBuildItem(className, functionType);
if (annotationInstances != null) {
buildItem.setBeanName(annotationInstances.get(0).value().asString());
}
buildItems.add(buildItem);
}
return buildItems;
}
@BuildStep
AnnotationsTransformerBuildItem annotationTransformer(CustomScopeAnnotationsBuildItem scopes) {
return new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {
@Override
public boolean appliesTo(org.jboss.jandex.AnnotationTarget.Kind kind) {
return kind == org.jboss.jandex.AnnotationTarget.Kind.CLASS;
}
@Override
public void transform(TransformationContext context) {
if (!scopes.isScopeIn(context.getAnnotations())) {
// Class with no scope annotation but with a method annotated with @Route, @RouteFilter
ClassInfo target = context.getTarget().asClass();
if (target.annotations().containsKey(ROUTE) || target.annotations().containsKey(ROUTES)
|| target.annotations().containsKey(ROUTE_FILTER)) {
LOGGER.debugf(
"Found route handler business methods on a class %s with no scope annotation - adding @Singleton",
context.getTarget());
context.transform().add(Singleton.class).done();
}
}
}
});
}
private Type verifyQueryResultType(Type t) {
if (isIntLongOrBoolean(t.name())) {
return t;
}
if (t.kind() == Kind.ARRAY) {
return verifyQueryResultType(t.asArrayType().component());
} else if (t.kind() == Kind.PARAMETERIZED_TYPE) {
List<Type> list = t.asParameterizedType().arguments();
if (list.size() == 1) {
return verifyQueryResultType(list.get(0));
} else {
for (Type x : list) {
verifyQueryResultType(x);
}
return t;
}
} else if (!DotNames.OBJECT.equals(t.name())) {
ClassInfo typeClassInfo = index.getClassByName(t.name());
if (typeClassInfo == null) {
throw new IllegalStateException(t.name() + " was not part of the Quarkus index");
}
}
return t;
}
private void addErrors(Schema schema) {
Collection<AnnotationInstance> errorAnnotations = ScanningContext.getIndex().getAnnotations(Annotations.ERROR_CODE);
if (errorAnnotations != null && !errorAnnotations.isEmpty()) {
for (AnnotationInstance errorAnnotation : errorAnnotations) {
AnnotationTarget annotationTarget = errorAnnotation.target();
if (annotationTarget.kind().equals(AnnotationTarget.Kind.CLASS)) {
ClassInfo exceptionClass = annotationTarget.asClass();
AnnotationValue value = errorAnnotation.value();
if (value != null && value.asString() != null && !value.asString().isEmpty()) {
schema.addError(new ErrorInfo(exceptionClass.name().toString(), value.asString()));
} else {
LOG.warn("Ignoring @ErrorCode on " + annotationTarget.toString() + " - Annotation value is not set");
}
} else {
LOG.warn("Ignoring @ErrorCode on " + annotationTarget.toString() + " - Wrong target, only apply to CLASS ["
+ annotationTarget.kind().toString() + "]");
}
}
}
}
/**
* Extract the package information from the given {@code ClassInfo} object.
*
* @param classInfo the class metadata.
* @param packages the collection to which we need to add the package information.
*/
private static void extractAndAddPackageInfo(ClassInfo classInfo, Set<String> packages, IndexView indexView) {
if (classInfo == null) {
return;
}
// Check if we were given an abstract class / interface, in which case we need to check the IndexView to see if there
// is an implementation or not.
String className = classInfo.name().toString();
if (indexView != null) {
DotName dotName = DotName.createSimple(className);
if (Modifier.isInterface(classInfo.flags())) {
indexView.getAllKnownImplementors(dotName).forEach(ci -> extractAndAddPackageInfo(ci, packages, indexView));
} else if (Modifier.isAbstract(classInfo.flags())) {
indexView.getAllKnownSubclasses(dotName).forEach(ci -> extractAndAddPackageInfo(ci, packages, indexView));
}
}
StringBuilder builder = new StringBuilder(className).reverse();
int idx = builder.indexOf(".");
if (idx != -1) {
builder.delete(0, idx + 1);
}
packages.add(builder.reverse().toString());
}
static Type resolveTypeParam(Type typeParam, Map<TypeVariable, Type> resolvedTypeParameters, IndexView index) {
if (typeParam.kind() == Kind.TYPE_VARIABLE) {
return resolvedTypeParameters.getOrDefault(typeParam, typeParam);
} else if (typeParam.kind() == Kind.PARAMETERIZED_TYPE) {
ParameterizedType parameterizedType = typeParam.asParameterizedType();
ClassInfo classInfo = index.getClassByName(parameterizedType.name());
if (classInfo != null) {
List<TypeVariable> typeParameters = classInfo.typeParameters();
List<Type> arguments = parameterizedType.arguments();
Type[] typeParams = new Type[typeParameters.size()];
for (int i = 0; i < typeParameters.size(); i++) {
typeParams[i] = resolveTypeParam(arguments.get(i), resolvedTypeParameters, index);
}
return ParameterizedType.create(parameterizedType.name(), typeParams, null);
}
}
return typeParam;
}
Collection<MethodInfo> getDelegatingMethods(BeanInfo bean) {
Map<Methods.MethodKey, MethodInfo> methods = new HashMap<>();
if (bean.isClassBean()) {
Methods.addDelegatingMethods(bean.getDeployment().getIndex(), bean.getTarget().get().asClass(),
methods);
} else if (bean.isProducerMethod()) {
MethodInfo producerMethod = bean.getTarget().get().asMethod();
ClassInfo returnTypeClass = getClassByName(bean.getDeployment().getIndex(), producerMethod.returnType());
Methods.addDelegatingMethods(bean.getDeployment().getIndex(), returnTypeClass, methods);
} else if (bean.isProducerField()) {
FieldInfo producerField = bean.getTarget().get().asField();
ClassInfo fieldClass = getClassByName(bean.getDeployment().getIndex(), producerField.type());
Methods.addDelegatingMethods(bean.getDeployment().getIndex(), fieldClass, methods);
} else if (bean.isSynthetic()) {
Methods.addDelegatingMethods(bean.getDeployment().getIndex(), bean.getImplClazz(), methods);
}
return methods.values();
}
@Override
public Collection<ClassInfo> extractDataClasses(Collection<ClassInfo> input, String targetDirectory) {
Set<ClassInfo> dataModelClasses = new HashSet<>();
for (ClassInfo modelClazz : input) {
try {
for (FieldInfo pd : modelClazz.fields()) {
if (pd.type().name().toString().startsWith("java.lang")
|| pd.type().name().toString().equals(Date.class.getCanonicalName())) {
continue;
}
dataModelClasses.add(index.getClassByName(pd.type().name()));
}
generateModelClassProto(modelClazz, targetDirectory);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return dataModelClasses;
}
static Set<Type> getProducerFieldTypeClosure(FieldInfo producerField, BeanDeployment beanDeployment) {
Set<Type> types;
Type fieldType = producerField.type();
if (fieldType.kind() == Kind.PRIMITIVE || fieldType.kind() == Kind.ARRAY) {
types = new HashSet<>();
types.add(fieldType);
types.add(OBJECT_TYPE);
} else {
ClassInfo fieldClassInfo = getClassByName(beanDeployment.getIndex(), producerField.type());
if (fieldClassInfo == null) {
throw new IllegalArgumentException("Producer field type not found in index: " + producerField.type().name());
}
if (Kind.CLASS.equals(fieldType.kind())) {
types = getTypeClosure(fieldClassInfo, producerField, Collections.emptyMap(), beanDeployment, null);
} else if (Kind.PARAMETERIZED_TYPE.equals(fieldType.kind())) {
types = getTypeClosure(fieldClassInfo, producerField,
buildResolvedMap(fieldType.asParameterizedType().arguments(), fieldClassInfo.typeParameters(),
Collections.emptyMap(), beanDeployment.getIndex()),
beanDeployment, null);
} else {
throw new IllegalArgumentException("Unsupported return type");
}
}
return restrictBeanTypes(types, beanDeployment.getAnnotations(producerField));
}
/**
* Get a single scope from the available options or throw a {@link DefinitionException} explaining
* where the annotations conflict.
*
* @param clazz The class annotated with the scopes
* @param scopes The scopes from the class and its stereotypes
* @param scopeStereotypes The stereotype annotations that declared the conflicting scopes
* @return The scope for the target class
*/
private DotName validateScope(final ClassInfo clazz, final Set<DotName> scopes, final Set<DotName> scopeStereotypes) {
final int size = scopes.size();
switch (size) {
case 0:
// Spring default
return CDI_SINGLETON_ANNOTATION;
case 1:
return scopes.iterator().next();
default:
throw new DefinitionException(
"Components annotated with multiple conflicting scopes must declare an explicit @Scope. "
+ clazz.name() + " declares scopes: "
+ scopes.stream().map(DotName::toString).collect(Collectors.joining(", "))
+ " through the stereotypes: "
+ scopeStereotypes.stream().map(DotName::toString)
.collect(Collectors.joining(", ")));
}
}
/**
* Find and process all Spring Controllers
* TODO: Also support org.springframework.stereotype.Controller annotations ?
*
* @param context the scanning context
* @param openApi the openAPI model
*/
private void processControllerClasses(final AnnotationScannerContext context, OpenAPI openApi) {
// Get all Spring controllers and convert them to OpenAPI models (and merge them into a single one)
Collection<AnnotationInstance> controllerAnnotations = context.getIndex()
.getAnnotations(SpringConstants.REST_CONTROLLER);
List<ClassInfo> applications = new ArrayList<>();
for (AnnotationInstance annotationInstance : controllerAnnotations) {
if (annotationInstance.target().kind().equals(AnnotationTarget.Kind.CLASS)) {
ClassInfo classInfo = annotationInstance.target().asClass();
applications.add(classInfo);
} else {
SpringLogging.log.ignoringAnnotation(SpringConstants.REST_CONTROLLER.withoutPackagePrefix());
}
}
// this can be a useful extension point to set/override the application path
processScannerExtensions(context, applications);
for (ClassInfo controller : applications) {
OpenAPI applicationOpenApi = processControllerClass(context, controller);
openApi = MergeUtil.merge(openApi, applicationOpenApi);
}
}
protected void createConstructor(ClassOutput classOutput, ClassCreator creator, InterceptorInfo interceptor,
String baseName,
Map<InjectionPointInfo, String> injectionPointToProviderField,
Map<InterceptorInfo, String> interceptorToProviderField, FieldDescriptor bindings,
ReflectionRegistration reflectionRegistration) {
MethodCreator constructor = initConstructor(classOutput, creator, interceptor, baseName, injectionPointToProviderField,
interceptorToProviderField, annotationLiterals, reflectionRegistration);
// Bindings
// bindings = new HashSet<>()
ResultHandle bindingsHandle = constructor.newInstance(MethodDescriptor.ofConstructor(HashSet.class));
for (AnnotationInstance bindingAnnotation : interceptor.getBindings()) {
// Create annotation literal first
ClassInfo bindingClass = interceptor.getDeployment().getInterceptorBinding(bindingAnnotation.name());
constructor.invokeInterfaceMethod(MethodDescriptors.SET_ADD, bindingsHandle,
annotationLiterals.process(constructor, classOutput, bindingClass, bindingAnnotation,
Types.getPackageName(creator.getClassName())));
}
constructor.writeInstanceField(bindings, constructor.getThis(), bindingsHandle);
constructor.returnValue(null);
}
/**
* Collect the beans with our custom bean defining annotation and configure them with the runtime config
*
* @param recorder - runtime recorder
* @param beanArchiveIndex - index of type information
* @param testBeanProducer - producer for located Class<IConfigConsumer> bean types
*/
@BuildStep
@Record(STATIC_INIT)
void scanForBeans(TestRecorder recorder, BeanArchiveIndexBuildItem beanArchiveIndex,
BuildProducer<TestBeanBuildItem> testBeanProducer) {
IndexView indexView = beanArchiveIndex.getIndex();
Collection<AnnotationInstance> testBeans = indexView.getAnnotations(TEST_ANNOTATION);
for (AnnotationInstance ann : testBeans) {
ClassInfo beanClassInfo = ann.target().asClass();
try {
boolean isConfigConsumer = beanClassInfo.interfaceNames()
.stream()
.anyMatch(dotName -> dotName.equals(DotName.createSimple(IConfigConsumer.class.getName())));
if (isConfigConsumer) {
Class<IConfigConsumer> beanClass = (Class<IConfigConsumer>) Class.forName(beanClassInfo.name().toString(),
true, Thread.currentThread().getContextClassLoader());
testBeanProducer.produce(new TestBeanBuildItem(beanClass));
log.infof("The configured bean: %s", beanClass);
}
} catch (ClassNotFoundException e) {
log.warn("Failed to load bean class", e);
}
}
}
/**
*
* @param i
* @param methodReference
* @param ci
* @return whether any superclass implements the method
*/
public static boolean implementsMethodRecursive ( Index i, MethodReference methodReference, ClassInfo ci ) {
if ( implementsMethod(methodReference, ci) ) {
return true;
}
DotName superName = ci.superName();
if ( superName != null ) {
ClassInfo superByName = i.getClassByName(superName);
if ( superByName == null || "java.lang.Object".equals(superByName.name().toString()) ) { //$NON-NLS-1$
return false;
}
return implementsMethodRecursive(i, methodReference, superByName);
}
return false;
}
private List<ClassInfo> getMappedSuperClassInfos(IndexView indexView, ClassInfo entityClass) {
List<ClassInfo> mappedSuperClassInfos = new ArrayList<>(3);
Type superClassType = entityClass.superClassType();
while (superClassType != null && !superClassType.name().equals(DotNames.OBJECT)) {
ClassInfo superClass = indexView.getClassByName(entityClass.superName());
if (superClass.classAnnotation(DotNames.JPA_MAPPED_SUPERCLASS) != null) {
mappedSuperClassInfos.add(superClass);
}
if (superClassType.kind() == Kind.CLASS) {
superClassType = indexView.getClassByName(superClassType.name()).superClassType();
} else if (superClassType.kind() == Kind.PARAMETERIZED_TYPE) {
ParameterizedType parameterizedType = superClassType.asParameterizedType();
superClassType = parameterizedType.owner();
}
}
if (mappedSuperClassInfos.size() > 0) {
return mappedSuperClassInfos;
}
return Collections.emptyList();
}
@Override
public boolean test(ClassInfo classInfo) {
int ctorCount = 0;
boolean hasCopyMethod = false;
boolean hasStaticCopyMethod = false;
boolean hasComponent1Method = false;
List<MethodInfo> methods = classInfo.methods();
for (MethodInfo method : methods) {
String methodName = method.name();
if ("<init>".equals(methodName)) {
ctorCount++;
} else if ("component1".equals(methodName) && Modifier.isFinal(method.flags())) {
hasComponent1Method = true;
} else if ("copy".equals(methodName) && Modifier.isFinal(method.flags())) {
hasCopyMethod = true;
} else if ("copy$default".equals(methodName) && Modifier.isStatic(method.flags())) {
hasStaticCopyMethod = true;
}
}
return ctorCount > 1 && hasComponent1Method && hasCopyMethod && hasStaticCopyMethod;
}
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void buildReplacementMap(List<PropertyMappingClassBuildStep> propertyMappingClasses, CombinedIndexBuildItem index,
PanacheMongoRecorder recorder) {
Map<String, Map<String, String>> replacementMap = new ConcurrentHashMap<>();
for (PropertyMappingClassBuildStep classToMap : propertyMappingClasses) {
DotName dotName = DotName.createSimple(classToMap.getClassName());
ClassInfo classInfo = index.getIndex().getClassByName(dotName);
if (classInfo != null) {
// only compute field replacement for types inside the index
Map<String, String> classReplacementMap = replacementMap.computeIfAbsent(classToMap.getClassName(),
className -> computeReplacement(classInfo));
if (classToMap.getAliasClassName() != null) {
// also register the replacement map for the projection classes
replacementMap.put(classToMap.getAliasClassName(), classReplacementMap);
}
}
}
recorder.setReplacementCache(replacementMap);
}
private static void contributeClass(Set<DotName> classNamesCollector, IndexView indexView, DotName className) {
classNamesCollector.add(className);
for (ClassInfo subclass : indexView.getAllKnownSubclasses(className)) {
if (Modifier.isAbstract(subclass.flags())) {
// we can avoid adding the abstract classes here: either they are parent classes
// and they will be dealt with by Hibernate Validator or they are child classes
// without any proper implementation and we can ignore them.
continue;
}
classNamesCollector.add(subclass.name());
}
for (ClassInfo implementor : indexView.getAllKnownImplementors(className)) {
if (Modifier.isAbstract(implementor.flags())) {
// we can avoid adding the abstract classes here: either they are parent classes
// and they will be dealt with by Hibernate Validator or they are child classes
// without any proper implementation and we can ignore them.
continue;
}
classNamesCollector.add(implementor.name());
}
}
private boolean hasAutoInjectAnnotation(Set<DotName> autoInjectAnnotationNames, ClassInfo clazz) {
for (DotName name : autoInjectAnnotationNames) {
List<AnnotationInstance> instances = clazz.annotations().get(name);
if (instances != null) {
for (AnnotationInstance instance : instances) {
if (instance.target().kind() == Kind.FIELD) {
return true;
}
}
}
}
return false;
}
private void getAllKnownSubClasses(DotName name, Set<ClassInfo> allKnown, Set<DotName> subClassesToProcess,
Set<DotName> processedClasses) {
for (Index index : indexes) {
final List<ClassInfo> list = index.getKnownDirectSubclasses(name);
if (list != null) {
for (final ClassInfo clazz : list) {
final DotName className = clazz.name();
if (!processedClasses.contains(className)) {
allKnown.add(clazz);
subClassesToProcess.add(className);
}
}
}
}
}
/**
* Get used when we create types and references to them
*
* Class level annotation for type creation.
*
* @param classInfo the java class
* @return annotation for this class
*/
public static Annotations getAnnotationsForClass(ClassInfo classInfo) {
Map<DotName, AnnotationInstance> annotationMap = new HashMap<>();
for (AnnotationInstance annotationInstance : classInfo.classAnnotations()) {
DotName name = annotationInstance.name();
annotationMap.put(name, annotationInstance);
}
return new Annotations(annotationMap);
}
static ResultHandle collectInjectionPointAnnotations(ClassOutput classOutput, ClassCreator beanCreator,
BeanDeployment beanDeployment, MethodCreator constructor, InjectionPointInfo injectionPoint,
AnnotationLiteralProcessor annotationLiterals, Predicate<DotName> injectionPointAnnotationsPredicate) {
ResultHandle annotationsHandle = constructor.newInstance(MethodDescriptor.ofConstructor(HashSet.class));
Collection<AnnotationInstance> annotations;
if (Kind.FIELD.equals(injectionPoint.getTarget().kind())) {
FieldInfo field = injectionPoint.getTarget().asField();
annotations = beanDeployment.getAnnotations(field);
} else {
MethodInfo method = injectionPoint.getTarget().asMethod();
annotations = Annotations.getParameterAnnotations(beanDeployment,
method, injectionPoint.getPosition());
}
for (AnnotationInstance annotation : annotations) {
if (!injectionPointAnnotationsPredicate.test(annotation.name())) {
continue;
}
ResultHandle annotationHandle;
if (DotNames.INJECT.equals(annotation.name())) {
annotationHandle = constructor
.readStaticField(FieldDescriptor.of(InjectLiteral.class, "INSTANCE", InjectLiteral.class));
} else {
// Create annotation literal if needed
ClassInfo literalClass = getClassByName(beanDeployment.getIndex(), annotation.name());
annotationHandle = annotationLiterals.process(constructor,
classOutput, literalClass, annotation,
Types.getPackageName(beanCreator.getClassName()));
}
constructor.invokeInterfaceMethod(MethodDescriptors.SET_ADD, annotationsHandle,
annotationHandle);
}
return annotationsHandle;
}
private HibernateOrmRestDataResourceInfo(ClassInfo classInfo, String idClassName, String entityClassName,
DataAccessImplementor dataAccessImplementor) {
this.classInfo = classInfo;
this.idClassName = idClassName;
this.entityClassName = entityClassName;
this.dataAccessImplementor = dataAccessImplementor;
}
public KotlinPanacheEntityClassVisitor(String className, ClassVisitor outputClassVisitor,
MetamodelInfo<EntityModel<EntityField>> modelInfo,
ClassInfo panacheEntityBaseClassInfo,
ClassInfo entityInfo,
List<PanacheMethodCustomizer> methodCustomizers) {
super(className, outputClassVisitor, modelInfo, panacheEntityBaseClassInfo, entityInfo, methodCustomizers);
}
private void addInterfaces(Type type, ClassInfo classInfo) {
List<DotName> interfaceNames = classInfo.interfaceNames();
for (DotName interfaceName : interfaceNames) {
// Ignore java interfaces (like Serializable)
if (!interfaceName.toString().startsWith(JAVA_DOT)) {
ClassInfo interfaceInfo = ScanningContext.getIndex().getClassByName(interfaceName);
if (interfaceInfo != null) {
Reference interfaceRef = referenceCreator.createReference(Direction.OUT, interfaceInfo);
type.addInterface(interfaceRef);
}
}
}
}
private boolean isExcluded(ClassInfo beanClass) {
if (!excludeTypes.isEmpty()) {
for (Predicate<ClassInfo> exclude : excludeTypes) {
if (exclude.test(beanClass)) {
return true;
}
}
}
return false;
}
@Test
public void testFormattedLocalDate() throws Exception {
Index complete = IndexCreator.index(AsyncApi.class);
ClassInfo classByName = complete.getClassByName(DotName.createSimple(AsyncApi.class.getName()));
MethodInfo nonNullString = classByName.method("formattedLocalDate");
Type type = nonNullString.returnType();
Annotations annotations = Annotations.getAnnotationsForMethod(nonNullString);
Optional<TransformInfo> format = FormatHelper.getFormat(type, annotations);
TransformInfo transformInfo = format.get();
assertEquals("yyyy-MM-dd", transformInfo.getFormat());
}
@Test
public void testNonNullString() throws Exception {
Index complete = IndexCreator.index(AsyncApi.class);
ClassInfo classByName = complete.getClassByName(DotName.createSimple(AsyncApi.class.getName()));
MethodInfo nonNullString = classByName.method("nonNullString");
Type type = nonNullString.returnType();
Annotations annotationsForMethod = Annotations.getAnnotationsForMethod(nonNullString);
assertTrue(NonNullHelper.markAsNonNull(type, annotationsForMethod));
}
private void addJavaMigrations(Collection<ClassInfo> candidates, RecorderContext context,
BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer, Set<Class<?>> javaMigrationClasses) {
for (ClassInfo javaMigration : candidates) {
if (Modifier.isAbstract(javaMigration.flags())) {
continue;
}
javaMigrationClasses.add(context.classProxy(javaMigration.name().toString()));
reflectiveClassProducer.produce(new ReflectiveClassBuildItem(false, false, javaMigration.name().toString()));
}
}