Search in sources :

Example 1 with TypeDeclarationDescr

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

the class TraitsTypeDeclarationBuilderImpl method postGenerateDeclaredBean.

@Override
protected void postGenerateDeclaredBean(AbstractClassTypeDeclarationDescr typeDescr, TypeDeclaration type, ClassDefinition def, PackageRegistry pkgRegistry) {
    traitRegistry = ((TraitKnowledgePackageImpl) pkgRegistry.getPackage()).getTraitRegistry();
    if (typeDescr.hasAnnotation(Traitable.class) || (!type.getKind().equals(TypeDeclaration.Kind.TRAIT) && kbuilder.getPackageRegistry().containsKey(def.getSuperClass()) && traitRegistry.getTraitables().containsKey(def.getSuperClass()))) {
        // traitable
        if (type.isNovel()) {
            try {
                PackageRegistry reg = kbuilder.getPackageRegistry(typeDescr.getNamespace());
                String availableName = typeDescr.getType().getFullName();
                Class<?> resolvedType = reg.getTypeResolver().resolveType(availableName);
                updateTraitDefinition(type, resolvedType, false);
            } catch (ClassNotFoundException cnfe) {
            // we already know the class exists
            }
        }
        traitRegistry.addTraitable(def);
    } else if (type.getKind().equals(TypeDeclaration.Kind.TRAIT) || typeDescr.hasAnnotation(Trait.class)) {
        // trait
        if (!type.isNovel()) {
            try {
                PackageRegistry reg = kbuilder.getPackageRegistry(typeDescr.getNamespace());
                String availableName = typeDescr.getType().getFullName();
                Class<?> resolvedType = reg.getTypeResolver().resolveType(availableName);
                if (!Thing.class.isAssignableFrom(resolvedType)) {
                    if (!resolvedType.isInterface()) {
                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "Unable to redeclare concrete class " + resolvedType.getName() + " as a trait."));
                        return;
                    }
                    updateTraitDefinition(type, resolvedType, false);
                    String target = typeDescr.getTypeName() + TraitFactoryImpl.SUFFIX;
                    TypeDeclarationDescr tempDescr = new TypeDeclarationDescr();
                    tempDescr.setNamespace(typeDescr.getNamespace());
                    tempDescr.setFields(typeDescr.getFields());
                    tempDescr.setType(target, typeDescr.getNamespace());
                    tempDescr.setTrait(true);
                    tempDescr.addSuperType(typeDescr.getType());
                    tempDescr.setResource(type.getResource());
                    TypeDeclaration tempDeclr = new TypeDeclaration(target);
                    tempDeclr.setKind(TypeDeclaration.Kind.TRAIT);
                    tempDeclr.setTypesafe(type.isTypesafe());
                    tempDeclr.setNovel(true);
                    tempDeclr.setTypeClassName(tempDescr.getType().getFullName());
                    tempDeclr.setResource(type.getResource());
                    ClassDefinition tempDef = new ClassDefinition(target);
                    tempDef.setClassName(tempDescr.getType().getFullName());
                    tempDef.setTraitable(false);
                    for (FieldDefinition fld : def.getFieldsDefinitions()) {
                        tempDef.addField(fld);
                    }
                    tempDef.setInterfaces(def.getInterfaces());
                    tempDef.setSuperClass(def.getClassName());
                    tempDef.setDefinedClass(resolvedType);
                    tempDef.setAbstrakt(true);
                    tempDeclr.setTypeClassDef(tempDef);
                    declaredClassBuilder.generateBeanFromDefinition(tempDescr, tempDeclr, pkgRegistry, tempDef, new TraitClassBuilderImpl());
                    try {
                        Class<?> clazz = pkgRegistry.getTypeResolver().resolveType(tempDescr.getType().getFullName());
                        tempDeclr.setTypeClass(clazz);
                        traitRegistry.addTrait(tempDef.getClassName().replace(TraitFactoryImpl.SUFFIX, ""), tempDef);
                    } catch (ClassNotFoundException cnfe) {
                        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "Internal Trait extension Class '" + target + "' could not be generated correctly'"));
                    } finally {
                        pkgRegistry.getPackage().addTypeDeclaration(tempDeclr);
                    }
                } else {
                    updateTraitDefinition(type, resolvedType, true);
                    traitRegistry.addTrait(def);
                }
            } catch (ClassNotFoundException cnfe) {
            // we already know the class exists
            }
        } else {
            if (def.getClassName().endsWith(TraitFactoryImpl.SUFFIX)) {
                traitRegistry.addTrait(def.getClassName().replace(TraitFactoryImpl.SUFFIX, ""), def);
            } else {
                traitRegistry.addTrait(def);
            }
        }
    }
}
Also used : TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) AbstractClassTypeDeclarationDescr(org.drools.drl.ast.descr.AbstractClassTypeDeclarationDescr) TypeDeclarationDescr(org.drools.drl.ast.descr.TypeDeclarationDescr) FieldDefinition(org.drools.core.factmodel.FieldDefinition) TraitClassBuilderImpl(org.drools.traits.core.factmodel.TraitClassBuilderImpl) Traitable(org.drools.core.factmodel.traits.Traitable) ClassDefinition(org.drools.core.factmodel.ClassDefinition) TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Example 2 with TypeDeclarationDescr

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

the class TypeDeclarationDescrVisitor method visit.

public void visit(List<TypeDeclarationDescr> typeDeclarationDescrs) {
    for (TypeDeclarationDescr typeDeclaration : typeDeclarationDescrs) {
        Import objectImport = data.getImportByName(typeDeclaration.getTypeName());
        String objectTypeName;
        if (objectImport == null) {
            objectTypeName = typeDeclaration.getTypeName();
        } else {
            objectTypeName = objectImport.getName();
        }
        ObjectType objectType = this.data.getObjectTypeByFullName(objectTypeName);
        if (objectType == null) {
            objectType = new ObjectType(typeDeclaration);
            objectType.setName(typeDeclaration.getTypeName());
            objectType.setFullName(typeDeclaration.getTypeName());
            data.add(objectType);
        }
        for (String fieldName : typeDeclaration.getFields().keySet()) {
            Field field = data.getFieldByObjectTypeAndFieldName(objectType.getFullName(), fieldName);
            if (field == null) {
                field = ObjectTypeFactory.createField(typeDeclaration.getFields().get(fieldName), fieldName, objectType);
                field.setFieldType(typeDeclaration.getFields().get(fieldName).getPattern().getObjectType());
                data.add(field);
            }
        }
        for (AnnotationDescr annDescr : typeDeclaration.getAnnotations()) {
            Map<String, Object> values = typeDeclaration.getAnnotation(annDescr.getName()).getValueMap();
            for (String value : values.keySet()) {
                objectType.getMetadata().put(annDescr.getName(), value);
            }
        }
    }
}
Also used : ObjectType(org.drools.verifier.components.ObjectType) Field(org.drools.verifier.components.Field) Import(org.drools.verifier.components.Import) TypeDeclarationDescr(org.drools.drl.ast.descr.TypeDeclarationDescr) AnnotationDescr(org.drools.drl.ast.descr.AnnotationDescr)

Example 3 with TypeDeclarationDescr

use of org.drools.drl.ast.descr.TypeDeclarationDescr 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 4 with TypeDeclarationDescr

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

the class POJOGenerator method findPOJOorGenerate.

public void findPOJOorGenerate() {
    TypeResolver typeResolver = pkg.getTypeResolver();
    Set<String> generatedPojos = new HashSet<>();
    for (TypeDeclarationDescr typeDescr : packageDescr.getTypeDeclarations()) {
        if (!generatedPojos.add(typeDescr.getFullTypeName())) {
            builder.addBuilderResult(new DuplicatedDeclarationError(typeDescr.getFullTypeName()));
            continue;
        }
        try {
            Class<?> type = typeResolver.resolveType(typeDescr.getFullTypeName());
            checkRedeclarationCompatibility(type, typeDescr);
            processTypeMetadata(type, typeDescr.getAnnotations());
        } catch (ClassNotFoundException e) {
            createPOJO(typeDescr);
        }
    }
    for (EnumDeclarationDescr enumDescr : packageDescr.getEnumDeclarations()) {
        try {
            Class<?> type = typeResolver.resolveType(enumDescr.getFullTypeName());
            processTypeMetadata(type, enumDescr.getAnnotations());
        } catch (ClassNotFoundException e) {
            TypeDeclaration generatedEnum = new EnumGenerator().generate(enumDescr);
            packageModel.addGeneratedPOJO(generatedEnum);
            addTypeMetadata(enumDescr.getTypeName());
        }
    }
}
Also used : DuplicatedDeclarationError(org.drools.modelcompiler.builder.errors.DuplicatedDeclarationError) TypeDeclarationDescr(org.drools.drl.ast.descr.TypeDeclarationDescr) TypeResolver(org.drools.core.addon.TypeResolver) EnumDeclarationDescr(org.drools.drl.ast.descr.EnumDeclarationDescr) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) HashSet(java.util.HashSet)

Example 5 with TypeDeclarationDescr

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

the class KnowledgeBuilderTest method testTypeDeclarationWithFieldMetadata.

@Test
public void testTypeDeclarationWithFieldMetadata() throws Exception {
    PackageDescr pkgDescr = new PackageDescr("org.drools.mvel.compiler.test");
    TypeDeclarationDescr typeDescr = new TypeDeclarationDescr("TypeWithFieldMeta");
    TypeFieldDescr f1 = new TypeFieldDescr("field", new PatternDescr("String"));
    f1.addAnnotation("custom", null);
    typeDescr.addField(f1);
    pkgDescr.addTypeDeclaration(typeDescr);
    KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();
    builder.addPackage(pkgDescr);
    assertFalse(builder.hasErrors());
    InternalKnowledgePackage bp = builder.getPackage(pkgDescr.getName());
    final FactType factType = bp.getFactType("org.drools.mvel.compiler.test.TypeWithFieldMeta");
    assertNotNull(factType);
    final FactField field = factType.getField("field");
    assertNotNull(field);
    final Map<String, Object> fieldMetaData = field.getMetaData();
    assertNotNull("No field-level custom metadata got compiled", fieldMetaData);
    assertTrue("Field metadata does not include expected value", fieldMetaData.containsKey("custom"));
}
Also used : FactField(org.kie.api.definition.type.FactField) TypeDeclarationDescr(org.drools.drl.ast.descr.TypeDeclarationDescr) PatternDescr(org.drools.drl.ast.descr.PatternDescr) TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) PackageDescr(org.drools.drl.ast.descr.PackageDescr) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) FactType(org.kie.api.definition.type.FactType) Test(org.junit.Test)

Aggregations

TypeDeclarationDescr (org.drools.drl.ast.descr.TypeDeclarationDescr)22 PackageDescr (org.drools.drl.ast.descr.PackageDescr)10 AbstractClassTypeDeclarationDescr (org.drools.drl.ast.descr.AbstractClassTypeDeclarationDescr)9 Test (org.junit.Test)7 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)6 TypeFieldDescr (org.drools.drl.ast.descr.TypeFieldDescr)6 TypeDeclarationError (org.drools.compiler.compiler.TypeDeclarationError)5 EnumDeclarationDescr (org.drools.drl.ast.descr.EnumDeclarationDescr)5 ArrayList (java.util.ArrayList)4 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)4 TypeDeclaration (org.drools.core.rule.TypeDeclaration)4 HashSet (java.util.HashSet)3 TypeResolver (org.drools.core.addon.TypeResolver)3 ClassDefinition (org.drools.core.factmodel.ClassDefinition)3 AnnotationDescr (org.drools.drl.ast.descr.AnnotationDescr)3 RuleDescr (org.drools.drl.ast.descr.RuleDescr)3 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 List (java.util.List)2