Search in sources :

Example 11 with TypeFieldDescr

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

the class ClassHierarchyManager method buildDescrsFromFields.

private static void buildDescrsFromFields(Class klass, TypeDeclarationDescr typeDescr, Map<String, TypeFieldDescr> fieldMap) {
    ClassFieldInspector inspector;
    try {
        inspector = CoreComponentsBuilder.get().createClassFieldInspector(klass);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    for (String name : inspector.getGetterMethods().keySet()) {
        // classFieldAccessor requires both getter and setter
        if (inspector.getSetterMethods().containsKey(name)) {
            if (!inspector.isNonGetter(name) && !"class".equals(name)) {
                Resource resource = typeDescr.getResource();
                PatternDescr patternDescr = new PatternDescr(inspector.getFieldType(name).getName());
                patternDescr.setResource(resource);
                TypeFieldDescr inheritedFlDescr = new TypeFieldDescr(name, patternDescr);
                inheritedFlDescr.setResource(resource);
                inheritedFlDescr.setInherited(!Modifier.isAbstract(inspector.getGetterMethods().get(name).getModifiers()));
                if (!fieldMap.containsKey(inheritedFlDescr.getFieldName()))
                    fieldMap.put(inheritedFlDescr.getFieldName(), inheritedFlDescr);
            }
        }
    }
}
Also used : PatternDescr(org.drools.drl.ast.descr.PatternDescr) TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) Resource(org.kie.api.io.Resource) IOException(java.io.IOException) ClassFieldInspector(org.drools.core.base.ClassFieldInspector)

Example 12 with TypeFieldDescr

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

the class TypeDeclarationFactory method checkRedeclaration.

protected void checkRedeclaration(AbstractClassTypeDeclarationDescr typeDescr, TypeDeclaration type, PackageRegistry pkgRegistry) {
    TypeDeclaration previousTypeDeclaration = kbuilder.getPackageRegistry(typeDescr.getNamespace()).getPackage().getTypeDeclaration(typeDescr.getTypeName());
    try {
        // to the behavior previous these changes
        if (!type.isDefinition()) {
            // new declarations of a POJO can't declare new fields,
            // except if the POJO was previously generated/compiled and saved into the kjar
            Class<?> existingDeclarationClass = TypeDeclarationUtils.getExistingDeclarationClass(typeDescr, pkgRegistry);
            if (!kbuilder.getBuilderConfiguration().isPreCompiled() && !GeneratedFact.class.isAssignableFrom(existingDeclarationClass) && !type.getTypeClassDef().getFields().isEmpty()) {
                try {
                    Class existingClass = pkgRegistry.getPackage().getTypeResolver().resolveType(typeDescr.getType().getFullName());
                    ClassFieldInspector cfi = CoreComponentsBuilder.get().createClassFieldInspector(existingClass);
                    int fieldCount = 0;
                    for (String existingFieldName : cfi.getFieldTypesField().keySet()) {
                        if (!cfi.isNonGetter(existingFieldName) && !"class".equals(existingFieldName) && cfi.getSetterMethods().containsKey(existingFieldName) && cfi.getGetterMethods().containsKey(existingFieldName)) {
                            if (!typeDescr.getFields().containsKey(existingFieldName)) {
                                type.setValid(false);
                                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "New declaration of " + typeDescr.getType().getFullName() + " does not include field " + existingFieldName));
                            } else {
                                String fldType = cfi.getFieldType(existingFieldName).getName();
                                fldType = TypeDeclarationUtils.toBuildableType(fldType, kbuilder.getRootClassLoader());
                                TypeFieldDescr declaredField = typeDescr.getFields().get(existingFieldName);
                                if (!fldType.equals(type.getTypeClassDef().getField(existingFieldName).getTypeName())) {
                                    type.setValid(false);
                                    kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "New declaration of " + typeDescr.getType().getFullName() + " redeclared field " + existingFieldName + " : \n" + "existing : " + fldType + " vs declared : " + declaredField.getPattern().getObjectType()));
                                } else {
                                    fieldCount++;
                                }
                            }
                        }
                    }
                    if (fieldCount != typeDescr.getFields().size()) {
                        kbuilder.addBuilderResult(reportDeclarationDiff(cfi, typeDescr));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    type.setValid(false);
                    kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "Unable to redeclare " + typeDescr.getType().getFullName() + " : " + e.getMessage()));
                } catch (ClassNotFoundException e) {
                    type.setValid(false);
                    kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "Unable to redeclare " + typeDescr.getType().getFullName() + " : " + e.getMessage()));
                }
            }
        } else if (previousTypeDeclaration != null) {
            // previous declaration can be null during an incremental compilation
            int typeComparisonResult = this.compareTypeDeclarations(previousTypeDeclaration, type);
            if (typeComparisonResult < 0) {
                // oldDeclaration is "less" than newDeclaration -> error
                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, typeDescr.getType().getFullName() + " declares more fields than the already existing version"));
                type.setValid(false);
            } else if (typeComparisonResult > 0 && !type.getTypeClassDef().getFields().isEmpty()) {
                // oldDeclaration is "grater" than newDeclaration -> error
                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, typeDescr.getType().getFullName() + " declares less fields than the already existing version"));
                type.setValid(false);
            }
            // fields present in the previous declaration
            if (type.getNature() == TypeDeclaration.Nature.DECLARATION) {
                mergeTypeDeclarations(previousTypeDeclaration, type);
            }
        }
    } catch (IncompatibleClassChangeError error) {
        // if the types are incompatible -> error
        kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, error.getMessage()));
    }
}
Also used : TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) IOException(java.io.IOException) TypeDeclaration(org.drools.core.rule.TypeDeclaration) GeneratedFact(org.drools.core.factmodel.GeneratedFact) ClassFieldInspector(org.drools.core.base.ClassFieldInspector)

Example 13 with TypeFieldDescr

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

the class DescrTypeDefinition method processFields.

private List<DescrFieldDefinition> processFields() {
    List<FieldDefinition> inheritedFields = findInheritedDeclaredFields();
    List<TypeFieldDescr> sortedTypeFields = typeFieldsSortedByPosition(inheritedFields);
    int position = inheritedFields.size();
    List<DescrFieldDefinition> allFields = new ArrayList<>();
    for (TypeFieldDescr typeFieldDescr : sortedTypeFields) {
        ProcessedTypeField processedTypeField = processTypeField(position, typeFieldDescr);
        allFields.add(processedTypeField.fieldDefinition);
        position = processedTypeField.position;
    }
    if (typeDeclarationDescr.getFields().size() != sortedTypeFields.size()) {
        typeDeclarationDescr.getFields().values().stream().filter(f -> inheritedFields.stream().map(FieldDefinition::getFieldName).anyMatch(name -> name.equals(f.getFieldName()))).map(DescrFieldDefinition::new).map(d -> d.setOverride(true)).forEach(allFields::add);
    }
    return allFields;
}
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) TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) FieldDefinition(org.drools.modelcompiler.builder.generator.declaredtype.api.FieldDefinition) ArrayList(java.util.ArrayList)

Example 14 with TypeFieldDescr

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

the class EnumGenerator method generate.

public TypeDeclaration generate(EnumDeclarationDescr enumDeclarationDescr) {
    NodeList<Modifier> modifiers = nodeList(Modifier.publicModifier());
    enumDeclaration = new EnumDeclaration(modifiers, enumDeclarationDescr.getFullTypeName());
    for (Map.Entry<String, TypeFieldDescr> field : enumDeclarationDescr.getFields().entrySet()) {
        addField(field);
    }
    for (EnumLiteralDescr enumLiteral : enumDeclarationDescr.getLiterals()) {
        addEnumerationValue(enumLiteral);
    }
    createConstructor(enumDeclarationDescr);
    return enumDeclaration;
}
Also used : TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) Modifier(com.github.javaparser.ast.Modifier) Map(java.util.Map) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) EnumLiteralDescr(org.drools.drl.ast.descr.EnumLiteralDescr)

Example 15 with TypeFieldDescr

use of org.drools.drl.ast.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.drl.ast.descr.TypeDeclarationDescr) TypeFieldDescr(org.drools.drl.ast.descr.TypeFieldDescr) PackageDescr(org.drools.drl.ast.descr.PackageDescr) Test(org.junit.Test)

Aggregations

TypeFieldDescr (org.drools.drl.ast.descr.TypeFieldDescr)15 TypeDeclarationError (org.drools.compiler.compiler.TypeDeclarationError)6 TypeDeclarationDescr (org.drools.drl.ast.descr.TypeDeclarationDescr)6 ArrayList (java.util.ArrayList)5 PackageDescr (org.drools.drl.ast.descr.PackageDescr)5 PatternDescr (org.drools.drl.ast.descr.PatternDescr)5 IOException (java.io.IOException)4 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)4 FieldDefinition (org.drools.core.factmodel.FieldDefinition)4 AnnotationDescr (org.drools.drl.ast.descr.AnnotationDescr)4 HashMap (java.util.HashMap)3 ClassFieldInspector (org.drools.core.base.ClassFieldInspector)3 TypeDeclaration (org.drools.core.rule.TypeDeclaration)3 QualifiedName (org.drools.drl.ast.descr.QualifiedName)3 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Optional (java.util.Optional)2