Search in sources :

Example 6 with TypeFieldDescr

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

the class RuleParserTest method testTypeDeclarationWithFields.

@Test
public void testTypeDeclarationWithFields() throws Exception {
    final PackageDescr pkg = (PackageDescr) parseResource("compilationUnit", "declare_type_with_fields.drl");
    assertFalse(parser.getErrors().toString(), parser.hasErrors());
    List<TypeDeclarationDescr> td = pkg.getTypeDeclarations();
    assertEquals(3, td.size());
    TypeDeclarationDescr d = td.get(0);
    assertEquals("SomeFact", d.getTypeName());
    assertEquals(2, d.getFields().size());
    assertTrue(d.getFields().containsKey("name"));
    assertTrue(d.getFields().containsKey("age"));
    TypeFieldDescr f = d.getFields().get("name");
    assertEquals("String", f.getPattern().getObjectType());
    f = d.getFields().get("age");
    assertEquals("Integer", f.getPattern().getObjectType());
    d = td.get(1);
    assertEquals("AnotherFact", d.getTypeName());
    TypeDeclarationDescr type = td.get(2);
    assertEquals("Person", type.getTypeName());
    assertEquals("fact", type.getAnnotation("role").getValue());
    assertEquals("\"Models a person\"", type.getAnnotation("doc").getValue("descr"));
    assertEquals("\"Bob\"", type.getAnnotation("doc").getValue("author"));
    assertEquals("Calendar.getInstance().getDate()", type.getAnnotation("doc").getValue("date"));
    assertEquals(2, type.getFields().size());
    TypeFieldDescr field = type.getFields().get("name");
    assertEquals("name", field.getFieldName());
    assertEquals("String", field.getPattern().getObjectType());
    assertEquals("\"John Doe\"", field.getInitExpr());
    assertEquals("50", field.getAnnotation("length").getValue("max"));
    assertNotNull(field.getAnnotation("key"));
    field = type.getFields().get("age");
    assertEquals("age", field.getFieldName());
    assertEquals("int", field.getPattern().getObjectType());
    assertEquals("-1", field.getInitExpr());
    assertEquals("0", field.getAnnotation("ranged").getValue("min"));
    assertEquals("150", field.getAnnotation("ranged").getValue("max"));
    assertEquals("-1", field.getAnnotation("ranged").getValue("unknown"));
}
Also used : TypeDeclarationDescr(org.drools.compiler.lang.descr.TypeDeclarationDescr) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) Test(org.junit.Test)

Example 7 with TypeFieldDescr

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

the class KnowledgeBuilderTest method testTypeDeclarationNewBean.

@Test
public void testTypeDeclarationNewBean() throws Exception {
    PackageDescr pkgDescr = new PackageDescr("org.drools.compiler.test");
    TypeDeclarationDescr typeDescr = new TypeDeclarationDescr("NewBean");
    TypeFieldDescr f1 = new TypeFieldDescr("name", new PatternDescr("String"));
    TypeFieldDescr f2 = new TypeFieldDescr("age", new PatternDescr("int"));
    typeDescr.addField(f1);
    typeDescr.addField(f2);
    pkgDescr.addTypeDeclaration(typeDescr);
    KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();
    builder.addPackage(pkgDescr);
    InternalKnowledgePackage pkg = builder.getPackage(pkgDescr.getName());
    assertEquals(1, pkg.getTypeDeclarations().size());
    TypeDeclaration type = pkg.getTypeDeclaration("NewBean");
    assertEquals("NewBean", type.getTypeName());
    assertEquals(Role.Type.FACT, type.getRole());
    assertEquals("org.drools.compiler.test.NewBean", type.getTypeClass().getName());
    assertFalse(builder.hasErrors());
    InternalKnowledgePackage bp = builder.getPackage(pkgDescr.getName());
    Class newBean = bp.getPackageClassLoader().loadClass("org.drools.compiler.test.NewBean");
    assertNotNull(newBean);
}
Also used : TypeDeclarationDescr(org.drools.compiler.lang.descr.TypeDeclarationDescr) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) TypeDeclaration(org.drools.core.rule.TypeDeclaration) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) CompositeObjectSinkAdapterTest(org.drools.core.reteoo.CompositeObjectSinkAdapterTest) Test(org.junit.Test)

Example 8 with TypeFieldDescr

use of org.drools.compiler.lang.descr.TypeFieldDescr 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 9 with TypeFieldDescr

use of org.drools.compiler.lang.descr.TypeFieldDescr in project drools-wb by kiegroup.

the class FactModelPersistence method toModel.

private static List<FactMetaModel> toModel(String drl) throws DroolsParserException {
    Preconditions.checkNotNull(drl, "The string representing DRL can't be null!");
    if (drl.startsWith("#advanced") || drl.startsWith("//advanced")) {
        throw new DroolsParserException("Using advanced editor");
    }
    final DrlParser parser = new DrlParser();
    final StringReader reader = new StringReader(drl);
    final PackageDescr pkg = parser.parse(reader);
    if (parser.hasErrors()) {
        throw new DroolsParserException("The model drl " + drl + " is not valid");
    }
    if (pkg == null) {
        return emptyList();
    }
    final List<TypeDeclarationDescr> types = pkg.getTypeDeclarations();
    final List<FactMetaModel> list = new ArrayList<FactMetaModel>(types.size());
    for (final TypeDeclarationDescr td : types) {
        final FactMetaModel mm = new FactMetaModel();
        mm.setName(td.getTypeName());
        mm.setSuperType(td.getSuperTypeName());
        final Map<String, TypeFieldDescr> fields = td.getFields();
        for (Map.Entry<String, TypeFieldDescr> en : fields.entrySet()) {
            final String fieldName = en.getKey();
            final TypeFieldDescr descr = en.getValue();
            final FieldMetaModel fm = new FieldMetaModel(fieldName, descr.getPattern().getObjectType());
            mm.getFields().add(fm);
        }
        for (final AnnotationDescr descr : td.getAnnotations()) {
            final String annotationName = descr.getName();
            final Map<String, String> values = extractStringValues(descr);
            final AnnotationMetaModel am = new AnnotationMetaModel(annotationName, values);
            mm.getAnnotations().add(am);
        }
        list.add(mm);
    }
    return list;
}
Also used : TypeDeclarationDescr(org.drools.compiler.lang.descr.TypeDeclarationDescr) ArrayList(java.util.ArrayList) FactMetaModel(org.drools.workbench.screens.factmodel.model.FactMetaModel) DroolsParserException(org.drools.compiler.compiler.DroolsParserException) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) FieldMetaModel(org.drools.workbench.screens.factmodel.model.FieldMetaModel) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) StringReader(java.io.StringReader) DrlParser(org.drools.compiler.compiler.DrlParser) AnnotationMetaModel(org.drools.workbench.screens.factmodel.model.AnnotationMetaModel) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with TypeFieldDescr

use of org.drools.compiler.lang.descr.TypeFieldDescr 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<FieldDefinition>(fields.size());
    int maxDeclaredPos = 0;
    BitSet occupiedPositions = new BitSet(fields.size());
    for (TypeFieldDescr field : fields.values()) {
        String typeName = field.getPattern().getObjectType();
        String typeNameKey = typeName;
        String fullFieldType = kbuilder != null ? TypeDeclarationUtils.toBuildableType(typeNameKey, kbuilder.getRootClassLoader()) : typeNameKey;
        FieldDefinition fieldDef = new FieldDefinition(field.getFieldName(), fullFieldType);
        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 = field.getTypedAnnotation(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.compiler.lang.descr.AnnotationDescr) Annotation(java.lang.annotation.Annotation) IOException(java.io.IOException) TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr)

Aggregations

TypeFieldDescr (org.drools.compiler.lang.descr.TypeFieldDescr)14 TypeDeclarationError (org.drools.compiler.compiler.TypeDeclarationError)5 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)5 PatternDescr (org.drools.compiler.lang.descr.PatternDescr)5 TypeDeclarationDescr (org.drools.compiler.lang.descr.TypeDeclarationDescr)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 AnnotationDescr (org.drools.compiler.lang.descr.AnnotationDescr)4 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)4 FieldDefinition (org.drools.core.factmodel.FieldDefinition)4 TypeDeclaration (org.drools.core.rule.TypeDeclaration)3 ClassFieldInspector (org.drools.core.util.asm.ClassFieldInspector)3 Test (org.junit.Test)3 Position (org.kie.api.definition.type.Position)3 Collection (java.util.Collection)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 GeneratedFact (org.drools.core.factmodel.GeneratedFact)2 CompositeObjectSinkAdapterTest (org.drools.core.reteoo.CompositeObjectSinkAdapterTest)2