Search in sources :

Example 11 with AnnotationDescr

use of org.drools.compiler.lang.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}.
 */
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(new StringLiteralExpr(metaAttr));
        AnnotationDescr ad = ruleDescr.getAnnotation(metaAttr);
        String adFqn = ad.getFullyQualifiedName();
        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(new StringLiteralExpr(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.getValues().size() == 1) {
                    metaAttributeCall.addArgument(objectAsJPExpression(resolveValue(ad.getSingleValueAsString())));
                } else {
                    metaAttributeCall.addArgument(objectAsJPExpression(ad.getValueMap()));
                }
            } else {
                metaAttributeCall.addArgument(new NullLiteralExpr());
            }
        }
        ruleMetaAttributes.add(metaAttributeCall);
    }
    return ruleMetaAttributes;
}
Also used : AnnotationDefinition(org.drools.core.factmodel.AnnotationDefinition) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) NullLiteralExpr(org.drools.javaparser.ast.expr.NullLiteralExpr) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 12 with AnnotationDescr

use of org.drools.compiler.lang.descr.AnnotationDescr in project drools by kiegroup.

the class POJOGenerator method toClassDeclaration.

/**
 * @param packageDescr
 */
public static ClassOrInterfaceDeclaration toClassDeclaration(TypeDeclarationDescr typeDeclaration, PackageDescr packageDescr) {
    EnumSet<Modifier> classModifiers = EnumSet.of(Modifier.PUBLIC);
    String generatedClassName = typeDeclaration.getTypeName();
    ClassOrInterfaceDeclaration generatedClass = new ClassOrInterfaceDeclaration(classModifiers, false, generatedClassName);
    generatedClass.addImplementedType(GeneratedFact.class.getName());
    // Ref: {@link org.drools.core.factmodel.DefaultBeanClassBuilder} by default always receive is Serializable.
    generatedClass.addImplementedType(Serializable.class.getName());
    boolean hasSuper = typeDeclaration.getSuperTypeName() != null;
    if (hasSuper) {
        generatedClass.addExtendedType(typeDeclaration.getSuperTypeName());
    }
    List<AnnotationDescr> softAnnotations = new ArrayList<>();
    for (AnnotationDescr ann : typeDeclaration.getAnnotations()) {
        final String annFqn = Optional.ofNullable(ann.getFullyQualifiedName()).orElse(Optional.ofNullable(predefinedClassLevelAnnotation.get(ann.getName())).map(Class::getCanonicalName).orElse(null));
        if (annFqn != null) {
            NormalAnnotationExpr annExpr = generatedClass.addAndGetAnnotation(annFqn);
            ann.getValueMap().forEach((k, v) -> annExpr.addPair(k, getAnnotationValue(annFqn, k, v.toString())));
        } else {
            softAnnotations.add(ann);
        }
    }
    if (softAnnotations.size() > 0) {
        String softAnnDictionary = softAnnotations.stream().map(a -> "<dt>" + a.getName() + "</dt><dd>" + a.getValuesAsString() + "</dd>").collect(Collectors.joining());
        JavadocComment generatedClassJavadoc = new JavadocComment("<dl>" + softAnnDictionary + "</dl>");
        generatedClass.setJavadocComment(generatedClassJavadoc);
    }
    // No-args ctor
    generatedClass.addConstructor(Modifier.PUBLIC);
    List<Statement> equalsFieldStatement = new ArrayList<>();
    List<Statement> hashCodeFieldStatement = new ArrayList<>();
    List<String> toStringFieldStatement = new ArrayList<>();
    List<TypeFieldDescr> keyFields = new ArrayList<>();
    Collection<TypeFieldDescr> inheritedFields = findInheritedDeclaredFields(typeDeclaration, packageDescr);
    Collection<TypeFieldDescr> typeFields = typeDeclaration.getFields().values();
    if (!inheritedFields.isEmpty() || !typeDeclaration.getFields().isEmpty()) {
        ConstructorDeclaration fullArgumentsCtor = generatedClass.addConstructor(Modifier.PUBLIC);
        NodeList<Statement> ctorFieldStatement = NodeList.nodeList();
        MethodCallExpr superCall = new MethodCallExpr(null, "super");
        for (TypeFieldDescr typeFieldDescr : inheritedFields) {
            String fieldName = typeFieldDescr.getFieldName();
            addCtorArg(fullArgumentsCtor, typeFieldDescr.getPattern().getObjectType(), fieldName);
            superCall.addArgument(fieldName);
            if (typeFieldDescr.getAnnotation("key") != null) {
                keyFields.add(typeFieldDescr);
            }
        }
        ctorFieldStatement.add(new ExpressionStmt(superCall));
        int position = inheritedFields.size();
        for (TypeFieldDescr typeFieldDescr : typeFields) {
            String fieldName = typeFieldDescr.getFieldName();
            Type returnType = addCtorArg(fullArgumentsCtor, typeFieldDescr.getPattern().getObjectType(), fieldName);
            FieldDeclaration field = generatedClass.addField(returnType, fieldName, Modifier.PRIVATE);
            field.createSetter();
            field.addAndGetAnnotation(Position.class.getName()).addPair("value", "" + position++);
            MethodDeclaration getter = field.createGetter();
            equalsFieldStatement.add(generateEqualsForField(getter, fieldName));
            hashCodeFieldStatement.addAll(generateHashCodeForField(getter, fieldName));
            ctorFieldStatement.add(replaceFieldName(parseStatement("this.__fieldName = __fieldName;"), fieldName));
            toStringFieldStatement.add(format("+ {0}+{1}", quote(fieldName + "="), fieldName));
            if (typeFieldDescr.getAnnotation("key") != null) {
                keyFields.add(typeFieldDescr);
            }
        }
        fullArgumentsCtor.setBody(new BlockStmt(ctorFieldStatement));
        if (!keyFields.isEmpty() && keyFields.size() != inheritedFields.size() + typeFields.size()) {
            ConstructorDeclaration keyArgumentsCtor = generatedClass.addConstructor(Modifier.PUBLIC);
            NodeList<Statement> ctorKeyFieldStatement = NodeList.nodeList();
            MethodCallExpr keySuperCall = new MethodCallExpr(null, "super");
            ctorKeyFieldStatement.add(new ExpressionStmt(keySuperCall));
            for (TypeFieldDescr typeFieldDescr : keyFields) {
                String fieldName = typeFieldDescr.getFieldName();
                addCtorArg(keyArgumentsCtor, typeFieldDescr.getPattern().getObjectType(), fieldName);
                if (typeDeclaration.getFields().get(fieldName) != null) {
                    ctorKeyFieldStatement.add(replaceFieldName(parseStatement("this.__fieldName = __fieldName;"), fieldName));
                } else {
                    keySuperCall.addArgument(fieldName);
                }
            }
            keyArgumentsCtor.setBody(new BlockStmt(ctorKeyFieldStatement));
        }
        if (hasSuper) {
            generatedClass.addMember(generateEqualsMethod(generatedClassName, equalsFieldStatement));
            generatedClass.addMember(generateHashCodeMethod(hashCodeFieldStatement));
        }
    }
    generatedClass.addMember(generateToStringMethod(generatedClassName, toStringFieldStatement));
    return generatedClass;
}
Also used : JavaParser.parseStatement(org.drools.javaparser.JavaParser.parseStatement) ClassOrInterfaceType(org.drools.javaparser.ast.type.ClassOrInterfaceType) Primitive(org.drools.javaparser.ast.type.PrimitiveType.Primitive) JavaParser(org.drools.javaparser.JavaParser) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) HashMap(java.util.HashMap) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) NodeList.nodeList(org.drools.javaparser.ast.NodeList.nodeList) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) ArrayList(java.util.ArrayList) JavadocComment(org.drools.javaparser.ast.comments.JavadocComment) JavaParserCompiler.compileAll(org.drools.modelcompiler.builder.JavaParserCompiler.compileAll) FieldDeclaration(org.drools.javaparser.ast.body.FieldDeclaration) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr) MessageFormat.format(java.text.MessageFormat.format) Map(java.util.Map) MethodDeclaration(org.drools.javaparser.ast.body.MethodDeclaration) FieldAccessExpr(org.drools.javaparser.ast.expr.FieldAccessExpr) ExpressionStmt(org.drools.javaparser.ast.stmt.ExpressionStmt) PrimitiveType(org.drools.javaparser.ast.type.PrimitiveType) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) Statement(org.drools.javaparser.ast.stmt.Statement) EnumSet(java.util.EnumSet) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) ConstructorDeclaration(org.drools.javaparser.ast.body.ConstructorDeclaration) PackageModel(org.drools.modelcompiler.builder.PackageModel) TypeResolver(org.kie.soup.project.datamodel.commons.types.TypeResolver) Collection(java.util.Collection) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) TypeDeclarationDescr(org.drools.compiler.lang.descr.TypeDeclarationDescr) NormalAnnotationExpr(org.drools.javaparser.ast.expr.NormalAnnotationExpr) GeneratedFact(org.drools.core.factmodel.GeneratedFact) Collectors(java.util.stream.Collectors) NameExpr(org.drools.javaparser.ast.expr.NameExpr) StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) Serializable(java.io.Serializable) Type(org.drools.javaparser.ast.type.Type) List(java.util.List) NodeList(org.drools.javaparser.ast.NodeList) Position(org.kie.api.definition.type.Position) Optional(java.util.Optional) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) GeneratedClassWithPackage(org.drools.modelcompiler.builder.GeneratedClassWithPackage) Role(org.kie.api.definition.type.Role) Collections(java.util.Collections) Modifier(org.drools.javaparser.ast.Modifier) Serializable(java.io.Serializable) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) ArrayList(java.util.ArrayList) ExpressionStmt(org.drools.javaparser.ast.stmt.ExpressionStmt) FieldDeclaration(org.drools.javaparser.ast.body.FieldDeclaration) JavadocComment(org.drools.javaparser.ast.comments.JavadocComment) ConstructorDeclaration(org.drools.javaparser.ast.body.ConstructorDeclaration) NormalAnnotationExpr(org.drools.javaparser.ast.expr.NormalAnnotationExpr) Modifier(org.drools.javaparser.ast.Modifier) JavaParser.parseStatement(org.drools.javaparser.JavaParser.parseStatement) Statement(org.drools.javaparser.ast.stmt.Statement) MethodDeclaration(org.drools.javaparser.ast.body.MethodDeclaration) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) ClassOrInterfaceType(org.drools.javaparser.ast.type.ClassOrInterfaceType) PrimitiveType(org.drools.javaparser.ast.type.PrimitiveType) Type(org.drools.javaparser.ast.type.Type) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) GeneratedFact(org.drools.core.factmodel.GeneratedFact) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 13 with AnnotationDescr

use of org.drools.compiler.lang.descr.AnnotationDescr in project drools by kiegroup.

the class POJOGenerator method processType.

private static void processType(PackageModel packageModel, TypeDeclarationDescr typeDescr, Class<?> type) {
    MethodCallExpr typeMetaDataCall = registerTypeMetaData(type.getPackage().getName(), type.getSimpleName());
    for (AnnotationDescr ann : typeDescr.getAnnotations()) {
        typeMetaDataCall = new MethodCallExpr(typeMetaDataCall, "addAnnotation");
        typeMetaDataCall.addArgument(new StringLiteralExpr(ann.getName()));
        for (Map.Entry<String, Object> entry : ann.getValueMap().entrySet()) {
            MethodCallExpr annotationValueCall = new MethodCallExpr(null, "annotationValue");
            annotationValueCall.addArgument(new StringLiteralExpr(entry.getKey()));
            annotationValueCall.addArgument(new StringLiteralExpr(entry.getValue().toString()));
            typeMetaDataCall.addArgument(annotationValueCall);
        }
    }
    packageModel.addTypeMetaDataExpressions(typeMetaDataCall);
}
Also used : StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) HashMap(java.util.HashMap) Map(java.util.Map) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 14 with AnnotationDescr

use of org.drools.compiler.lang.descr.AnnotationDescr in project drools by kiegroup.

the class RuleContext method findUnitClass.

private void findUnitClass() {
    if (descr == null) {
        return;
    }
    String unitName = null;
    AnnotationDescr unitAnn = descr.getAnnotation("Unit");
    if (unitAnn != null) {
        unitName = (String) unitAnn.getValue();
        unitName = unitName.substring(0, unitName.length() - ".class".length());
    } else if (descr.getUnit() != null) {
        unitName = descr.getUnit().getTarget();
    }
    if (unitName != null) {
        try {
            Class<? extends RuleUnit> unitClass = (Class<? extends RuleUnit>) getTypeResolver().resolveType(unitName);
            ruleUnitDescr = ruleUnitDescrCache.computeIfAbsent(unitClass, RuleUnitDescr::new);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
Also used : RuleUnit(org.kie.api.runtime.rule.RuleUnit) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr)

Example 15 with AnnotationDescr

use of org.drools.compiler.lang.descr.AnnotationDescr in project drools by kiegroup.

the class RuleModelDRLPersistenceImpl method getRuleModel.

private RuleModel getRuleModel(final ExpandedDRLInfo expandedDRLInfo, final PackageDataModelOracle dmo, final Collection<RuleModelIActionPersistenceExtension> extensions) throws RuleModelDRLPersistenceException {
    // De-serialize model
    RuleDescr ruleDescr = parseDrl(expandedDRLInfo);
    RuleModel model = new RuleModel();
    model.name = ruleDescr.getName();
    model.parentName = ruleDescr.getParentName();
    for (AnnotationDescr annotation : ruleDescr.getAnnotations()) {
        model.addMetadata(new RuleMetadata(annotation.getName(), annotation.getValuesAsString()));
    }
    // De-serialize Package name
    final String packageName = PackageNameParser.parsePackageName(expandedDRLInfo.plainDrl);
    model.setPackageName(packageName);
    // De-serialize imports
    final Imports imports = ImportsParser.parseImports(expandedDRLInfo.plainDrl);
    for (Import item : imports.getImports()) {
        model.getImports().addImport(item);
    }
    boolean isJavaDialect = parseAttributes(model, ruleDescr.getAttributes());
    Map<String, String> boundParams = parseLhs(model, ruleDescr.getLhs(), isJavaDialect, expandedDRLInfo, dmo);
    parseRhs(model, expandedDRLInfo.consequence != null ? expandedDRLInfo.consequence : (String) ruleDescr.getConsequence(), isJavaDialect, boundParams, expandedDRLInfo, dmo, extensions);
    return model;
}
Also used : Import(org.kie.soup.project.datamodel.imports.Import) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) RuleMetadata(org.drools.workbench.models.datamodel.rule.RuleMetadata) Imports(org.kie.soup.project.datamodel.imports.Imports) RuleModel(org.drools.workbench.models.datamodel.rule.RuleModel) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr)

Aggregations

AnnotationDescr (org.drools.compiler.lang.descr.AnnotationDescr)27 AnnotatedBaseDescr (org.drools.compiler.lang.descr.AnnotatedBaseDescr)8 BaseDescr (org.drools.compiler.lang.descr.BaseDescr)8 ConstraintConnectiveDescr (org.drools.compiler.lang.descr.ConstraintConnectiveDescr)8 HashMap (java.util.HashMap)5 AnnotationDefinition (org.drools.core.factmodel.AnnotationDefinition)5 ArrayList (java.util.ArrayList)4 TypeDeclarationDescr (org.drools.compiler.lang.descr.TypeDeclarationDescr)4 TypeFieldDescr (org.drools.compiler.lang.descr.TypeFieldDescr)4 Map (java.util.Map)3 MethodCallExpr (org.drools.javaparser.ast.expr.MethodCallExpr)3 StringLiteralExpr (org.drools.javaparser.ast.expr.StringLiteralExpr)3 List (java.util.List)2 TypeDeclarationError (org.drools.compiler.compiler.TypeDeclarationError)2 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)2 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)2 FieldDefinition (org.drools.core.factmodel.FieldDefinition)2 IOException (java.io.IOException)1 Serializable (java.io.Serializable)1 StringReader (java.io.StringReader)1