Java Code Examples for org.jboss.jandex.MethodInfo

The following examples show how to use org.jboss.jandex.MethodInfo. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: quarkus   Source File: SpringDIProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getAnnotationsToAddBeanMethodDefaultsToSingleton() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
    final MethodInfo target = index.getClassByName(DotName.createSimple(BeanConfig.class.getName()))
            .method("singletonBean");

    final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);

    final Set<AnnotationInstance> expected = setOf(
            AnnotationInstance.create(DotName.createSimple(Singleton.class.getName()), target,
                    Collections.emptyList()),
            AnnotationInstance.create(DotNames.PRODUCES, target, Collections.emptyList()),
            AnnotationInstance.create(DotName.createSimple(Named.class.getName()), target,
                    Collections.singletonList(AnnotationValue.createStringValue("value", "singletonBean"))));
    assertEquals(expected, ret);
}
 
Example 2
Source Project: quarkus   Source File: SpringDIProcessorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getAnnotationsToAddBeanMethodWithScope() {
    final Map<DotName, Set<DotName>> scopes = processor.getStereotypeScopes(index);
    final MethodInfo target = index.getClassByName(DotName.createSimple(BeanConfig.class.getName()))
            .method("requestBean");

    final Set<AnnotationInstance> ret = processor.getAnnotationsToAdd(target, scopes, null);

    final Set<AnnotationInstance> expected = setOf(
            AnnotationInstance.create(DotName.createSimple(RequestScoped.class.getName()), target,
                    Collections.emptyList()),
            AnnotationInstance.create(DotNames.PRODUCES, target, Collections.emptyList()),
            AnnotationInstance.create(DotName.createSimple(Named.class.getName()), target,
                    Collections.singletonList(AnnotationValue.createStringValue("value", "requestBean"))));
    assertEquals(expected, ret);
}
 
Example 3
@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;
}
 
Example 4
Source Project: quarkus   Source File: JpaSecurityDefinition.java    License: Apache License 2.0 6 votes vote down vote up
private static MethodInfo findGetter(Index index, ClassInfo annotatedClass, String methodName) {
    MethodInfo method = annotatedClass.method(methodName);
    if (method != null) {
        return method;
    }
    DotName superName = annotatedClass.superName();
    if (superName != null && !superName.equals(QuarkusSecurityJpaProcessor.DOTNAME_OBJECT)) {
        ClassInfo superClass = index.getClassByName(superName);
        if (superClass != null) {
            method = findGetter(index, superClass, methodName);
            if (method != null) {
                return method;
            }
        }
    }
    for (DotName interfaceName : annotatedClass.interfaceNames()) {
        ClassInfo interf = index.getClassByName(interfaceName);
        if (interf != null) {
            method = findGetter(index, interf, methodName);
            if (method != null) {
                return method;
            }
        }
    }
    return null;
}
 
Example 5
Source Project: quarkus   Source File: RestClientProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void warnAboutNotWorkingFeaturesInNative(PackageConfig packageConfig, Map<DotName, ClassInfo> interfaces) {
    if (!packageConfig.type.equalsIgnoreCase(PackageConfig.NATIVE)) {
        return;
    }
    Set<DotName> dotNames = new HashSet<>();
    for (ClassInfo interfaze : interfaces.values()) {
        if (interfaze.classAnnotation(CLIENT_HEADER_PARAM) != null) {
            boolean hasDefault = false;
            for (MethodInfo method : interfaze.methods()) {
                if (isDefault(method.flags())) {
                    hasDefault = true;
                    break;
                }
            }
            if (hasDefault) {
                dotNames.add(interfaze.name());
            }
        }
    }
    if (!dotNames.isEmpty()) {
        log.warnf("rest-client interfaces that contain default methods and are annotated with '@" + CLIENT_HEADER_PARAM
                + "' might not work properly in native mode. Offending interfaces are: "
                + dotNames.stream().map(d -> "'" + d.toString() + "'").collect(Collectors.joining(", ")));
    }
}
 
Example 6
Source Project: quarkus   Source File: VertxProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
void collectEventConsumers(
        BeanRegistrationPhaseBuildItem beanRegistrationPhase,
        BuildProducer<EventConsumerBusinessMethodItem> messageConsumerBusinessMethods,
        BuildProducer<BeanConfiguratorBuildItem> errors) {
    // We need to collect all business methods annotated with @ConsumeEvent first
    AnnotationStore annotationStore = beanRegistrationPhase.getContext().get(BuildExtension.Key.ANNOTATION_STORE);
    for (BeanInfo bean : beanRegistrationPhase.getContext().beans().classBeans()) {
        for (MethodInfo method : bean.getTarget().get().asClass().methods()) {
            AnnotationInstance consumeEvent = annotationStore.getAnnotation(method, CONSUME_EVENT);
            if (consumeEvent != null) {
                // Validate method params and return type
                List<Type> params = method.parameters();
                if (params.size() != 1) {
                    throw new IllegalStateException(String.format(
                            "Event consumer business method must accept exactly one parameter: %s [method: %s, bean:%s",
                            params, method, bean));
                }
                messageConsumerBusinessMethods
                        .produce(new EventConsumerBusinessMethodItem(bean, method, consumeEvent));
                LOGGER.debugf("Found event consumer business method %s declared on %s", method, bean);
            }
        }
    }
}
 
Example 7
Source Project: quarkus   Source File: AsmUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Java bytecode signature of a given Jandex MethodInfo using the given type argument mappings.
 * For example, given this method:
 * 
 * <pre>
 * {@code
 * public class Foo<T> {
 *  public <R> List<R> method(int a, T t){...} 
 * }
 * }
 * </pre>
 * 
 * This will return <tt>&lt;R:Ljava/lang/Object;>(ILjava/lang/Integer;)Ljava/util/List&lt;TR;>;</tt> if
 * your {@code typeArgMapper} contains {@code T=Ljava/lang/Integer;}.
 * 
 * @param method the method you want the signature for.
 * @param typeArgMapper a mapping between type argument names and their bytecode signature.
 * @return a bytecode signature for that method.
 */
public static String getSignature(MethodInfo method, Function<String, String> typeArgMapper) {
    List<Type> parameters = method.parameters();

    StringBuilder signature = new StringBuilder("");
    for (TypeVariable typeVariable : method.typeParameters()) {
        if (signature.length() == 0)
            signature.append("<");
        else
            signature.append(",");
        signature.append(typeVariable.identifier()).append(":");
        // FIXME: only use the first bound
        toSignature(signature, typeVariable.bounds().get(0), typeArgMapper, false);
    }
    if (signature.length() > 0)
        signature.append(">");
    signature.append("(");
    for (Type type : parameters) {
        toSignature(signature, type, typeArgMapper, false);
    }
    signature.append(")");
    toSignature(signature, method.returnType(), typeArgMapper, false);
    return signature.toString();
}
 
Example 8
Source Project: smallrye-open-api   Source File: SpringAnnotationScanner.java    License: Apache License 2.0 6 votes vote down vote up
static Optional<String[]> getMediaTypes(MethodInfo resourceMethod, MediaTypeProperty property) {
    Set<DotName> annotationNames = SpringConstants.HTTP_METHODS;

    for (DotName annotationName : annotationNames) {
        AnnotationInstance annotation = resourceMethod.annotation(annotationName);

        if (annotation == null || annotation.value(property.name()) == null) {
            annotation = JandexUtil.getClassAnnotation(resourceMethod.declaringClass(), SpringConstants.REQUEST_MAPPING);
        }

        if (annotation != null) {
            AnnotationValue annotationValue = annotation.value(property.name());

            if (annotationValue != null) {
                return Optional.of(annotationValue.asStringArray());
            }

            return Optional.of(OpenApiConstants.DEFAULT_MEDIA_TYPES.get());
        }
    }
    return Optional.empty();
}
 
Example 9
Source Project: quarkus   Source File: Methods.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean skipForClientProxy(MethodInfo method) {
    if (Modifier.isStatic(method.flags()) || Modifier.isPrivate(method.flags())) {
        return true;
    }
    if (IGNORED_METHODS.contains(method.name())) {
        return true;
    }
    // skip all Object methods except for toString()
    if (method.declaringClass().name().equals(DotNames.OBJECT) && !method.name().equals(TO_STRING)) {
        return true;
    }
    if (Modifier.isFinal(method.flags())) {
        String className = method.declaringClass().name().toString();
        if (!className.startsWith("java.")) {
            LOGGER.warn(String.format(
                    "Final method %s.%s() is ignored during proxy generation and should never be invoked upon the proxy instance!",
                    className, method.name()));
        }
        return true;
    }
    return false;
}
 
Example 10
Source Project: quarkus   Source File: SmallRyeFaultToleranceProcessor.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 11
Source Project: quarkus   Source File: SimpleGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void init() throws IOException {
    TestClassOutput classOutput = new TestClassOutput();
    Index index = index(MyService.class, PublicMyService.class, BaseService.class, MyItem.class, String.class,
            CompletionStage.class,
            List.class);
    ValueResolverGenerator generator = new ValueResolverGenerator(index, classOutput, Collections.emptyMap());
    ClassInfo myServiceClazz = index.getClassByName(DotName.createSimple(MyService.class.getName()));
    generator.generate(myServiceClazz);
    generator.generate(index.getClassByName(DotName.createSimple(PublicMyService.class.getName())));
    generator.generate(index.getClassByName(DotName.createSimple(MyItem.class.getName())));
    generator.generate(index.getClassByName(DotName.createSimple(String.class.getName())));
    generator.generate(index.getClassByName(DotName.createSimple(List.class.getName())));
    generatedTypes.addAll(generator.getGeneratedTypes());

    ExtensionMethodGenerator extensionMethodGenerator = new ExtensionMethodGenerator(classOutput);
    MethodInfo extensionMethod = index.getClassByName(DotName.createSimple(MyService.class.getName())).method(
            "getDummy", Type.create(myServiceClazz.name(), Kind.CLASS), PrimitiveType.INT,
            Type.create(DotName.createSimple(String.class.getName()), Kind.CLASS));
    extensionMethodGenerator.generate(extensionMethod, null, null);
    extensionMethod = index.getClassByName(DotName.createSimple(MyService.class.getName())).method(
            "getDummy", Type.create(myServiceClazz.name(), Kind.CLASS), PrimitiveType.INT,
            PrimitiveType.LONG);
    extensionMethodGenerator.generate(extensionMethod, null, null);
    extensionMethod = index.getClassByName(DotName.createSimple(MyService.class.getName())).method(
            "getDummyVarargs", Type.create(myServiceClazz.name(), Kind.CLASS), PrimitiveType.INT,
            Type.create(DotName.createSimple("[L" + String.class.getName() + ";"), Kind.ARRAY));
    extensionMethodGenerator.generate(extensionMethod, null, null);
    generatedTypes.addAll(extensionMethodGenerator.getGeneratedTypes());
}
 
Example 12
Source Project: smallrye-graphql   Source File: SchemaBuilder.java    License: Apache License 2.0 5 votes vote down vote up
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;
    }
 
Example 13
Source Project: smallrye-graphql   Source File: SchemaBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This inspect all method, looking for Query and Mutation annotations,
 * to create those Operations.
 * 
 * @param schema the schema to add the operation to.
 * @param methodInfoList the java methods.
 */
private void addOperations(Schema schema, List<MethodInfo> methodInfoList) {
    for (MethodInfo methodInfo : methodInfoList) {
        Annotations annotationsForMethod = Annotations.getAnnotationsForMethod(methodInfo);
        if (annotationsForMethod.containsOneOfTheseAnnotations(Annotations.QUERY)) {
            Operation query = operationCreator.createOperation(methodInfo, OperationType.Query, null);
            schema.addQuery(query);
        } else if (annotationsForMethod.containsOneOfTheseAnnotations(Annotations.MUTATION)) {
            Operation mutation = operationCreator.createOperation(methodInfo, OperationType.Mutation, null);
            schema.addMutation(mutation);
        }
    }
}
 
Example 14
Source Project: quarkus   Source File: MethodPropertiesAccessor.java    License: Apache License 2.0 5 votes vote down vote up
private boolean doParametersMatch(MethodInfo methodInfo, String... methodParameterTypes) {
    if (methodInfo.parameters().size() != methodParameterTypes.length) {
        return false;
    }

    List<String> actualParameterTypes = methodInfo.parameters()
            .stream()
            .map(Type::name)
            .map(DotName::toString)
            .collect(Collectors.toList());

    return actualParameterTypes.equals(Arrays.asList(methodParameterTypes));
}
 
Example 15
Source Project: quarkus   Source File: ConstructorPropertiesProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void registerInstance(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, AnnotationInstance instance) {
    AnnotationTarget annotationTarget = instance.target();
    if (annotationTarget instanceof MethodInfo) {
        MethodInfo methodInfo = (MethodInfo) annotationTarget;
        String classname = methodInfo.declaringClass().toString();
        reflectiveClass.produce(asReflectiveClassBuildItem(classname));
    }
}
 
Example 16
Source Project: quarkus   Source File: BeanMethodInvocationGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private MethodInfo determineMatchingBeanMethod(String methodName, int methodParametersSize, ClassInfo beanClassInfo,
        MethodInfo securedMethodInfo, String expression, String beanName) {
    MethodInfo matchingBeanClassMethod = null;
    for (MethodInfo candidateMethod : beanClassInfo.methods()) {
        if (candidateMethod.name().equals(methodName) &&
                Modifier.isPublic(candidateMethod.flags()) &&
                DotNames.PRIMITIVE_BOOLEAN.equals(candidateMethod.returnType().name()) &&
                candidateMethod.parameters().size() == methodParametersSize) {
            if (matchingBeanClassMethod == null) {
                matchingBeanClassMethod = candidateMethod;
            } else {
                throw new IllegalArgumentException(
                        "Could not match a unique method name '" + methodName + "' for bean named " + beanName
                                + " with class " + beanClassInfo.name() + " Offending expression is " +
                                expression + " of @PreAuthorize on method '" + methodName + "' of class "
                                + securedMethodInfo.declaringClass());
            }
        }
    }
    if (matchingBeanClassMethod == null) {
        throw new IllegalArgumentException(
                "Could not find a public, boolean returning method named '" + methodName + "' for bean named " + beanName
                        + " with class " + beanClassInfo.name() + " Offending expression is " +
                        expression + " of @PreAuthorize on method '" + methodName + "' of class "
                        + securedMethodInfo.declaringClass());
    }
    return matchingBeanClassMethod;
}
 
Example 17
Source Project: smallrye-graphql   Source File: OperationCreator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the name from annotation(s) or default.
 * This is for operations (query, mutation and source)
 * 
 * @param methodInfo the java method
 * @param operationType the type (query, mutation)
 * @param annotations the annotations on this method
 * @return the operation name
 */
private static String getOperationName(MethodInfo methodInfo, OperationType operationType, Annotations annotations) {
    DotName operationAnnotation = getOperationAnnotation(operationType);

    // If the @Query or @Mutation annotation has a value, use that, else use name or jsonb property
    return annotations.getOneOfTheseMethodAnnotationsValue(
            operationAnnotation,
            Annotations.NAME,
            Annotations.JSONB_PROPERTY)
            .orElse(getDefaultExecutionTypeName(methodInfo, operationType));

}
 
Example 18
Source Project: smallrye-graphql   Source File: TypeCreator.java    License: Apache License 2.0 5 votes vote down vote up
private void addOperations(Type type, ClassInfo classInfo) {
    Map<DotName, List<MethodParameterInfo>> sourceFields = SourceOperationHelper.getAllSourceAnnotations();
    // See if there is source operations for this class
    if (sourceFields.containsKey(classInfo.name())) {
        List<MethodParameterInfo> methodParameterInfos = sourceFields.get(classInfo.name());
        for (MethodParameterInfo methodParameterInfo : methodParameterInfos) {
            MethodInfo methodInfo = methodParameterInfo.method();
            Operation operation = operationCreator.createOperation(methodInfo, OperationType.Source, type);
            type.addOperation(operation);
        }
    }
}
 
Example 19
Source Project: smallrye-graphql   Source File: FormatHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 20
Source Project: smallrye-graphql   Source File: FormatHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFormattedCompletionStage() throws Exception {
    Index complete = IndexCreator.index(AsyncApi.class);

    ClassInfo classByName = complete.getClassByName(DotName.createSimple(AsyncApi.class.getName()));
    MethodInfo nonNullString = classByName.method("formattedCompletionStage");
    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());
}
 
Example 21
Source Project: quarkus   Source File: HasRoleValueUtil.java    License: Apache License 2.0 5 votes vote down vote up
static HasRoleValueProducer getHasRoleValueProducer(String hasRoleValue, MethodInfo methodInfo, IndexView index,
        Map<String, DotName> springBeansNameToDotName,
        Map<String, ClassInfo> springBeansNameToClassInfo, Set<String> beansReferencedInPreAuthorized) {
    if (hasRoleValue.startsWith("'") && hasRoleValue.endsWith("'")) {
        return new StaticHasRoleValueProducer(hasRoleValue.replace("'", ""));
    } else if (hasRoleValue.startsWith("@")) {
        Matcher beanFieldMatcher = BEAN_FIELD_PATTERN.matcher(hasRoleValue);
        if (!beanFieldMatcher.find()) {
            throw SpringSecurityProcessorUtil.createGenericMalformedException(methodInfo, hasRoleValue);
        }

        String beanName = beanFieldMatcher.group(1);
        ClassInfo beanClassInfo = SpringSecurityProcessorUtil.getClassInfoFromBeanName(beanName, index,
                springBeansNameToDotName, springBeansNameToClassInfo, hasRoleValue, methodInfo);

        String fieldName = beanFieldMatcher.group(2);
        FieldInfo fieldInfo = beanClassInfo.field(fieldName);
        if ((fieldInfo == null) || !Modifier.isPublic(fieldInfo.flags())
                || !DotNames.STRING.equals(fieldInfo.type().name())) {
            throw new IllegalArgumentException("Bean named '" + beanName + "' found in expression '" + hasRoleValue
                    + "' in the @PreAuthorize annotation on method " + methodInfo.name() + " of class "
                    + methodInfo.declaringClass() + " does not have a public field named '" + fieldName
                    + "' of type String");
        }

        beansReferencedInPreAuthorized.add(fieldInfo.declaringClass().name().toString());

        return new FromBeanHasRoleValueProducer(beanName, fieldInfo);
    } else {
        throw SpringSecurityProcessorUtil.createGenericMalformedException(methodInfo, hasRoleValue);
    }
}
 
Example 22
Source Project: quarkus   Source File: FieldAccessImplementor.java    License: Apache License 2.0 5 votes vote down vote up
public ResultHandle getId(BytecodeCreator creator, String className, ResultHandle instance) {
    ClassInfo classInfo = index.getClassByName(DotName.createSimple(className));
    FieldInfo field = getIdField(classInfo);
    if (field == null) {
        throw new RuntimeException(className + " does not have a field annotated with @Id");
    }

    MethodInfo getter = getGetter(classInfo, field);
    if (getter != null) {
        return creator.invokeVirtualMethod(getter, instance);
    }

    return creator.readInstanceField(field, instance);
}
 
Example 23
Source Project: quarkus   Source File: ObserverInfo.java    License: Apache License 2.0 5 votes vote down vote up
int initEventMetadataParam(MethodInfo observerMethod) {
    if (observerMethod != null) {
        for (ListIterator<Type> iterator = observerMethod.parameters().listIterator(); iterator.hasNext();) {
            if (iterator.next().name().equals(DotNames.EVENT_METADATA)) {
                return iterator.previousIndex();
            }
        }
    }
    return -1;
}
 
Example 24
Source Project: smallrye-graphql   Source File: OperationCreatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFailOnNonPublicOperation() throws Exception {
    Index complete = IndexCreator.index(TestApi.class);

    ClassInfo classByName = complete.getClassByName(DotName.createSimple(TestApi.class.getName()));
    MethodInfo method = classByName.method("nonPublicQuery");

    try {
        operationCreator().createOperation(method, OperationType.Query, null);
        fail();
    } catch (IllegalArgumentException expected) {
    }
}
 
Example 25
Source Project: smallrye-graphql   Source File: OperationCreatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicOperation() throws Exception {
    Index complete = IndexCreator.index(TestApi.class);

    ClassInfo classByName = complete.getClassByName(DotName.createSimple(TestApi.class.getName()));
    MethodInfo method = classByName.method("publicQuery");

    final Operation operation = operationCreator().createOperation(method, OperationType.Query, null);

    assertEquals("publicQuery", operation.getName());
}
 
Example 26
private boolean annotationTargetIsCamelApi(AnnotationTarget target) {
    /**
     * Verify whether an annotation is applied to org.apache.camel types. If the declaring class
     * has the org.apache.camel package prefix, it is ignored since we are only interested in
     * annotations declared within user classes.
     */
    if (target != null) {
        if (target.kind().equals(Kind.CLASS)) {
            ClassInfo classInfo = target.asClass();
            if (isCamelApi(classInfo.name())) {
                return false;
            }

            Type superType = classInfo.superClassType();
            if (superType != null && isCamelApi(superType.name())) {
                return true;
            }

            return classInfo.interfaceNames().stream().anyMatch(interfaceName -> isCamelApi(interfaceName));
        } else if (target.kind().equals(Kind.FIELD)) {
            FieldInfo fieldInfo = target.asField();
            return !isCamelApi(fieldInfo.declaringClass().name()) && isCamelApi(fieldInfo.type().name());
        } else if (target.kind().equals(Kind.METHOD)) {
            MethodInfo methodInfo = target.asMethod();
            return !isCamelApi(methodInfo.declaringClass().name()) && isCamelApi(methodInfo.returnType().name());
        }
    }
    return false;
}
 
Example 27
Source Project: quarkus   Source File: JpaSecurityDefinition.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodInfo findGetter(Index index, ClassInfo annotatedClass, FieldInfo field, boolean isPanache) {
    // if it's a panache field, we won't see the getter but it will be there
    String methodName = "get" + JavaBeanUtil.capitalize(field.name());
    if (isPanache) {
        return MethodInfo.create(field.declaringClass(), methodName, new Type[0], field.type(), (short) Modifier.PUBLIC);
    }
    return findGetter(index, annotatedClass, methodName);
}
 
Example 28
Source Project: quarkus   Source File: Types.java    License: Apache License 2.0 5 votes vote down vote up
static Set<Type> getProducerMethodTypeClosure(MethodInfo producerMethod, BeanDeployment beanDeployment) {
    Set<Type> types;
    Type returnType = producerMethod.returnType();
    if (returnType.kind() == Kind.PRIMITIVE || returnType.kind() == Kind.ARRAY) {
        types = new HashSet<>();
        types.add(returnType);
        types.add(OBJECT_TYPE);
        return types;
    } else {
        ClassInfo returnTypeClassInfo = getClassByName(beanDeployment.getIndex(), returnType);
        if (returnTypeClassInfo == null) {
            throw new IllegalArgumentException(
                    "Producer method return type not found in index: " + producerMethod.returnType().name());
        }
        if (Kind.CLASS.equals(returnType.kind())) {
            types = getTypeClosure(returnTypeClassInfo, producerMethod, Collections.emptyMap(), beanDeployment, null);
        } else if (Kind.PARAMETERIZED_TYPE.equals(returnType.kind())) {
            types = getTypeClosure(returnTypeClassInfo, producerMethod,
                    buildResolvedMap(returnType.asParameterizedType().arguments(), returnTypeClassInfo.typeParameters(),
                            Collections.emptyMap(), beanDeployment.getIndex()),
                    beanDeployment, null);
        } else {
            throw new IllegalArgumentException("Unsupported return type");
        }
    }
    return restrictBeanTypes(types, beanDeployment.getAnnotations(producerMethod));
}
 
Example 29
Source Project: quarkus   Source File: InterfaceConfigPropertiesUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static String getPropertyName(MethodInfo method, ConfigProperties.NamingStrategy namingStrategy) {
    String effectiveName = method.name();
    try {
        effectiveName = JavaBeanUtil.getPropertyNameFromGetter(method.name());
    } catch (IllegalArgumentException ignored) {

    }
    return namingStrategy.getName(effectiveName);
}
 
Example 30
Source Project: quarkus   Source File: CacheAnnotationsTransformer.java    License: Apache License 2.0 5 votes vote down vote up
private AnnotationInstance createCacheInvalidateBinding(MethodInfo method, AnnotationInstance annotation,
        AnnotationTarget target) {
    List<AnnotationValue> parameters = new ArrayList<>();
    parameters.add(getCacheName(annotation));
    findCacheKeyParameters(method).ifPresent(parameters::add);
    return createBinding(CacheInvalidateInterceptorBinding.class, target, toArray(parameters));
}