Search in sources :

Example 11 with TypeFieldDescr

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

the class ClassHierarchyManager method sortByHierarchy.

/**
 * Utility method to sort declared beans. Linearizes the hierarchy,
 * i.e.generates a sequence of declaration such that, if Sub is subclass of
 * Sup, then the index of Sub will be > than the index of Sup in the
 * resulting collection. This ensures that superclasses are processed before
 * their subclasses
 */
protected List<AbstractClassTypeDeclarationDescr> sortByHierarchy(Collection<AbstractClassTypeDeclarationDescr> unsortedDescrs, KnowledgeBuilderImpl kbuilder) {
    taxonomy = new HashMap<QualifiedName, Collection<QualifiedName>>();
    Map<QualifiedName, AbstractClassTypeDeclarationDescr> cache = new HashMap<QualifiedName, AbstractClassTypeDeclarationDescr>();
    for (AbstractClassTypeDeclarationDescr tdescr : unsortedDescrs) {
        cache.put(tdescr.getType(), tdescr);
    }
    for (AbstractClassTypeDeclarationDescr tdescr : unsortedDescrs) {
        QualifiedName name = tdescr.getType();
        Collection<QualifiedName> supers = taxonomy.get(name);
        if (supers == null) {
            supers = new ArrayList<QualifiedName>();
            taxonomy.put(name, supers);
        } else {
            kbuilder.addBuilderResult(new TypeDeclarationError(tdescr, "Found duplicate declaration for type " + tdescr.getType()));
        }
        boolean circular = false;
        for (QualifiedName sup : tdescr.getSuperTypes()) {
            if (!Object.class.getName().equals(name.getFullName())) {
                if (!hasCircularDependency(tdescr.getType(), sup, taxonomy)) {
                    if (cache.containsKey(sup)) {
                        supers.add(sup);
                    }
                } else {
                    circular = true;
                    kbuilder.addBuilderResult(new TypeDeclarationError(tdescr, "Found circular dependency for type " + tdescr.getTypeName()));
                    break;
                }
            }
        }
        if (circular) {
            tdescr.getSuperTypes().clear();
        }
    }
    for (AbstractClassTypeDeclarationDescr tdescr : unsortedDescrs) {
        for (TypeFieldDescr field : tdescr.getFields().values()) {
            QualifiedName name = tdescr.getType();
            QualifiedName typeName = new QualifiedName(field.getPattern().getObjectType());
            if (!hasCircularDependency(name, typeName, taxonomy)) {
                if (cache.containsKey(typeName)) {
                    taxonomy.get(name).add(typeName);
                }
            } else {
                field.setRecursive(true);
            }
        }
    }
    List<QualifiedName> sorted = new HierarchySorter<QualifiedName>().sort(taxonomy);
    ArrayList list = new ArrayList(sorted.size());
    for (QualifiedName name : sorted) {
        list.add(cache.get(name));
    }
    return list;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QualifiedName(org.drools.compiler.lang.descr.QualifiedName) ArrayList(java.util.ArrayList) TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) AbstractClassTypeDeclarationDescr(org.drools.compiler.lang.descr.AbstractClassTypeDeclarationDescr) Collection(java.util.Collection)

Example 12 with TypeFieldDescr

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

the class ClassHierarchyManager method mergeFields.

protected void mergeFields(String simpleSuperTypeName, String superTypePackageName, String fullSuper, TypeDeclarationDescr typeDescr, List<TypeDefinition> unresolvedTypes, Map<String, AbstractClassTypeDeclarationDescr> unprocessableDescrs, TypeResolver resolver) {
    Map<String, TypeFieldDescr> fieldMap = new LinkedHashMap<String, TypeFieldDescr>();
    boolean isNovel = TypeDeclarationUtils.isNovelClass(typeDescr, kbuilder.getPackageRegistry(typeDescr.getNamespace()));
    PackageRegistry registry = kbuilder.getPackageRegistry(superTypePackageName);
    InternalKnowledgePackage pack = null;
    if (registry != null) {
        pack = registry.getPackage();
    }
    if (unprocessableDescrs.containsKey(fullSuper)) {
        unprocessableDescrs.put(typeDescr.getType().getFullName(), typeDescr);
        return;
    }
    // if a class is declared in DRL, its package can't be null? The default package is replaced by "defaultpkg"
    boolean isSuperClassTagged = false;
    // in the same package, or in a previous one
    boolean isSuperClassDeclared = true;
    if (pack != null) {
        // look for the supertype declaration in available packages
        TypeDeclaration superTypeDeclaration = pack.getTypeDeclaration(simpleSuperTypeName);
        if (superTypeDeclaration != null && superTypeDeclaration.getTypeClassDef() != null) {
            ClassDefinition classDef = superTypeDeclaration.getTypeClassDef();
            // inherit fields
            for (org.kie.api.definition.type.FactField fld : classDef.getFields()) {
                TypeFieldDescr inheritedFlDescr = buildInheritedFieldDescrFromDefinition(fld, typeDescr);
                fieldMap.put(inheritedFlDescr.getFieldName(), inheritedFlDescr);
            }
            // new classes are already distinguished from tagged external classes
            isSuperClassTagged = !superTypeDeclaration.isNovel();
        }
    } else {
        isSuperClassDeclared = false;
    }
    // look for the class externally
    if (!isSuperClassDeclared || isSuperClassTagged) {
        try {
            Class superKlass;
            if (registry != null) {
                superKlass = registry.getTypeResolver().resolveType(fullSuper);
            } else {
                // if the supertype has not been declared, and we have got so far, it means that this class is not novel
                superKlass = resolver.resolveType(fullSuper);
            }
            buildDescrsFromFields(superKlass, typeDescr, registry, fieldMap);
        } catch (ClassNotFoundException cnfe) {
            unprocessableDescrs.put(typeDescr.getType().getFullName(), typeDescr);
            return;
        }
    }
    // notice that it is not possible to override a field changing its type
    for (String fieldName : typeDescr.getFields().keySet()) {
        if (fieldMap.containsKey(fieldName)) {
            String type1 = fieldMap.get(fieldName).getPattern().getObjectType();
            String type2 = typeDescr.getFields().get(fieldName).getPattern().getObjectType();
            if (type2.lastIndexOf(".") < 0) {
                try {
                    TypeResolver typeResolver = kbuilder.getPackageRegistry(typeDescr.getNamespace()).getTypeResolver();
                    type1 = typeResolver.resolveType(type1).getName();
                    type2 = typeResolver.resolveType(type2).getName();
                    // now that we are at it... this will be needed later anyway
                    fieldMap.get(fieldName).getPattern().setObjectType(type1);
                    typeDescr.getFields().get(fieldName).getPattern().setObjectType(type2);
                } catch (ClassNotFoundException cnfe) {
                // will fail later
                }
            }
            boolean clash = !type1.equals(type2);
            TypeFieldDescr overriding = null;
            if (clash) {
                // this may still be an override using a subclass of the original type
                try {
                    Class<?> sup = resolver.resolveType(type1);
                    Class<?> loc = resolver.resolveType(type2);
                    if (sup.isAssignableFrom(loc)) {
                        clash = false;
                        // mark as non inherited so that a new field is actually built
                        overriding = fieldMap.get(fieldName);
                    }
                } catch (ClassNotFoundException cnfe) {
                // not much to do
                }
            }
            if (clash) {
                kbuilder.addBuilderResult(new TypeDeclarationError(typeDescr, "Cannot redeclare field '" + fieldName + " from " + type1 + " to " + type2));
                typeDescr.setType(null, null);
                return;
            } else {
                String initVal = fieldMap.get(fieldName).getInitExpr();
                TypeFieldDescr fd = typeDescr.getFields().get(fieldName);
                if (fd.getInitExpr() == null) {
                    fd.setInitExpr(initVal);
                }
                fd.setInherited(fieldMap.get(fieldName).isInherited());
                fd.setOverriding(overriding);
                for (String key : fieldMap.get(fieldName).getAnnotationNames()) {
                    if (fd.getAnnotation(key) == null) {
                        fd.addAnnotation(fieldMap.get(fieldName).getAnnotation(key));
                    }
                }
                if (fd.getIndex() < 0) {
                    fd.setIndex(fieldMap.get(fieldName).getIndex());
                }
            }
        }
        fieldMap.put(fieldName, typeDescr.getFields().get(fieldName));
    }
    typeDescr.setFields(fieldMap);
}
Also used : TypeResolver(org.kie.soup.project.datamodel.commons.types.TypeResolver) ClassDefinition(org.drools.core.factmodel.ClassDefinition) LinkedHashMap(java.util.LinkedHashMap) TypeDeclarationError(org.drools.compiler.compiler.TypeDeclarationError) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) TypeDeclaration(org.drools.core.rule.TypeDeclaration) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 13 with TypeFieldDescr

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

the class KnowledgeBuilderTest method testTypeDeclarationWithFieldMetadata.

@Test
public void testTypeDeclarationWithFieldMetadata() throws Exception {
    PackageDescr pkgDescr = new PackageDescr("org.drools.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.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.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) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) FactType(org.kie.api.definition.type.FactType) CompositeObjectSinkAdapterTest(org.drools.core.reteoo.CompositeObjectSinkAdapterTest) Test(org.junit.Test)

Example 14 with TypeFieldDescr

use of org.drools.compiler.lang.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 = new ClassFieldInspector(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.compiler.lang.descr.TypeFieldDescr) IOException(java.io.IOException) TypeDeclaration(org.drools.core.rule.TypeDeclaration) GeneratedFact(org.drools.core.factmodel.GeneratedFact) ClassFieldInspector(org.drools.core.util.asm.ClassFieldInspector)

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