下面列出了javax.validation.Constraint#org.jboss.jandex.AnnotationInstance 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public AnnotationInstance build() {
AnnotationValue ignoreValue;
if (ignores.isEmpty()) {
ignoreValue = AnnotationValue.createArrayValue(ValueResolverGenerator.IGNORE, new AnnotationValue[] {});
} else {
AnnotationValue[] values = new AnnotationValue[ignores.size()];
for (int i = 0; i < ignores.size(); i++) {
values[i] = AnnotationValue.createStringValue(ValueResolverGenerator.IGNORE + i, ignores.get(i));
}
ignoreValue = AnnotationValue.createArrayValue(ValueResolverGenerator.IGNORE, values);
}
AnnotationValue propertiesValue = AnnotationValue.createBooleanValue(ValueResolverGenerator.PROPERTIES, properties);
AnnotationValue ignoreSuperclassesValue = AnnotationValue.createBooleanValue(ValueResolverGenerator.IGNORE_SUPERCLASSES,
ignoreSuperclasses);
return AnnotationInstance.create(ValueResolverGenerator.TEMPLATE_DATA, null,
new AnnotationValue[] { ignoreValue, propertiesValue, ignoreSuperclassesValue });
}
/**
* Annotation to Info
*
* @param annotationValue the {@literal @}Info annotation
* @return Info model
*/
public static Info readInfo(final AnnotationValue annotationValue) {
if (annotationValue == null) {
return null;
}
IoLogging.log.annotation("@Info");
AnnotationInstance nested = annotationValue.asNested();
Info info = new InfoImpl();
info.setTitle(JandexUtil.stringValue(nested, InfoConstant.PROP_TITLE));
info.setDescription(JandexUtil.stringValue(nested, InfoConstant.PROP_DESCRIPTION));
info.setTermsOfService(JandexUtil.stringValue(nested, InfoConstant.PROP_TERMS_OF_SERVICE));
info.setContact(ContactReader.readContact(nested.value(InfoConstant.PROP_CONTACT)));
info.setLicense(LicenseReader.readLicense(nested.value(InfoConstant.PROP_LICENSE)));
info.setVersion(JandexUtil.stringValue(nested, InfoConstant.PROP_VERSION));
return info;
}
/**
* 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);
}
}
/**
* Reads a single Content annotation into a {@link MediaType} model.
*
* @param context the scanning context
* @param annotationInstance {@literal @}Content annotation
* @return MediaType model
*/
public static MediaType readMediaType(final AnnotationScannerContext context,
final AnnotationInstance annotationInstance) {
if (annotationInstance == null) {
return null;
}
IoLogging.log.singleAnnotationAs("@Content", "MediaType");
MediaType mediaType = new MediaTypeImpl();
mediaType.setExamples(ExampleReader.readExamples(annotationInstance.value(MediaTypeConstant.PROP_EXAMPLES)));
mediaType.setExample(JandexUtil.stringValue(annotationInstance, MediaTypeConstant.PROP_EXAMPLE));
mediaType.setSchema(SchemaFactory.readSchema(context.getIndex(),
annotationInstance.value(MediaTypeConstant.PROP_SCHEMA)));
mediaType.setEncoding(
EncodingReader.readEncodings(context, annotationInstance.value(MediaTypeConstant.PROP_ENCODING)));
return mediaType;
}
/**
* Reads a string property named "ref" value from the given annotation and converts it
* to a value appropriate for setting on a model's "$ref" property.
*
* @param annotation AnnotationInstance
* @param refType RefType
* @return String value
*/
public static String refValue(AnnotationInstance annotation, RefType refType) {
AnnotationValue value = annotation.value(OpenApiConstants.REF);
if (value == null) {
return null;
}
String ref = value.asString();
if (!COMPONENT_KEY_PATTERN.matcher(ref).matches()) {
return ref;
}
if (refType != null) {
ref = "#/components/" + refType.componentPath + "/" + ref;
} else {
throw UtilMessages.msg.refTypeNotNull();
}
return ref;
}
@BuildStep
SpringBeanNameToDotNameBuildItem createBeanNamesMap(BeanArchiveIndexBuildItem beanArchiveIndexBuildItem) {
final Map<String, DotName> result = new HashMap<>();
final IndexView index = beanArchiveIndexBuildItem.getIndex();
final Collection<AnnotationInstance> stereotypeInstances = new ArrayList<>();
stereotypeInstances.addAll(index.getAnnotations(SPRING_COMPONENT));
stereotypeInstances.addAll(index.getAnnotations(SPRING_REPOSITORY));
stereotypeInstances.addAll(index.getAnnotations(SPRING_SERVICE));
for (AnnotationInstance stereotypeInstance : stereotypeInstances) {
if (stereotypeInstance.target().kind() != AnnotationTarget.Kind.CLASS) {
continue;
}
result.put(getBeanNameFromStereotypeInstance(stereotypeInstance), stereotypeInstance.target().asClass().name());
}
for (AnnotationInstance beanInstance : index.getAnnotations(BEAN_ANNOTATION)) {
if (beanInstance.target().kind() != AnnotationTarget.Kind.METHOD) {
continue;
}
result.put(getBeanNameFromBeanInstance(beanInstance), beanInstance.target().asMethod().returnType().name());
}
return new SpringBeanNameToDotNameBuildItem(result);
}
private boolean restJsonSupportNeeded(CombinedIndexBuildItem indexBuildItem, DotName mediaTypeAnnotation) {
for (AnnotationInstance annotationInstance : indexBuildItem.getIndex().getAnnotations(mediaTypeAnnotation)) {
final AnnotationValue annotationValue = annotationInstance.value();
if (annotationValue == null) {
continue;
}
List<String> mediaTypes = Collections.emptyList();
if (annotationValue.kind() == Kind.ARRAY) {
mediaTypes = Arrays.asList(annotationValue.asStringArray());
} else if (annotationValue.kind() == Kind.STRING) {
mediaTypes = Collections.singletonList(annotationValue.asString());
}
return mediaTypes.contains(MediaType.APPLICATION_JSON)
|| mediaTypes.contains(MediaType.APPLICATION_JSON_PATCH_JSON);
}
return false;
}
/**
* Reads an array of APIResponse annotations into an {@link APIResponses} model.
*
* @param context the scanning context
* @param annotationValue {@literal @}APIResponse annotation
* @return APIResponses model
*/
public static APIResponses readResponses(final AnnotationScannerContext context,
final AnnotationValue annotationValue) {
if (annotationValue == null) {
return null;
}
IoLogging.log.annotationsListInto("@APIResponse", "APIResponses model");
APIResponses responses = new APIResponsesImpl();
AnnotationInstance[] nestedArray = annotationValue.asNestedArray();
for (AnnotationInstance nested : nestedArray) {
String responseCode = JandexUtil.stringValue(nested, ResponseConstant.PROP_RESPONSE_CODE);
if (responseCode != null) {
responses.addAPIResponse(responseCode,
ResponseReader.readResponse(context, nested));
}
}
return responses;
}
/**
* Reads the PathItem.
* Also used in CallbackOperation
*
* @param context the scanning context
* @param annotationValue the annotation value
* @return PathItem model
*/
public static PathItem readPathItem(final AnnotationScannerContext context,
final AnnotationValue annotationValue) {
if (annotationValue == null) {
return null;
}
AnnotationInstance[] nestedArray = annotationValue.asNestedArray();
PathItem pathItem = new PathItemImpl();
for (AnnotationInstance operationAnno : nestedArray) {
String method = JandexUtil.stringValue(operationAnno, PathsConstant.PROP_METHOD);
Operation operation = OperationReader.readOperation(context, operationAnno);
if (method == null) {
continue;
}
try {
PropertyDescriptor descriptor = new PropertyDescriptor(method.toUpperCase(), pathItem.getClass());
Method mutator = descriptor.getWriteMethod();
mutator.invoke(pathItem, operation);
} catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
IoLogging.log.readingCallbackOperation(e);
}
}
return pathItem;
}
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 void validateUsage(AnnotationInstance instance) {
if (instance.target().kind() != AnnotationTarget.Kind.METHOD) {
throw new IllegalArgumentException(
"Currently Spring Cache annotations can only be added to methods. Offending instance is annotation '"
+ instance + "' on " + instance.target() + "'");
}
List<AnnotationValue> values = instance.values();
List<String> unsupportedValues = new ArrayList<>();
for (AnnotationValue value : values) {
if (CURRENTLY_UNSUPPORTED_ANNOTATION_VALUES.contains(value.name())) {
unsupportedValues.add(value.name());
}
}
if (!unsupportedValues.isEmpty()) {
throw new IllegalArgumentException("Annotation '" +
instance + "' on '" + instance.target()
+ "' contains the following currently unsupported annotation values: "
+ String.join(", ", unsupportedValues));
}
}
/**
* Reads a Schema annotation into a model.
*
* @param index the index
* @param annotation the annotation instance
* @return Schema model
*/
public static Schema readSchema(IndexView index, AnnotationInstance annotation) {
if (annotation == null) {
return null;
}
IoLogging.log.singleAnnotation("@Schema");
// Schemas can be hidden. Skip if that's the case.
Optional<Boolean> isHidden = JandexUtil.booleanValue(annotation, SchemaConstant.PROP_HIDDEN);
if (isHidden.isPresent() && isHidden.get()) {
return null;
}
return readSchema(index, new SchemaImpl(), annotation, Collections.emptyMap());
}
/**
* @see {@link Index#getAnnotations(org.jboss.jandex.DotName)}
*/
public List<AnnotationInstance> getAnnotations(final DotName annotationName) {
final List<AnnotationInstance> allInstances = new ArrayList<AnnotationInstance>();
for (Index index : indexes) {
final List<AnnotationInstance> list = index.getAnnotations(annotationName);
if (list != null) {
allInstances.addAll(list);
}
}
return Collections.unmodifiableList(allInstances);
}
/**
* Reads an OAuthFlows annotation into a model.
*
* @param annotationValue the annotation value
* @return OAuthFlows model
*/
public static OAuthFlows readOAuthFlows(final AnnotationValue annotationValue) {
if (annotationValue == null) {
return null;
}
IoLogging.log.singleAnnotation("@OAuthFlows");
AnnotationInstance annotation = annotationValue.asNested();
OAuthFlows flows = new OAuthFlowsImpl();
flows.setImplicit(readOAuthFlow(annotation.value(SecuritySchemeConstant.PROP_IMPLICIT)));
flows.setPassword(readOAuthFlow(annotation.value(SecuritySchemeConstant.PROP_PASSWORD)));
flows.setClientCredentials(readOAuthFlow(annotation.value(SecuritySchemeConstant.PROP_CLIENT_CREDENTIALS)));
flows.setAuthorizationCode(readOAuthFlow(annotation.value(SecuritySchemeConstant.PROP_AUTHORIZATION_CODE)));
return flows;
}
/**
* Reads a Integer property value from the given annotation instance. If no value is found
* this will return null.
*
* @param annotation AnnotationInstance
* @param propertyName String
* @return Integer value
*/
public static Integer intValue(AnnotationInstance annotation, String propertyName) {
AnnotationValue value = annotation.value(propertyName);
if (value == null) {
return null;
} else {
return value.asInt();
}
}
private AnnotationInstance getAnnotation(DeploymentUnit depUnit, String className) {
List<AnnotationInstance> annotations = getAnnotations(depUnit, className);
if (annotations.size() > 1) {
LOGGER.warn("Multiple annotations found: {}", annotations);
}
return annotations.size() > 0 ? annotations.get(0) : null;
}
private ResultHandle lookupUserById(JpaSecurityDefinition jpaSecurityDefinition, String name, MethodCreator methodCreator,
ResultHandle username, AnnotationInstance naturalIdAnnotation) {
ResultHandle user;
if (naturalIdAnnotation != null) {
// Session session = em.unwrap(Session.class);
ResultHandle session = methodCreator.invokeInterfaceMethod(
MethodDescriptor.ofMethod(EntityManager.class, "unwrap", Object.class, Class.class),
methodCreator.getMethodParam(0),
methodCreator.loadClass(Session.class));
// SimpleNaturalIdLoadAccess<PlainUserEntity> naturalIdLoadAccess = session.bySimpleNaturalId(PlainUserEntity.class);
ResultHandle naturalIdLoadAccess = methodCreator.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Session.class, "bySimpleNaturalId",
SimpleNaturalIdLoadAccess.class, Class.class),
methodCreator.checkCast(session, Session.class),
methodCreator.loadClass(jpaSecurityDefinition.annotatedClass.name().toString()));
// PlainUserEntity user = naturalIdLoadAccess.load(request.getUsername());
user = methodCreator.invokeInterfaceMethod(
MethodDescriptor.ofMethod(SimpleNaturalIdLoadAccess.class, "load",
Object.class, Object.class),
naturalIdLoadAccess, username);
} else {
// Query query = entityManager.createQuery("FROM Entity WHERE field = :name")
String hql = "FROM " + jpaSecurityDefinition.annotatedClass.simpleName() + " WHERE "
+ jpaSecurityDefinition.username.name() + " = :name";
ResultHandle query = methodCreator.invokeInterfaceMethod(
MethodDescriptor.ofMethod(EntityManager.class, "createQuery", Query.class, String.class),
methodCreator.getMethodParam(0), methodCreator.load(hql));
// query.setParameter("name", request.getUsername())
ResultHandle query2 = methodCreator.invokeInterfaceMethod(
MethodDescriptor.ofMethod(Query.class, "setParameter", Query.class, String.class, Object.class),
query, methodCreator.load("name"), username);
// UserEntity user = getSingleUser(query2);
user = methodCreator.invokeVirtualMethod(
MethodDescriptor.ofMethod(name, "getSingleUser", Object.class, Query.class),
methodCreator.getThis(), query2);
}
return user;
}
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;
}
/**
* Returns all annotations configured for a single parameter of a method.
*
* @param method MethodInfo
* @param paramPosition parameter position
* @return List of AnnotationInstance's
*/
public static List<AnnotationInstance> getParameterAnnotations(MethodInfo method, short paramPosition) {
return method.annotations()
.stream()
.filter(annotation -> {
AnnotationTarget target = annotation.target();
return target != null && target.kind() == Kind.METHOD_PARAMETER
&& target.asMethodParameter().position() == paramPosition;
})
.collect(toList());
}
@Test
public void getAnnotationsToAddDefaultsToSingleton() {
final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
final ClassInfo target = index.getClassByName(DotName.createSimple(UndeclaredBean.class.getName()));
final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);
final Set<AnnotationInstance> expected = setOf(
AnnotationInstance.create(DotName.createSimple(Singleton.class.getName()), target,
Collections.emptyList()));
assertEquals(expected, ret);
}
@BuildStep
void build(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, CombinedIndexBuildItem indexBuildItem) {
IndexView index = indexBuildItem.getIndex();
for (AnnotationInstance annotationInstance : index.getAnnotations(CONSTRUCTOR_PROPERTIES)) {
registerInstance(reflectiveClass, annotationInstance);
}
}
private Schema generateSchema() {
// Get all the @GraphQLAPI annotations
Collection<AnnotationInstance> graphQLApiAnnotations = ScanningContext.getIndex()
.getAnnotations(Annotations.GRAPHQL_API);
final Schema schema = new Schema();
for (AnnotationInstance graphQLApiAnnotation : graphQLApiAnnotations) {
ClassInfo apiClass = graphQLApiAnnotation.target().asClass();
List<MethodInfo> methods = apiClass.methods();
addOperations(schema, methods);
}
// The above queries and mutations reference some models (input / type / interfaces / enum), let's create those
addTypesToSchema(schema);
// We might have missed something
addOutstandingTypesToSchema(schema);
// Add all annotated errors (Exceptions)
addErrors(schema);
// Reset the maps.
referenceCreator.clear();
return schema;
}
/**
* Retrieves a constraint {@link AnnotationInstance} from the current
* target. If the annotation is found and applies to multiple bean
* validation groups or to a single group other than the {@link Default},
* returns null.
*
* @param target
* the object from which to retrieve the constraint annotation
* @param annotationName
* name of the annotation
* @return the first occurrence of the named constraint if no groups or only
* the {@link Default} group is specified, or null
*/
AnnotationInstance getConstraint(AnnotationTarget target, DotName annotationName) {
AnnotationInstance constraint = getAnnotation(target, annotationName);
if (constraint != null) {
AnnotationValue groupValue = constraint.value("groups");
if (groupValue == null) {
return constraint;
}
Type[] groups = groupValue.asClassArray();
switch (groups.length) {
case 0:
return constraint;
case 1:
if (groups[0].name().equals(BV_DEFAULT_GROUP)) {
return constraint;
}
break;
default:
break;
}
}
return null;
}
private static Optional<TransformInfo> getNumberFormat(AnnotationInstance annotationInstance) {
if (annotationInstance != null) {
String format = getStringValue(annotationInstance);
String locale = getStringValue(annotationInstance, LOCALE);
return Optional.of(new TransformInfo(
TransformInfo.Type.NUMBER,
format,
locale,
isJsonB(annotationInstance)));
}
return Optional.empty();
}
/**
* Reads any Server annotations.The annotation value is an array of Server annotations.
*
* @param annotationValue an Array of {@literal @}Server annotations
* @return a List of Server models
*/
public static Optional<List<Server>> readServers(final AnnotationValue annotationValue) {
if (annotationValue != null) {
IoLogging.log.annotationsArray("@Server");
AnnotationInstance[] nestedArray = annotationValue.asNestedArray();
List<Server> servers = new ArrayList<>();
for (AnnotationInstance serverAnno : nestedArray) {
servers.add(readServer(serverAnno));
}
return Optional.of(servers);
}
return Optional.empty();
}
private static Optional<String> getFormat(AnnotationInstance annotationInstance) {
AnnotationValue locale = annotationInstance.value(LOCALE);
AnnotationValue format = annotationInstance.value();
if (format == null && locale == null) {
return Optional.empty();
} else if (format == null) {
return Optional.of(locale.asString());
} else if (locale == null) {
return Optional.of(format.asString());
} else {
return Optional.of(format.asString() + " " + locale.asString());
}
}
/**
* Retrieves the "value" parameter from annotation to be used as the name.
* If no value was specified or an empty value, return the name of the annotation
* target.
*
* @param annotation parameter annotation
* @return the name of the parameter
*/
static String paramName(AnnotationInstance annotation) {
AnnotationValue value = annotation.value();
String valueString = null;
if (value != null) {
valueString = value.asString();
if (valueString.length() > 0) {
return valueString;
}
}
AnnotationTarget target = annotation.target();
switch (target.kind()) {
case FIELD:
valueString = target.asField().name();
break;
case METHOD_PARAMETER:
valueString = target.asMethodParameter().name();
break;
case METHOD:
// This is a bean property setter
MethodInfo method = target.asMethod();
if (method.parameters().size() == 1) {
String methodName = method.name();
if (methodName.startsWith("set")) {
valueString = Introspector.decapitalize(methodName.substring(3));
} else {
valueString = methodName;
}
}
break;
default:
break;
}
return valueString;
}
@BuildStep
AdditionalBeanBuildItem registerProviderBeans(CombinedIndexBuildItem combinedIndex) {
IndexView index = combinedIndex.getIndex();
List<AnnotationInstance> allInstances = new ArrayList<>(index.getAnnotations(REGISTER_PROVIDER));
for (AnnotationInstance annotation : index.getAnnotations(REGISTER_PROVIDERS)) {
allInstances.addAll(Arrays.asList(annotation.value().asNestedArray()));
}
AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder().setUnremovable();
for (AnnotationInstance annotationInstance : allInstances) {
// Make sure all providers not annotated with @Provider but used in @RegisterProvider are registered as beans
builder.addBeanClass(annotationInstance.value().asClass().toString());
}
return builder.build();
}
private AnnotationInstance getSingleControllerAdviceInstance(IndexView index) {
Collection<AnnotationInstance> controllerAdviceInstances = index.getAnnotations(REST_CONTROLLER_ADVICE);
if (controllerAdviceInstances.isEmpty()) {
return null;
}
if (controllerAdviceInstances.size() > 1) {
throw new IllegalStateException("You can only have a single class annotated with @ControllerAdvice");
}
return controllerAdviceInstances.iterator().next();
}
@Test
public void getAnnotationsToAddExplicitScopeOnConflictWorks() {
final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
final ClassInfo target = index
.getClassByName(DotName.createSimple(OverrideConflictStereotypeBean.class.getName()));
final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);
final Set<AnnotationInstance> expected = setOf(
AnnotationInstance.create(DotName.createSimple(ApplicationScoped.class.getName()), target,
Collections.emptyList()));
assertEquals(expected, ret);
}