下面列出了java.lang.annotation.Inherited#org.jboss.jandex.DotName 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testCreate() throws IOException {
DotName nested = DotNames.create(Nested.class);
assertTrue(nested.isComponentized());
assertEquals("io.quarkus.arc.processor.DotNamesTest$Nested", nested.toString());
assertEquals("DotNamesTest$Nested", nested.local());
assertEquals("DotNamesTest$Nested", nested.withoutPackagePrefix());
assertFalse(nested.isInner());
DotName nestedNested = DotNames.create(NestedNested.class);
assertTrue(nestedNested.isComponentized());
assertEquals("io.quarkus.arc.processor.DotNamesTest$Nested$NestedNested", nestedNested.toString());
assertEquals("DotNamesTest$Nested$NestedNested", nestedNested.local());
assertEquals("DotNamesTest$Nested$NestedNested", nestedNested.withoutPackagePrefix());
assertFalse(nestedNested.isInner());
}
@BuildStep
void picocliRunner(ApplicationIndexBuildItem applicationIndex,
CombinedIndexBuildItem combinedIndex,
BuildProducer<AdditionalBeanBuildItem> additionalBean,
BuildProducer<QuarkusApplicationClassBuildItem> quarkusApplicationClass,
BuildProducer<AnnotationsTransformerBuildItem> annotationsTransformer) {
IndexView index = combinedIndex.getIndex();
Collection<DotName> topCommands = classesAnnotatedWith(index, TopCommand.class.getName());
if (topCommands.isEmpty()) {
List<DotName> commands = classesAnnotatedWith(applicationIndex.getIndex(),
CommandLine.Command.class.getName());
if (commands.size() == 1) {
annotationsTransformer.produce(createAnnotationTransformer(commands.get(0)));
}
}
if (index.getAnnotations(DotName.createSimple(QuarkusMain.class.getName())).isEmpty()) {
additionalBean.produce(AdditionalBeanBuildItem.unremovableOf(PicocliRunner.class));
additionalBean.produce(AdditionalBeanBuildItem.unremovableOf(DefaultPicocliCommandLineFactory.class));
quarkusApplicationClass.produce(new QuarkusApplicationClassBuildItem(PicocliRunner.class));
}
}
private static int compareAnnotation(AnnotationTarget t1, AnnotationTarget t2, DotName annotationName) {
boolean hasAnno1 = TypeUtil.hasAnnotation(t1, annotationName);
boolean hasAnno2 = TypeUtil.hasAnnotation(t2, annotationName);
// Element with @Schema is top priority
if (hasAnno1) {
if (!hasAnno2) {
return -1;
}
} else {
if (hasAnno2) {
return 1;
}
}
return 0;
}
private void scanAsyncResponseProvidersFromClassName(Class<?> asyncResponseProviderClass, String name) {
try {
Class<?> klass = Class.forName(name);
if (asyncResponseProviderClass.isAssignableFrom(klass)) {
for (java.lang.reflect.Type type : klass.getGenericInterfaces()) {
if (type instanceof java.lang.reflect.ParameterizedType) {
java.lang.reflect.ParameterizedType pType = (java.lang.reflect.ParameterizedType) type;
if (pType.getRawType().equals(asyncResponseProviderClass)
&& pType.getActualTypeArguments().length == 1) {
java.lang.reflect.Type asyncType = pType.getActualTypeArguments()[0];
String asyncTypeName;
if (asyncType instanceof java.lang.reflect.ParameterizedType)
asyncTypeName = ((java.lang.reflect.ParameterizedType) asyncType).getRawType().getTypeName();
else
asyncTypeName = asyncType.getTypeName();
asyncTypes.add(DotName.createSimple(asyncTypeName));
}
}
}
}
} catch (ClassNotFoundException x) {
// ignore it
}
}
static ClassInfo getClassInfoFromBeanName(String beanName, IndexView index, Map<String, DotName> springBeansNameToDotName,
Map<String, ClassInfo> springBeansNameToClassInfo,
String expression, MethodInfo methodInfo) {
ClassInfo beanClassInfo = springBeansNameToClassInfo.get(beanName);
if (beanClassInfo == null) {
DotName beanClassDotName = springBeansNameToDotName.get(beanName);
if (beanClassDotName == null) {
throw new IllegalArgumentException("Could not find bean named '" + beanName
+ "' found in expression" + expression + "' in the @PreAuthorize annotation on method "
+ methodInfo.name() + " of class " + methodInfo.declaringClass()
+ " in the set of the application beans");
}
beanClassInfo = index.getClassByName(beanClassDotName);
if (beanClassInfo == null) {
throw new IllegalStateException("Unable to locate class " + beanClassDotName + " in the index");
}
springBeansNameToClassInfo.put(beanName, beanClassInfo);
}
return beanClassInfo;
}
private AnnotationTarget getIdAnnotationTargetRec(DotName currentDotName, IndexView index, DotName originalEntityDotName) {
ClassInfo classInfo = index.getClassByName(currentDotName);
if (classInfo == null) {
throw new IllegalStateException("Entity " + originalEntityDotName + " was not part of the Quarkus index");
}
if (!classInfo.annotations().containsKey(DotNames.JPA_ID)) {
if (DotNames.OBJECT.equals(classInfo.superName())) {
throw new IllegalArgumentException("Currently only Entities with the @Id annotation are supported. " +
"Offending class is " + originalEntityDotName);
}
return getIdAnnotationTargetRec(classInfo.superName(), index, originalEntityDotName);
}
List<AnnotationInstance> annotationInstances = classInfo.annotations().get(DotNames.JPA_ID);
if (annotationInstances.size() > 1) {
throw new IllegalArgumentException(
"Currently the @Id annotation can only be placed on a single field or method. " +
"Offending class is " + originalEntityDotName);
}
return annotationInstances.get(0).target();
}
private static void addReflectiveType(IndexView index, Set<DotName> reflectiveClassCollector,
Set<Type> reflectiveTypeCollector, Type type) {
if (type instanceof VoidType || type instanceof PrimitiveType || type instanceof UnresolvedTypeVariable) {
return;
} else if (type instanceof ClassType) {
ClassInfo classInfo = index.getClassByName(type.name());
addReflectiveClass(index, reflectiveClassCollector, reflectiveTypeCollector, classInfo);
} else if (type instanceof ArrayType) {
addReflectiveType(index, reflectiveClassCollector, reflectiveTypeCollector, type.asArrayType().component());
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = type.asParameterizedType();
addReflectiveType(index, reflectiveClassCollector, reflectiveTypeCollector, parameterizedType.owner());
for (Type typeArgument : parameterizedType.arguments()) {
addReflectiveType(index, reflectiveClassCollector, reflectiveTypeCollector, typeArgument);
}
}
}
private void validateRouteMethod(BeanInfo bean, MethodInfo method, DotName[] validParamTypes) {
if (!method.returnType().kind().equals(Type.Kind.VOID)) {
throw new IllegalStateException(
String.format("Route handler business method must return void [method: %s, bean: %s]", method, bean));
}
List<Type> params = method.parameters();
boolean hasInvalidParam = true;
if (params.size() == 1) {
DotName paramTypeName = params.get(0).name();
for (DotName type : validParamTypes) {
if (type.equals(paramTypeName)) {
hasInvalidParam = false;
}
}
}
if (hasInvalidParam) {
throw new IllegalStateException(String.format(
"Route business method must accept exactly one parameter of type %s: %s [method: %s, bean: %s]",
validParamTypes, params, method, bean));
}
}
/**
* Add a method like this:
*
* <pre>
* @Produces
* public SomeConfig produceSomeClass(Config config) {
* return new SomeConfigQuarkusImpl(config)
* }
* </pre>
*/
static void addProducerMethodForInterfaceConfigProperties(ClassCreator classCreator, DotName interfaceName,
String prefix, boolean needsQualifier, String generatedClassName) {
String methodName = "produce" + interfaceName.withoutPackagePrefix();
if (needsQualifier) {
// we need to differentiate the different producers of the same class
methodName = methodName + "WithPrefix" + HashUtil.sha1(prefix);
}
try (MethodCreator method = classCreator.getMethodCreator(methodName, interfaceName.toString(),
Config.class.getName())) {
method.addAnnotation(Produces.class);
if (needsQualifier) {
method.addAnnotation(AnnotationInstance.create(DotNames.CONFIG_PREFIX, null,
new AnnotationValue[] { AnnotationValue.createStringValue("value", prefix) }));
} else {
method.addAnnotation(Default.class);
}
method.returnValue(method.newInstance(MethodDescriptor.ofConstructor(generatedClassName, Config.class),
method.getMethodParam(0)));
}
}
/**
* Obtains the MetricType from a bean that is a producer method or field,
* or null if no MetricType can be detected.
*/
private MetricType getMetricType(ClassInfo clazz) {
DotName name = clazz.name();
if (name.equals(GAUGE_INTERFACE)) {
return MetricType.GAUGE;
}
if (name.equals(COUNTER_INTERFACE)) {
return MetricType.COUNTER;
}
if (name.equals(CONCURRENT_GAUGE_INTERFACE)) {
return MetricType.CONCURRENT_GAUGE;
}
if (name.equals(HISTOGRAM_INTERFACE)) {
return MetricType.HISTOGRAM;
}
if (name.equals(SIMPLE_TIMER_INTERFACE)) {
return MetricType.SIMPLE_TIMER;
}
if (name.equals(TIMER_INTERFACE)) {
return MetricType.TIMER;
}
if (name.equals(METER_INTERFACE)) {
return MetricType.METERED;
}
return null;
}
private static void scanMethodParameters(DotName annotationType,
BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy, IndexView index) {
Collection<AnnotationInstance> instances = index.getAnnotations(annotationType);
for (AnnotationInstance instance : instances) {
if (instance.target().kind() != Kind.METHOD) {
continue;
}
MethodInfo method = instance.target().asMethod();
String source = method.declaringClass() + "[" + method + "]";
reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(method.returnType(), index,
ResteasyDotNames.IGNORE_FOR_REFLECTION_PREDICATE, source));
for (short i = 0; i < method.parameters().size(); i++) {
Type parameterType = method.parameters().get(i);
if (!hasAnnotation(method, i, ResteasyDotNames.CONTEXT)) {
reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(parameterType, index,
ResteasyDotNames.IGNORE_FOR_REFLECTION_PREDICATE, source));
}
}
}
}
static Consumer<BuildChainBuilder> buildCustomizer() {
return new Consumer<BuildChainBuilder>() {
@Override
public void accept(BuildChainBuilder builder) {
builder.addBuildStep(new BuildStep() {
@Override
public void execute(BuildContext context) {
context.produce(new BeanDefiningAnnotationBuildItem(DotName.createSimple(MakeItBean.class.getName()),
DotName.createSimple(ApplicationScoped.class.getName())));
}
}).produces(BeanDefiningAnnotationBuildItem.class).build();
}
};
}
static Optional<String[]> getMediaTypes(MethodInfo resourceMethod, DotName annotationName) {
AnnotationInstance annotation = resourceMethod.annotation(annotationName);
if (annotation == null) {
annotation = JandexUtil.getClassAnnotation(resourceMethod.declaringClass(), annotationName);
}
if (annotation != null) {
AnnotationValue annotationValue = annotation.value();
if (annotationValue != null) {
return Optional.of(annotationValue.asStringArray());
}
return Optional.of(OpenApiConstants.DEFAULT_MEDIA_TYPES.get());
}
return Optional.empty();
}
/**
* Read a single annotation that is either {@link @Parameter} or
* {@link @Parameters}. The results are stored in the private {@link #params}
* collection.
*
* @param annotation a parameter annotation to be read and processed
*/
void readParameterAnnotation(AnnotationInstance annotation) {
DotName name = annotation.name();
if (ParameterConstant.DOTNAME_PARAMETER.equals(name)) {
readAnnotatedType(annotation, null, false);
} else if (ParameterConstant.DOTNAME_PARAMETERS.equals(name)) {
AnnotationValue annotationValue = annotation.value();
if (annotationValue != null) {
/*
* Unwrap annotations wrapped by @Parameters and
* identify the target as the target of the @Parameters annotation
*/
for (AnnotationInstance nested : annotationValue.asNestedArray()) {
readAnnotatedType(AnnotationInstance.create(nested.name(),
annotation.target(),
nested.values()),
null,
false);
}
}
}
}
private boolean hasFTAnnotations(IndexView index, AnnotationStore annotationStore, ClassInfo info) {
if (info == null) {
//should not happen, but guard against it
//happens in this case due to a bug involving array types
return false;
}
// first check annotations on type
if (annotationStore.hasAnyAnnotation(info, FT_ANNOTATIONS)) {
return true;
}
// then check on the methods
for (MethodInfo method : info.methods()) {
if (annotationStore.hasAnyAnnotation(method, FT_ANNOTATIONS)) {
return true;
}
}
// then check on the parent
DotName parentClassName = info.superName();
if (parentClassName == null || parentClassName.equals(DotNames.OBJECT)) {
return false;
}
ClassInfo parentClassInfo = index.getClassByName(parentClassName);
if (parentClassInfo == null) {
return false;
}
return hasFTAnnotations(index, annotationStore, parentClassInfo);
}
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;
}
public PanacheRepositoryClassVisitor(String className, ClassVisitor outputClassVisitor,
ClassInfo panacheRepositoryBaseClassInfo, IndexView indexView) {
super(Gizmo.ASM_API_VERSION, outputClassVisitor);
daoClassInfo = indexView.getClassByName(DotName.createSimple(className));
daoBinaryName = className.replace('.', '/');
this.panacheRepositoryBaseClassInfo = panacheRepositoryBaseClassInfo;
this.indexView = indexView;
}
@Test
public void testAccepts_ExcludedPackageOverridesIncludedPackage() {
Map<String, Object> properties = new HashMap<>();
properties.put(OASConfig.SCAN_PACKAGES, "com.example");
properties.put(OASConfig.SCAN_EXCLUDE_PACKAGES, "com.example");
OpenApiConfig config = IndexScannerTestBase.dynamicConfig(properties);
FilteredIndexView view = new FilteredIndexView(null, config);
assertFalse(view.accepts(DotName.createSimple("com.example.TopLevelClass")));
assertFalse(view.accepts(DotName.createSimple("com.example.pkgA.MyBean")));
assertFalse(view.accepts(DotName.createSimple("com.example.pkgA.MyClass")));
assertFalse(view.accepts(DotName.createSimple("com.example.pkgA.MyImpl")));
}
static Type determineSingleGenericType(Type type, DotName declaringClass) {
if (!(type.kind() == Type.Kind.PARAMETERIZED_TYPE)) {
throw new IllegalArgumentException("Type " + type.name().toString() + " which is used in class " + declaringClass
+ " must define a generic argument");
}
ParameterizedType parameterizedType = type.asParameterizedType();
if (parameterizedType.arguments().size() != 1) {
throw new IllegalArgumentException("Type " + type.name().toString() + " which is used in class " + declaringClass
+ " must define a single generic argument");
}
return type.asParameterizedType().arguments().get(0);
}
private static ScopeInfo getScope(DotName scopeAnnotationName,
Map<ScopeInfo, Function<MethodCreator, ResultHandle>> customContexts) {
BuiltinScope builtin = BuiltinScope.from(scopeAnnotationName);
if (builtin != null) {
return builtin.getInfo();
}
for (ScopeInfo customScope : customContexts.keySet()) {
if (customScope.getDotName().equals(scopeAnnotationName)) {
return customScope;
}
}
return null;
}
@Test
public void testIsA_IndexedSubjectUnrelatedToObject() {
final Class<?> subjectClass = UnrelatedType.class;
Index index = indexOf(subjectClass);
Type testSubject = Type.create(DotName.createSimple(subjectClass.getName()), Type.Kind.CLASS);
boolean result = TypeUtil.isA(index, testSubject, TYPE_COLLECTION);
assertFalse(result);
}
private boolean hasSpringSecurityAnnotationOtherThan(MethodInfo methodInfo, DotName excluded) {
Set<DotName> toCheck = new HashSet<>(DotNames.SUPPORTED_SPRING_SECURITY_ANNOTATIONS);
toCheck.remove(excluded);
List<AnnotationInstance> annotations = methodInfo.annotations();
for (AnnotationInstance instance : annotations) {
if (toCheck.contains(instance.name())) {
return true;
}
}
return false;
}
static String packageName(DotName dotName) {
String name = dotName.toString();
int index = name.lastIndexOf('.');
if (index == -1) {
return "";
}
return name.substring(0, index);
}
/**
* Unresolvable type parameter.
*/
@Test
public void testUnresolvable() throws IOException, JSONException {
DotName bar = createSimple(Bar.class.getName());
OpenApiDataObjectScanner scanner = new OpenApiDataObjectScanner(index, ClassType.create(bar, Type.Kind.CLASS));
Schema result = scanner.process();
printToConsole(bar.local(), result);
assertJsonEquals(bar.local(), "unresolvable.expected.json", result);
}
public static String packageName(DotName dotName) {
String name = dotName.toString();
int index = name.lastIndexOf('.');
if (index == -1) {
return "";
}
return name.substring(0, index);
}
@Test
public void getAnnotationsToAdd() {
final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
final ClassInfo target = index.getClassByName(DotName.createSimple(RequestBean.class.getName()));
final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);
final Set<AnnotationInstance> expected = setOf(
AnnotationInstance.create(DotName.createSimple(RequestScoped.class.getName()), target,
Collections.emptyList()));
assertEquals(expected, ret);
}
@Test
public void testBuildCronParam() {
final MethodInfo target = index.getClassByName(DotName.createSimple(SpringScheduledMethodsBean.class.getName()))
.method("checkEverySecondCron");
AnnotationInstance annotation = target.annotation(SpringScheduledProcessor.SPRING_SCHEDULED);
AnnotationValue annotationValue = springScheduledProcessor.buildCronParam(annotation.values());
assertThat(annotationValue.name()).isEqualTo("cron");
assertThat(annotationValue.value()).isEqualTo("0/1 * * * * ?");
}
@BuildStep
public AdditionalJaxRsResourceMethodParamAnnotations additionalJaxRsResourceMethodParamAnnotations() {
return new AdditionalJaxRsResourceMethodParamAnnotations(
Arrays.asList(DotName.createSimple("org.springframework.web.bind.annotation.RequestParam"),
PATH_VARIABLE,
DotName.createSimple("org.springframework.web.bind.annotation.RequestBody"),
DotName.createSimple("org.springframework.web.bind.annotation.MatrixVariable"),
DotName.createSimple("org.springframework.web.bind.annotation.RequestHeader"),
DotName.createSimple("org.springframework.web.bind.annotation.CookieValue")));
}
@BuildStep
NativeImageProxyDefinitionBuildItem stmProxies() {
final DotName TRANSACTIONAL = DotName.createSimple(Transactional.class.getName());
IndexView index = combinedIndexBuildItem.getIndex();
Collection<String> proxies = new ArrayList<>();
for (AnnotationInstance stm : index.getAnnotations(TRANSACTIONAL)) {
if (AnnotationTarget.Kind.CLASS.equals(stm.target().kind())) {
DotName name = stm.target().asClass().name();
proxies.add(name.toString());
log.debugf("Registering transactional interface %s%n", name);
for (ClassInfo ci : index.getAllKnownImplementors(name)) {
reflectiveHierarchyClass.produce(
new ReflectiveHierarchyBuildItem(Type.create(ci.name(), Type.Kind.CLASS)));
}
}
}
String[] classNames = proxies.toArray(new String[0]);
reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, classNames));
return new NativeImageProxyDefinitionBuildItem(classNames);
}
private static void enlistExplicitClasses(IndexView index, JpaEntitiesBuildItem domainObjectCollector,
Set<String> enumTypeCollector, Set<String> javaTypeCollector, List<String> managedClassNames,
Set<DotName> unindexedClasses) {
for (String className : managedClassNames) {
DotName dotName = DotName.createSimple(className);
boolean isInIndex = index.getClassByName(dotName) != null;
if (!isInIndex) {
unindexedClasses.add(dotName);
}
addClassHierarchyToReflectiveList(index, domainObjectCollector, enumTypeCollector, javaTypeCollector, dotName,
unindexedClasses);
}
}