Search in sources :

Example 11 with AnnotationDescr

use of org.drools.drl.ast.descr.AnnotationDescr in project drools by kiegroup.

the class ClassDefinitionFactory method wireAnnotationDefs.

protected boolean wireAnnotationDefs(AbstractClassTypeDeclarationDescr typeDescr, ClassDefinition def, TypeResolver resolver) {
    for (AnnotationDescr annotationDescr : typeDescr.getAnnotations()) {
        Class annotation;
        try {
            annotation = annotationDescr.getFullyQualifiedName() != null ? resolver.resolveType(annotationDescr.getFullyQualifiedName()) : null;
        } catch (ClassNotFoundException e) {
            continue;
        }
        if (annotation != null && annotation.isAnnotation()) {
            try {
                AnnotationDefinition annotationDefinition = AnnotationDefinition.build(annotation, annotationDescr.getValueMap(), resolver);
                def.addAnnotation(annotationDefinition);
            } catch (NoSuchMethodException nsme) {
                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "Annotated type " + typeDescr.getType().getFullName() + "  - undefined property in @annotation " + annotationDescr.getName() + ": " + nsme.getMessage() + ";"));
            }
        }
        if (annotation == null || annotation.getCanonicalName().startsWith("org.kie.api.definition.type")) {
            def.addMetaData(annotationDescr.getName(), annotationDescr.getSingleValue());
        }
    }
    return true;
}
Also used : AnnotationDefinition(org.drools.core.factmodel.AnnotationDefinition) TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) AnnotationDescr(org.drools.drl.ast.descr.AnnotationDescr)

Example 12 with AnnotationDescr

use of org.drools.drl.ast.descr.AnnotationDescr in project drools by kiegroup.

the class ModelGenerator method ruleMetaAttributes.

/**
 * Build a list of method calls, representing each needed {@link org.drools.model.impl.RuleBuilder#metadata(String, Object)}
 * starting from a drools-compiler {@link RuleDescr}.<br/>
 * Based on {@link org.drools.modelcompiler.KiePackagesBuilder#setRuleMetaAttributes(Rule, RuleImpl)} the reserved annotation keywords are:
 * Propagation, All, Direct.
 */
private static List<MethodCallExpr> ruleMetaAttributes(RuleContext context, RuleDescr ruleDescr) {
    List<MethodCallExpr> ruleMetaAttributes = new ArrayList<>();
    for (String metaAttr : ruleDescr.getAnnotationNames()) {
        MethodCallExpr metaAttributeCall = new MethodCallExpr(METADATA_CALL);
        metaAttributeCall.addArgument(toStringLiteral(metaAttr));
        AnnotationDescr ad = ruleDescr.getAnnotation(metaAttr);
        String adFqn = ad.getFullyQualifiedName();
        if ("Propagation".equals(metaAttr)) {
            // legacy case, as explained in the javadoc annotation above, ref. DROOLS-5685
            metaAttributeCall.addArgument(parseExpression(org.kie.api.definition.rule.Propagation.Type.class.getCanonicalName() + "." + ad.getSingleValueAsString()));
        } else if (adFqn != null) {
            AnnotationDefinition annotationDefinition;
            try {
                annotationDefinition = AnnotationDefinition.build(context.getTypeResolver().resolveType(adFqn), ad.getValueMap(), context.getTypeResolver());
            } catch (NoSuchMethodException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            if (annotationDefinition.getValues().size() == 1 && annotationDefinition.getValues().containsKey(AnnotationDescr.VALUE)) {
                Object annValue = annotationDefinition.getPropertyValue(AnnotationDescr.VALUE);
                metaAttributeCall.addArgument(toStringLiteral(annValue.toString()));
            } else {
                Map<String, Object> map = new HashMap<>(annotationDefinition.getValues().size());
                for (String key : annotationDefinition.getValues().keySet()) {
                    map.put(key, annotationDefinition.getPropertyValue(key));
                }
                metaAttributeCall.addArgument(objectAsJPExpression(map));
            }
        } else {
            if (ad.hasValue()) {
                if (ad.getValueMap().size() == 1) {
                    metaAttributeCall.addArgument(annotationSingleValueExpression(ad));
                } else {
                    metaAttributeCall.addArgument(objectAsJPExpression(ad.getValueMap()));
                }
            } else {
                metaAttributeCall.addArgument(new NullLiteralExpr());
            }
        }
        ruleMetaAttributes.add(metaAttributeCall);
    }
    return ruleMetaAttributes;
}
Also used : AnnotationDefinition(org.drools.core.factmodel.AnnotationDefinition) ArrayList(java.util.ArrayList) AnnotationDescr(org.drools.drl.ast.descr.AnnotationDescr) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) Map(java.util.Map) HashMap(java.util.HashMap) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 13 with AnnotationDescr

use of org.drools.drl.ast.descr.AnnotationDescr in project drools by kiegroup.

the class DescrTypeDefinition method processClassAnnotations.

private void processClassAnnotations() {
    for (AnnotationDescr ann : typeDeclarationDescr.getAnnotations()) {
        if (ann.getName().equals(SERIAL_VERSION_UID)) {
            DescrFieldDefinition serialVersionField = new DescrFieldDefinition(SERIAL_VERSION_UID, "long", ann.getValue("value").toString()).setFinal(true).setStatic(true);
            fieldDefinition.add(serialVersionField);
        }
        try {
            annotations.add(DescrAnnotationDefinition.fromDescr(typeResolver, ann));
        } catch (UnkownAnnotationClassException | UnknownKeysInAnnotation e) {
        // Do not do anything
        }
    }
}
Also used : AnnotationDescr(org.drools.drl.ast.descr.AnnotationDescr)

Example 14 with AnnotationDescr

use of org.drools.drl.ast.descr.AnnotationDescr in project drools by kiegroup.

the class DescrTypeDefinition method typeFieldsSortedByPosition.

private List<TypeFieldDescr> typeFieldsSortedByPosition(List<FieldDefinition> inheritedFields) {
    Collection<TypeFieldDescr> typeFields = typeDeclarationDescr.getFields().values().stream().filter(f -> inheritedFields.stream().map(FieldDefinition::getFieldName).noneMatch(name -> name.equals(f.getFieldName()))).collect(Collectors.toList());
    TypeFieldDescr[] sortedTypes = new TypeFieldDescr[typeFields.size()];
    List<TypeFieldDescr> nonPositionalFields = new ArrayList<>();
    for (TypeFieldDescr descr : typeFields) {
        AnnotationDescr ann = descr.getAnnotation("Position");
        if (ann == null) {
            nonPositionalFields.add(descr);
        } else {
            int pos = Integer.parseInt(ann.getValue().toString());
            if (pos >= sortedTypes.length) {
                errors.add(new TypeDeclarationError(typeDeclarationDescr, "Out of range position " + pos + " for field '" + descr.getFieldName() + "' on class " + typeDeclarationDescr.getTypeName()));
            } else if (sortedTypes[pos] != null) {
                errors.add(new TypeDeclarationError(typeDeclarationDescr, "Duplicated position " + pos + " for field '" + descr.getFieldName() + "' on class " + typeDeclarationDescr.getTypeName()));
            } else {
                sortedTypes[pos] = descr;
            }
        }
    }
    if (!errors.isEmpty()) {
        return Collections.emptyList();
    }
    int counter = 0;
    for (TypeFieldDescr descr : nonPositionalFields) {
        for (; sortedTypes[counter] != null; counter++) ;
        sortedTypes[counter++] = descr;
    }
    return Arrays.asList(sortedTypes);
}
Also used : QualifiedName(org.drools.drl.ast.descr.QualifiedName) Optional.empty(java.util.Optional.empty) Arrays(java.util.Arrays) AnnotationDescr(org.drools.drl.ast.descr.AnnotationDescr) Optional.of(java.util.Optional.of) TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) ArrayList(java.util.ArrayList) FieldDefinition(org.drools.modelcompiler.builder.generator.declaredtype.api.FieldDefinition) TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) PackageDescr(org.drools.drl.ast.descr.PackageDescr) Optional.ofNullable(java.util.Optional.ofNullable) Collection(java.util.Collection) TypeDefinition(org.drools.modelcompiler.builder.generator.declaredtype.api.TypeDefinition) StreamUtils.optionalToStream(org.drools.modelcompiler.util.StreamUtils.optionalToStream) MethodDefinition(org.drools.modelcompiler.builder.generator.declaredtype.api.MethodDefinition) AnnotationDefinition(org.drools.modelcompiler.builder.generator.declaredtype.api.AnnotationDefinition) Collectors(java.util.stream.Collectors) AnnotationDeclarationError(org.drools.compiler.compiler.AnnotationDeclarationError) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) TypeDeclarationDescr(org.drools.drl.ast.descr.TypeDeclarationDescr) DroolsError(org.drools.drl.parser.DroolsError) Optional(java.util.Optional) Collections(java.util.Collections) POJOGenerator.quote(org.drools.modelcompiler.builder.generator.declaredtype.POJOGenerator.quote) TypeResolver(org.drools.modelcompiler.builder.generator.declaredtype.api.TypeResolver) TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) ArrayList(java.util.ArrayList) AnnotationDescr(org.drools.drl.ast.descr.AnnotationDescr)

Example 15 with AnnotationDescr

use of org.drools.drl.ast.descr.AnnotationDescr in project drools by kiegroup.

the class ClassDefinitionFactory method sortFields.

private static List<FieldDefinition> sortFields(Map<String, TypeFieldDescr> fields, TypeResolver typeResolver, KnowledgeBuilderImpl kbuilder) {
    List<FieldDefinition> fieldDefs = new ArrayList<>(fields.size());
    int maxDeclaredPos = 0;
    BitSet occupiedPositions = new BitSet(fields.size());
    for (TypeFieldDescr field : fields.values()) {
        GenericTypeDefinition genericType = field.getPattern().getGenericType().map(type -> TypeDeclarationUtils.toBuildableType(type, kbuilder != null ? kbuilder.getRootClassLoader() : null));
        FieldDefinition fieldDef = new FieldDefinition(field.getFieldName(), genericType);
        fieldDefs.add(fieldDef);
        if (field.hasOverride()) {
            fieldDef.setOverriding(field.getOverriding().getPattern().getObjectType());
        }
        fieldDef.setInherited(field.isInherited());
        fieldDef.setRecursive(field.isRecursive());
        fieldDef.setInitExpr(TypeDeclarationUtils.rewriteInitExprWithImports(field.getInitExpr(), typeResolver));
        if (field.getIndex() >= 0) {
            int pos = field.getIndex();
            occupiedPositions.set(pos);
            maxDeclaredPos = Math.max(maxDeclaredPos, pos);
            fieldDef.addMetaData("position", pos);
        } else {
            Position position = getTypedAnnotation(field, Position.class);
            if (position != null) {
                int pos = position.value();
                field.setIndex(pos);
                occupiedPositions.set(pos);
                maxDeclaredPos = Math.max(maxDeclaredPos, pos);
                fieldDef.addMetaData("position", pos);
            }
        }
        if (field.hasAnnotation(Key.class)) {
            fieldDef.setKey(true);
            fieldDef.addMetaData("key", null);
        }
        for (AnnotationDescr annotationDescr : field.getAnnotations()) {
            if (annotationDescr.getFullyQualifiedName() == null) {
                if (annotationDescr.isStrict()) {
                    kbuilder.addBuilderResult(new TypeDeclarationError(field, "Unknown annotation @" + annotationDescr.getName() + " on field " + field.getFieldName()));
                } else {
                    // Annotation is custom metadata
                    fieldDef.addMetaData(annotationDescr.getName(), annotationDescr.getSingleValue());
                    continue;
                }
            }
            Annotation annotation = AnnotationFactory.buildAnnotation(typeResolver, annotationDescr);
            if (annotation != null) {
                try {
                    AnnotationDefinition annotationDefinition = AnnotationDefinition.build(annotation.annotationType(), field.getAnnotation(annotationDescr.getFullyQualifiedName()).getValueMap(), typeResolver);
                    fieldDef.addAnnotation(annotationDefinition);
                } catch (Exception e) {
                    kbuilder.addBuilderResult(new TypeDeclarationError(field, "Annotated field " + field.getFieldName() + "  - undefined property in @annotation " + annotationDescr.getName() + ": " + e.getMessage() + ";"));
                }
            } else {
                if (annotationDescr.isStrict()) {
                    kbuilder.addBuilderResult(new TypeDeclarationError(field, "Unknown annotation @" + annotationDescr.getName() + " on field " + field.getFieldName()));
                }
            }
        }
        fieldDef.setDeclIndex(field.getIndex());
    }
    int curr = 0;
    for (FieldDefinition fieldDef : fieldDefs) {
        if (fieldDef.getDeclIndex() < 0) {
            int freePos = occupiedPositions.nextClearBit(0);
            if (freePos < maxDeclaredPos) {
                occupiedPositions.set(freePos);
            } else {
                freePos = maxDeclaredPos + 1;
            }
            fieldDef.setPriority(freePos * 256 + curr++);
        } else {
            fieldDef.setPriority(fieldDef.getDeclIndex() * 256 + curr++);
        }
    }
    Collections.sort(fieldDefs);
    return fieldDefs;
}
Also used : AnnotationDefinition(org.drools.core.factmodel.AnnotationDefinition) Position(org.kie.api.definition.type.Position) FieldDefinition(org.drools.core.factmodel.FieldDefinition) ArrayList(java.util.ArrayList) BitSet(java.util.BitSet) AnnotationDescr(org.drools.drl.ast.descr.AnnotationDescr) AnnotationFactory.getTypedAnnotation(org.drools.compiler.rule.builder.util.AnnotationFactory.getTypedAnnotation) Annotation(java.lang.annotation.Annotation) IOException(java.io.IOException) TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) GenericTypeDefinition(org.kie.internal.definition.GenericTypeDefinition)

Aggregations

AnnotationDescr (org.drools.drl.ast.descr.AnnotationDescr)26 BaseDescr (org.drools.drl.ast.descr.BaseDescr)8 ConstraintConnectiveDescr (org.drools.drl.ast.descr.ConstraintConnectiveDescr)8 AnnotationDefinition (org.drools.core.factmodel.AnnotationDefinition)5 ArrayList (java.util.ArrayList)3 TypeDeclarationError (org.drools.compiler.compiler.TypeDeclarationError)3 TypeDeclarationDescr (org.drools.drl.ast.descr.TypeDeclarationDescr)3 TypeFieldDescr (org.drools.drl.ast.descr.TypeFieldDescr)3 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 AnnotationDeclarationError (org.drools.compiler.compiler.AnnotationDeclarationError)2 FieldDefinition (org.drools.core.factmodel.FieldDefinition)2 QualifiedName (org.drools.drl.ast.descr.QualifiedName)2 NullLiteralExpr (com.github.javaparser.ast.expr.NullLiteralExpr)1 IOException (java.io.IOException)1 Annotation (java.lang.annotation.Annotation)1 Arrays (java.util.Arrays)1 BitSet (java.util.BitSet)1