Java Code Examples for org.jboss.jandex.ClassInfo#methods()

The following examples show how to use org.jboss.jandex.ClassInfo#methods() . 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 File: IsDataClassWithDefaultValuesPredicate.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: SmallRyeMetricsProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void findNonOverriddenDefaultMethods(ClassInfo interfaceInfo, Set<String> alreadyRegisteredNames,
        SmallRyeMetricsRecorder recorder,
        BeanArchiveIndexBuildItem beanArchiveIndex, JandexMemberInfoAdapter memberInfoAdapter, BeanInfo beanInfo) {
    // Check for default methods which are NOT overridden by the bean that we are registering metrics for
    // or any of its superclasses. Register a metric for each of them.
    for (MethodInfo method : interfaceInfo.methods()) {
        if (!Modifier.isAbstract(method.flags())) { // only take default methods
            if (!alreadyRegisteredNames.contains(method.name())) {
                recorder.registerMetrics(beanInfo, memberInfoAdapter.convert(method));
                alreadyRegisteredNames.add(method.name());
            }
        }
    }
    // recursively repeat the same for interfaces which this interface extends
    for (Type extendedInterface : interfaceInfo.interfaceTypes()) {
        ClassInfo extendedInterfaceInfo = beanArchiveIndex.getIndex().getClassByName(extendedInterface.name());
        if (extendedInterfaceInfo != null) {
            findNonOverriddenDefaultMethods(extendedInterfaceInfo, alreadyRegisteredNames, recorder, beanArchiveIndex,
                    memberInfoAdapter,
                    beanInfo);
        }
    }
}
 
Example 3
Source File: QuteProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to find a property with the specified name, ie. a public non-static non-synthetic field with the given name or a
 * public non-static non-synthetic method with no params and the given name.
 * 
 * @param name
 * @param clazz
 * @param index
 * @return the property or null
 */
private AnnotationTarget findProperty(String name, ClassInfo clazz, IndexView index) {
    while (clazz != null) {
        // Fields
        for (FieldInfo field : clazz.fields()) {
            if (Modifier.isPublic(field.flags()) && !Modifier.isStatic(field.flags())
                    && !ValueResolverGenerator.isSynthetic(field.flags()) && field.name().equals(name)) {
                return field;
            }
        }
        // Methods
        for (MethodInfo method : clazz.methods()) {
            if (Modifier.isPublic(method.flags()) && !Modifier.isStatic(method.flags())
                    && !ValueResolverGenerator.isSynthetic(method.flags()) && (method.name().equals(name)
                            || ValueResolverGenerator.getPropertyName(method.name()).equals(name))) {
                return method;
            }
        }
        DotName superName = clazz.superName();
        if (superName == null) {
            clazz = null;
        } else {
            clazz = index.getClassByName(clazz.superName());
        }
    }
    return null;
}
 
Example 4
Source File: BeanMethodInvocationGenerator.java    From quarkus with 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 5
Source File: SchedulerProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void collectScheduledMethods(IndexView index, AnnotationStore annotationStore, BeanInfo bean,
        ClassInfo beanClass, BuildProducer<ScheduledBusinessMethodItem> scheduledBusinessMethods) {

    for (MethodInfo method : beanClass.methods()) {
        List<AnnotationInstance> schedules = null;
        AnnotationInstance scheduledAnnotation = annotationStore.getAnnotation(method, SCHEDULED_NAME);
        if (scheduledAnnotation != null) {
            schedules = Collections.singletonList(scheduledAnnotation);
        } else {
            AnnotationInstance scheduledsAnnotation = annotationStore.getAnnotation(method, SCHEDULES_NAME);
            if (scheduledsAnnotation != null) {
                schedules = new ArrayList<>();
                for (AnnotationInstance scheduledInstance : scheduledsAnnotation.value().asNestedArray()) {
                    schedules.add(scheduledInstance);
                }
            }
        }
        if (schedules != null) {
            scheduledBusinessMethods.produce(new ScheduledBusinessMethodItem(bean, method, schedules));
            LOGGER.debugf("Found scheduled business method %s declared on %s", method, bean);
        }
    }

    DotName superClassName = beanClass.superName();
    if (superClassName != null) {
        ClassInfo superClass = index.getClassByName(superClassName);
        if (superClass != null) {
            collectScheduledMethods(index, annotationStore, bean, superClass, scheduledBusinessMethods);
        }
    }
}
 
Example 6
Source File: RestClientProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void processInterfaceReturnTypes(ClassInfo classInfo, Set<Type> returnTypes) {
    for (MethodInfo method : classInfo.methods()) {
        Type type = method.returnType();
        if (!type.name().toString().startsWith("java.lang")) {
            returnTypes.add(type);
        }
    }
}
 
Example 7
Source File: SpringScheduledProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BuildStep
void collectScheduledMethods(BeanRegistrationPhaseBuildItem beanRegistrationPhase,
        BuildProducer<ScheduledBusinessMethodItem> scheduledBusinessMethods) {

    Map<MethodInfo, AnnotationInstance> result = new HashMap<>();
    AnnotationStore annotationStore = beanRegistrationPhase.getContext().get(BuildExtension.Key.ANNOTATION_STORE);

    for (BeanInfo bean : beanRegistrationPhase.getContext().beans().classBeans()) {
        ClassInfo classInfo = bean.getTarget().get().asClass();
        for (MethodInfo method : classInfo.methods()) {
            List<AnnotationInstance> schedules = null;
            AnnotationInstance scheduledAnnotation = annotationStore.getAnnotation(method, SPRING_SCHEDULED);
            if (scheduledAnnotation != null) {
                schedules = Collections.singletonList(scheduledAnnotation);
            } else {
                AnnotationInstance scheduledsAnnotation = annotationStore.getAnnotation(method, SPRING_SCHEDULES);
                if (scheduledsAnnotation != null) {
                    schedules = new ArrayList<>();
                    for (AnnotationInstance scheduledInstance : scheduledsAnnotation.value().asNestedArray()) {
                        schedules.add(scheduledInstance);
                    }
                }
            }
            processSpringScheduledAnnotation(scheduledBusinessMethods, bean, method, schedules);

        }

    }
}
 
Example 8
Source File: SmallRyeFaultToleranceProcessor.java    From quarkus with 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 9
Source File: SchemaBuilder.java    From smallrye-graphql with 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 10
Source File: DenyingUnannotatedTransformer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void transform(TransformationContext transformationContext) {
    ClassInfo classInfo = transformationContext.getTarget().asClass();
    List<MethodInfo> methods = classInfo.methods();
    if (!SecurityTransformerUtils.hasStandardSecurityAnnotation(classInfo)
            && methods.stream().anyMatch(SecurityTransformerUtils::hasStandardSecurityAnnotation)) {
        transformationContext.transform().add(DENY_ALL).done();
    }
}
 
Example 11
Source File: Beans.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void collectCallbacks(ClassInfo clazz, List<MethodInfo> callbacks, DotName annotation, IndexView index) {
    for (MethodInfo method : clazz.methods()) {
        if (method.hasAnnotation(annotation) && method.returnType().kind() == Kind.VOID && method.parameters().isEmpty()) {
            callbacks.add(method);
        }
    }
    if (clazz.superName() != null) {
        ClassInfo superClass = getClassByName(index, clazz.superName());
        if (superClass != null) {
            collectCallbacks(superClass, callbacks, annotation, index);
        }
    }
}
 
Example 12
Source File: Methods.java    From quarkus with Apache License 2.0 5 votes vote down vote up
static void addDelegatingMethods(IndexView index, ClassInfo classInfo, Map<Methods.MethodKey, MethodInfo> methods) {
    // TODO support interfaces default methods
    if (classInfo != null) {
        for (MethodInfo method : classInfo.methods()) {
            if (skipForClientProxy(method)) {
                continue;
            }
            methods.computeIfAbsent(new Methods.MethodKey(method), key -> {
                // If parameterized try to resolve the type variables
                Type returnType = key.method.returnType();
                Type[] params = new Type[key.method.parameters().size()];
                for (int i = 0; i < params.length; i++) {
                    params[i] = key.method.parameters().get(i);
                }
                List<TypeVariable> typeVariables = key.method.typeParameters();
                return MethodInfo.create(classInfo, key.method.name(), params, returnType, key.method.flags(),
                        typeVariables.toArray(new TypeVariable[] {}),
                        key.method.exceptions().toArray(Type.EMPTY_ARRAY));
            });
        }
        // Interfaces
        for (Type interfaceType : classInfo.interfaceTypes()) {
            ClassInfo interfaceClassInfo = getClassByName(index, interfaceType.name());
            if (interfaceClassInfo != null) {
                addDelegatingMethods(index, interfaceClassInfo, methods);
            }
        }
        if (classInfo.superClassType() != null) {
            ClassInfo superClassInfo = getClassByName(index, classInfo.superName());
            if (superClassInfo != null) {
                addDelegatingMethods(index, superClassInfo, methods);
            }
        }
    }
}
 
Example 13
Source File: KogitoAssetsProcessor.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void generatePersistenceInfo(AppPaths appPaths,
                                     BuildProducer<GeneratedBeanBuildItem> generatedBeans,
                                     IndexView index,
                                     LaunchModeBuildItem launchMode,
                                     BuildProducer<NativeImageResourceBuildItem> resource,
                                     CurateOutcomeBuildItem curateOutcomeBuildItem) throws IOException, BootstrapDependencyProcessingException {

    ClassInfo persistenceClass = index
            .getClassByName(createDotName(persistenceFactoryClass));
    boolean usePersistence = persistenceClass != null;
    List<String> parameters = new ArrayList<>();
    if (usePersistence) {
        for (MethodInfo mi : persistenceClass.methods()) {
            if (mi.name().equals("<init>") && !mi.parameters().isEmpty()) {
                parameters = mi.parameters().stream().map(p -> p.name().toString()).collect(Collectors.toList());
                break;
            }
        }
    }

    Collection<GeneratedFile> generatedFiles = getGeneratedPersistenceFiles( appPaths, index, usePersistence, parameters );

    if (!generatedFiles.isEmpty()) {
        MemoryFileSystem trgMfs = new MemoryFileSystem();
        CompilationResult result = compile(appPaths, trgMfs, curateOutcomeBuildItem.getEffectiveModel(), generatedFiles, launchMode.getLaunchMode());
        register(appPaths, trgMfs, generatedBeans, GeneratedBeanBuildItem::new, launchMode.getLaunchMode(), result);
    }

    if (usePersistence) {
        resource.produce(new NativeImageResourceBuildItem("kogito-types.proto"));
    }
}
 
Example 14
Source File: AmazonLambdaProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BuildStep
List<AmazonLambdaBuildItem> discover(CombinedIndexBuildItem combinedIndexBuildItem,
        Optional<ProvidedAmazonLambdaHandlerBuildItem> providedLambda,
        BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildProducer,
        BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy,
        BuildProducer<ReflectiveClassBuildItem> reflectiveClassBuildItemBuildProducer) throws BuildException {

    Collection<ClassInfo> allKnownImplementors = combinedIndexBuildItem.getIndex().getAllKnownImplementors(REQUEST_HANDLER);
    allKnownImplementors.addAll(combinedIndexBuildItem.getIndex()
            .getAllKnownImplementors(REQUEST_STREAM_HANDLER));
    allKnownImplementors.addAll(combinedIndexBuildItem.getIndex()
            .getAllKnownSubclasses(SKILL_STREAM_HANDLER));

    if (allKnownImplementors.size() > 0 && providedLambda.isPresent()) {
        throw new BuildException(
                "Multiple handler classes.  You have a custom handler class and the " + providedLambda.get().getProvider()
                        + " extension.  Please remove one of them from your deployment.",
                Collections.emptyList());

    }
    AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder().setUnremovable();
    List<AmazonLambdaBuildItem> ret = new ArrayList<>();

    for (ClassInfo info : allKnownImplementors) {
        if (Modifier.isAbstract(info.flags())) {
            continue;
        }

        final DotName name = info.name();
        final String lambda = name.toString();
        builder.addBeanClass(lambda);
        reflectiveClassBuildItemBuildProducer.produce(new ReflectiveClassBuildItem(true, false, lambda));

        String cdiName = null;
        AnnotationInstance named = info.classAnnotation(NAMED);
        if (named != null) {
            cdiName = named.value().asString();
        }

        ClassInfo current = info;
        boolean done = false;
        boolean streamHandler = info.superName().equals(SKILL_STREAM_HANDLER) ? true : false;
        while (current != null && !done) {
            for (MethodInfo method : current.methods()) {
                if (method.name().equals("handleRequest")) {
                    if (method.parameters().size() == 3) {
                        streamHandler = true;
                        done = true;
                        break;
                    } else if (method.parameters().size() == 2
                            && !method.parameters().get(0).name().equals(DotName.createSimple(Object.class.getName()))) {
                        reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(method.parameters().get(0)));
                        reflectiveHierarchy.produce(new ReflectiveHierarchyBuildItem(method.returnType()));
                        done = true;
                        break;
                    }
                }
            }
            current = combinedIndexBuildItem.getIndex().getClassByName(current.superName());
        }
        ret.add(new AmazonLambdaBuildItem(lambda, cdiName, streamHandler));
    }
    additionalBeanBuildItemBuildProducer.produce(builder.build());
    reflectiveClassBuildItemBuildProducer
            .produce(new ReflectiveClassBuildItem(true, true, true, FunctionError.class));
    return ret;
}
 
Example 15
Source File: FragmentMethodsAdder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public void add(ClassCreator classCreator, String generatedClassName,
        List<DotName> customInterfaceNamesToImplement, Map<String, FieldDescriptor> customImplNameToHandle) {
    for (DotName customInterfaceToImplement : customInterfaceNamesToImplement) {
        String customImplementationClassName = FragmentMethodsUtil
                .getImplementationDotName(customInterfaceToImplement, index).toString();
        fragmentImplClassResolvedCallback.accept(customImplementationClassName);

        ClassInfo customInterfaceToImplementClassInfo = index.getClassByName(customInterfaceToImplement);
        if (customInterfaceToImplementClassInfo == null) {
            throw new IllegalArgumentException("Unable to implement" + customInterfaceToImplement
                    + " because it is not known - please make sure it's part of the Quarkus index");
        }

        for (MethodInfo methodToImplement : customInterfaceToImplementClassInfo.methods()) {
            // methods defined on the interface are implemented by forwarding them to the bean that implements them

            Object[] methodParameterTypes = new Object[methodToImplement.parameters().size()];
            for (int i = 0; i < methodToImplement.parameters().size(); i++) {
                methodParameterTypes[i] = methodToImplement.parameters().get(i).name().toString();
            }

            String methodReturnType = methodToImplement.returnType().name().toString();

            MethodDescriptor methodDescriptor = MethodDescriptor.ofMethod(generatedClassName, methodToImplement.name(),
                    methodReturnType, methodParameterTypes);

            if (!classCreator.getExistingMethods().contains(methodDescriptor)) {
                try (MethodCreator methodCreator = classCreator.getMethodCreator(methodDescriptor)) {
                    // obtain the bean from Arc
                    ResultHandle bean = methodCreator.readInstanceField(
                            customImplNameToHandle.get(customImplementationClassName), methodCreator.getThis());

                    ResultHandle[] methodParameterHandles = new ResultHandle[methodToImplement.parameters().size()];
                    for (int i = 0; i < methodToImplement.parameters().size(); i++) {
                        methodParameterHandles[i] = methodCreator.getMethodParam(i);
                    }

                    // delegate call to bean
                    ResultHandle result = methodCreator.invokeVirtualMethod(
                            MethodDescriptor.ofMethod(customImplementationClassName, methodToImplement.name(),
                                    methodReturnType, methodParameterTypes),
                            bean, methodParameterHandles);
                    if (void.class.getName().equals(methodReturnType)) {
                        methodCreator.returnValue(null);
                    } else {
                        methodCreator.returnValue(result);
                    }
                }
            }
        }
    }
}
 
Example 16
Source File: QuteProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
/**
 * Find a non-static non-synthetic method with the given name, matching number of params and assignable parameter types.
 * 
 * @param virtualMethod
 * @param clazz
 * @param expression
 * @param index
 * @param templateIdToPathFun
 * @param results
 * @return the method or null
 */
private AnnotationTarget findMethod(VirtualMethodPart virtualMethod, ClassInfo clazz, Expression expression,
        IndexView index, Function<String, String> templateIdToPathFun, Map<String, Match> results) {
    while (clazz != null) {
        for (MethodInfo method : clazz.methods()) {
            if (Modifier.isPublic(method.flags()) && !Modifier.isStatic(method.flags())
                    && !ValueResolverGenerator.isSynthetic(method.flags())
                    && method.name().equals(virtualMethod.getName())) {
                boolean isVarArgs = ValueResolverGenerator.isVarArgs(method);
                List<Type> parameters = method.parameters();
                int lastParamIdx = parameters.size() - 1;

                if (isVarArgs) {
                    // For varargs methods match the minimal number of params
                    if (lastParamIdx > virtualMethod.getParameters().size()) {
                        continue;
                    }
                } else {
                    if (virtualMethod.getParameters().size() != parameters.size()) {
                        // Number of params must be equal
                        continue;
                    }
                }

                // Check parameter types if available
                boolean matches = true;
                byte idx = 0;

                for (Expression param : virtualMethod.getParameters()) {
                    Match result = results.get(param.toOriginalString());
                    if (result != null && !result.isEmpty()) {
                        // Type info available - validate parameter type
                        Type paramType;
                        if (isVarArgs && idx >= lastParamIdx) {
                            // Replace the type for varargs methods
                            paramType = parameters.get(lastParamIdx).asArrayType().component();
                        } else {
                            paramType = parameters.get(idx);
                        }
                        if (!Types.isAssignableFrom(result.type,
                                paramType, index)) {
                            matches = false;
                            break;
                        }
                    } else {
                        LOGGER.debugf(
                                "Type info not available - skip validation for parameter [%s] of method [%s] for expression [%s] in template [%s] on line %s",
                                method.parameterName(idx),
                                method.declaringClass().name() + "#" + method,
                                expression.toOriginalString(),
                                templateIdToPathFun.apply(expression.getOrigin().getTemplateId()),
                                expression.getOrigin().getLine());
                    }
                    idx++;
                }
                return matches ? method : null;
            }
        }
        DotName superName = clazz.superName();
        if (superName == null || DotNames.OBJECT.equals(superName)) {
            clazz = null;
        } else {
            clazz = index.getClassByName(clazz.superName());
        }
    }
    return null;
}
 
Example 17
Source File: CustomQueryMethodsAdder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void generateCustomResultTypes(DotName interfaceName, DotName implName, Map<String, List<String>> queryMethods) {

        ClassInfo interfaceInfo = index.getClassByName(interfaceName);

        try (ClassCreator implClassCreator = ClassCreator.builder().classOutput(nonBeansClassOutput)
                .interfaces(interfaceName.toString()).className(implName.toString())
                .build()) {

            Map<String, FieldDescriptor> fields = new HashMap<>(3);

            for (MethodInfo method : interfaceInfo.methods()) {
                String getterName = method.name();
                String propertyName = JavaBeanUtil.getPropertyNameFromGetter(getterName);

                Type returnType = method.returnType();
                if (returnType.kind() == Type.Kind.VOID) {
                    throw new IllegalArgumentException("Method " + method.name() + " of interface " + interfaceName
                            + " is not a getter method since it returns void");
                }
                DotName fieldTypeName = getPrimitiveTypeName(returnType.name());

                FieldDescriptor field = implClassCreator.getFieldCreator(propertyName, fieldTypeName.toString())
                        .getFieldDescriptor();

                // create getter (based on the interface)
                try (MethodCreator getter = implClassCreator.getMethodCreator(getterName, returnType.toString())) {
                    getter.setModifiers(Modifier.PUBLIC);
                    getter.returnValue(getter.readInstanceField(field, getter.getThis()));
                }

                fields.put(propertyName.toLowerCase(), field);
            }

            // Add static methods to convert from Object[] to this type
            for (Map.Entry<String, List<String>> queryMethod : queryMethods.entrySet()) {
                try (MethodCreator convert = implClassCreator.getMethodCreator("convert_" + queryMethod.getKey(),
                        implName.toString(), Object[].class.getName())) {
                    convert.setModifiers(Modifier.STATIC);

                    ResultHandle newObject = convert.newInstance(MethodDescriptor.ofConstructor(implName.toString()));

                    // Use field names in the query-declared order
                    List<String> queryNames = queryMethod.getValue();

                    // Object[] is the only paramter: values are in column/declared order
                    ResultHandle array = convert.getMethodParam(0);

                    for (int i = 0; i < queryNames.size(); i++) {
                        FieldDescriptor f = fields.get(queryNames.get(i));
                        if (f == null) {
                            throw new IllegalArgumentException("@Query annotation for " + queryMethod.getKey()
                                    + " does not use fields from " + interfaceName);
                        } else {
                            convert.writeInstanceField(f, newObject,
                                    castReturnValue(convert, convert.readArrayValue(array, i), f.getType()));
                        }
                    }
                    convert.returnValue(newObject);
                }
            }
        }
    }
 
Example 18
Source File: TypeUtil.java    From serianalyzer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param methodReference
 * @param impl
 * @return
 */
static boolean implementsMethod ( MethodReference methodReference, ClassInfo impl ) {
    byte[] mnameb = methodReference.getMethod().getBytes(StandardCharsets.UTF_8);

    for ( MethodInfo i : impl.methods() ) {
        if ( ( i.flags() & Modifier.ABSTRACT ) != 0 ) {
            continue;
        }
        // this decodes the name every time
        byte[] inameb;
        try {
            inameb = (byte[]) NAME_BYTES.invoke(METHOD_INTERNAL.get(i));
        }
        catch ( Throwable e ) {
            e.printStackTrace();
            return false;
        }
        if ( Arrays.equals(mnameb, inameb) ) {
            // ACC_VARARGS
            if ( ( i.flags() & 0x80 ) != 0 ) {
                return true;
            }
            String sig2;
            try {
                sig2 = makeSignature(i, false);
                if ( sig2.equals(methodReference.getSignature()) ) {
                    return true;
                }

                if ( log.isTraceEnabled() ) {
                    log.trace("Signature mismatch " + methodReference.getSignature() + " vs " + sig2); //$NON-NLS-1$ //$NON-NLS-2$
                }

                if ( "<init>".equals(methodReference.getMethod()) ) { //$NON-NLS-1$
                    sig2 = makeSignature(i, true);
                    if ( sig2.equals(methodReference.getSignature()) ) {
                        return true;
                    }
                }
            }
            catch ( SerianalyzerException e1 ) {
                log.warn("Failed to generate signature", e1); //$NON-NLS-1$
            }

            return true;
        }
    }
    if ( log.isTraceEnabled() ) {
        log.trace("Not found in " + impl.name() + ": " + methodReference); //$NON-NLS-1$//$NON-NLS-2$
    }
    return false;
}
 
Example 19
Source File: SpringWebProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BuildStep(onlyIf = IsDevelopment.class)
@Record(STATIC_INIT)
public void registerWithDevModeNotFoundMapper(BeanArchiveIndexBuildItem beanArchiveIndexBuildItem,
        ExceptionMapperRecorder recorder) {
    IndexView index = beanArchiveIndexBuildItem.getIndex();
    Collection<AnnotationInstance> restControllerAnnotations = index.getAnnotations(REST_CONTROLLER_ANNOTATION);
    if (restControllerAnnotations.isEmpty()) {
        return;
    }

    Map<String, NonJaxRsClassMappings> nonJaxRsPaths = new HashMap<>();
    for (AnnotationInstance restControllerInstance : restControllerAnnotations) {
        String basePath = "/";
        ClassInfo restControllerAnnotatedClass = restControllerInstance.target().asClass();

        AnnotationInstance requestMappingInstance = restControllerAnnotatedClass.classAnnotation(REQUEST_MAPPING);
        if (requestMappingInstance != null) {
            String basePathFromAnnotation = getMappingValue(requestMappingInstance);
            if (basePathFromAnnotation != null) {
                basePath = basePathFromAnnotation;
            }
        }
        Map<String, String> methodNameToPath = new HashMap<>();
        NonJaxRsClassMappings nonJaxRsClassMappings = new NonJaxRsClassMappings();
        nonJaxRsClassMappings.setMethodNameToPath(methodNameToPath);
        nonJaxRsClassMappings.setBasePath(basePath);

        List<MethodInfo> methods = restControllerAnnotatedClass.methods();

        // go through each of the methods and see if there are any mapping Spring annotation from which to get the path
        METHOD: for (MethodInfo method : methods) {
            String methodName = method.name();
            String methodPath;
            // go through each of the annotations that can be used to make a method handle an http request
            for (DotName mappingClass : MAPPING_ANNOTATIONS) {
                AnnotationInstance mappingClassAnnotation = method.annotation(mappingClass);
                if (mappingClassAnnotation != null) {
                    methodPath = getMappingValue(mappingClassAnnotation);
                    if (methodPath == null) {
                        methodPath = ""; // ensure that no nasty null values show up in the output
                    } else if (!methodPath.startsWith("/")) {
                        methodPath = "/" + methodPath;
                    }
                    // record the mapping of method to the http path
                    methodNameToPath.put(methodName, methodPath);
                    continue METHOD;
                }
            }
        }

        // if there was at least one controller method, add the controller since it contains methods that handle http requests
        if (!methodNameToPath.isEmpty()) {
            nonJaxRsPaths.put(restControllerAnnotatedClass.name().toString(), nonJaxRsClassMappings);
        }
    }

    if (!nonJaxRsPaths.isEmpty()) {
        recorder.nonJaxRsClassNameToMethodPaths(nonJaxRsPaths);
    }
}
 
Example 20
Source File: ResteasyServerCommonProcessor.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private Set<DotName> findSubresources(IndexView index, Map<DotName, ClassInfo> scannedResources) {
    // First identify sub-resource candidates
    Set<DotName> subresources = new HashSet<>();
    for (DotName annotation : METHOD_ANNOTATIONS) {
        Collection<AnnotationInstance> annotationInstances = index.getAnnotations(annotation);
        for (AnnotationInstance annotationInstance : annotationInstances) {
            DotName declaringClassName = annotationInstance.target().asMethod().declaringClass().name();
            if (scannedResources.containsKey(declaringClassName)) {
                // Skip resource classes
                continue;
            }
            subresources.add(declaringClassName);
        }
    }
    if (!subresources.isEmpty()) {
        // Collect sub-resource locator return types
        Set<DotName> subresourceLocatorTypes = new HashSet<>();
        for (ClassInfo resourceClass : scannedResources.values()) {
            ClassInfo clazz = resourceClass;
            while (clazz != null) {
                for (MethodInfo method : clazz.methods()) {
                    if (method.hasAnnotation(ResteasyDotNames.PATH)) {
                        subresourceLocatorTypes.add(method.returnType().name());
                    }
                }
                if (clazz.superName().equals(DotNames.OBJECT)) {
                    clazz = null;
                } else {
                    clazz = index.getClassByName(clazz.superName());
                }
            }
        }
        // Remove false positives
        for (Iterator<DotName> iterator = subresources.iterator(); iterator.hasNext();) {
            DotName subresource = iterator.next();
            for (DotName type : subresourceLocatorTypes) {
                // Sub-resource may be a subclass of a locator return type
                if (!subresource.equals(type)
                        && index.getAllKnownSubclasses(type).stream().noneMatch(c -> c.name().equals(subresource))) {
                    iterator.remove();
                    break;
                }
            }
        }
    }
    log.trace("Sub-resources found: " + subresources);
    return subresources;
}