Search in sources :

Example 66 with TypeDeclaration

use of org.drools.core.rule.TypeDeclaration in project drools by kiegroup.

the class DroolsImpl method update.

@Override
public void update(Object object, String... modifiedProperties) {
    Class modifiedClass = object.getClass();
    TypeDeclaration typeDeclaration = workingMemory.getKnowledgeBase().getOrCreateExactTypeDeclaration(modifiedClass);
    org.drools.core.util.bitmask.BitMask mask = typeDeclaration.isPropertyReactive() ? calculatePositiveMask(modifiedClass, asList(modifiedProperties), typeDeclaration.getAccessibleProperties()) : org.drools.core.util.bitmask.AllSetBitMask.get();
    knowledgeHelper.update(fhLookup.get(object), mask, modifiedClass);
}
Also used : TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Example 67 with TypeDeclaration

use of org.drools.core.rule.TypeDeclaration in project drools by kiegroup.

the class TypeDeclarationUtil method createTypeDeclaration.

public static TypeDeclaration createTypeDeclaration(Class<?> cls) {
    TypeDeclaration typeDeclaration = createTypeDeclarationForBean(cls);
    Duration duration = cls.getAnnotation(Duration.class);
    if (duration != null) {
        wireDurationAccessor(duration.value(), typeDeclaration);
    }
    Timestamp timestamp = cls.getAnnotation(Timestamp.class);
    if (timestamp != null) {
        wireDurationAccessor(timestamp.value(), typeDeclaration);
    }
    return typeDeclaration;
}
Also used : Duration(org.kie.api.definition.type.Duration) TypeDeclaration(org.drools.core.rule.TypeDeclaration) Timestamp(org.kie.api.definition.type.Timestamp)

Example 68 with TypeDeclaration

use of org.drools.core.rule.TypeDeclaration in project drools by kiegroup.

the class TypeDeclarationUtil method createTypeDeclaration.

public static TypeDeclaration createTypeDeclaration(KnowledgePackageImpl pkg, TypeMetaData metaType) {
    try {
        Class<?> typeClass = pkg.getTypeResolver().resolveType(metaType.getPackage() + "." + metaType.getName());
        TypeDeclaration typeDeclaration = createTypeDeclarationForBean(typeClass);
        for (Map.Entry<String, AnnotationValue[]> ann : metaType.getAnnotations().entrySet()) {
            switch(ann.getKey()) {
                case "role":
                    for (AnnotationValue annVal : ann.getValue()) {
                        if (annVal.getKey().equals("value") && annVal.getValue().equals("event")) {
                            typeDeclaration.setRole(Role.Type.EVENT);
                        }
                    }
                    break;
                case "duration":
                    for (AnnotationValue annVal : ann.getValue()) {
                        if (annVal.getKey().equals("value")) {
                            wireDurationAccessor(annVal.getValue().toString(), typeDeclaration);
                        }
                    }
                    break;
                case "timestamp":
                    for (AnnotationValue annVal : ann.getValue()) {
                        if (annVal.getKey().equals("value")) {
                            wireTimestampAccessor(annVal.getValue().toString(), typeDeclaration);
                        }
                    }
                    break;
                case "expires":
                    for (AnnotationValue annVal : ann.getValue()) {
                        if (annVal.getKey().equals("value")) {
                            long offset = TimeIntervalParser.parseSingle(annVal.getValue().toString());
                            typeDeclaration.setExpirationOffset(offset == -1L ? Long.MAX_VALUE : offset);
                        } else if (annVal.getKey().equals("policy")) {
                            typeDeclaration.setExpirationType(Enum.valueOf(Expires.Policy.class, annVal.getValue().toString()));
                        }
                    }
                    break;
                case "propertyReactive":
                    typeDeclaration.setPropertyReactive(true);
                    break;
                case "classReactive":
                    typeDeclaration.setPropertyReactive(false);
                    break;
                default:
                    throw new UnsupportedOperationException("Unknown annotation: " + ann.getKey());
            }
        }
        return typeDeclaration;
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
Also used : AnnotationValue(org.drools.model.AnnotationValue) Expires(org.kie.api.definition.type.Expires) TypeDeclaration(org.drools.core.rule.TypeDeclaration) Map(java.util.Map)

Example 69 with TypeDeclaration

use of org.drools.core.rule.TypeDeclaration 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)

Example 70 with TypeDeclaration

use of org.drools.core.rule.TypeDeclaration in project drools by kiegroup.

the class TypeDeclarationUtils method resolveType.

/**
 * Tries to determine the namespace (package) of a simple type chosen to be
 * the superclass of a declared bean. Looks among imports, local
 * declarations and previous declarations. Means that a class can't extend
 * another class declared in package that has not been loaded yet.
 *
 * @param klass        the simple name of the class
 * @param packageDescr the descriptor of the package the base class is declared in
 * @param pkgRegistry  the current package registry
 * @return the fully qualified name of the superclass
 */
public static String resolveType(String klass, PackageDescr packageDescr, PackageRegistry pkgRegistry) {
    String arraySuffix = "";
    int arrayIndex = klass.indexOf("[");
    if (arrayIndex >= 0) {
        arraySuffix = klass.substring(arrayIndex);
        klass = klass.substring(0, arrayIndex);
    }
    // look among imports
    String temp = klass;
    while (temp.length() > 0) {
        for (ImportDescr id : packageDescr.getImports()) {
            String fqKlass = id.getTarget();
            if (fqKlass.endsWith("." + temp)) {
                // logger.info("Replace supertype " + sup + " with full name " + id.getTarget());
                fqKlass = fqKlass.substring(0, fqKlass.lastIndexOf(temp)) + klass;
                return arrayIndex < 0 ? fqKlass : fqKlass + arraySuffix;
            }
        }
        temp = temp.substring(0, Math.max(0, temp.lastIndexOf('.')));
    }
    // look among local declarations
    if (pkgRegistry != null) {
        for (String declaredName : pkgRegistry.getPackage().getTypeDeclarations().keySet()) {
            if (declaredName.equals(klass)) {
                TypeDeclaration typeDeclaration = pkgRegistry.getPackage().getTypeDeclaration(declaredName);
                if (typeDeclaration.getTypeClass() != null) {
                    klass = typeDeclaration.getTypeClass().getName();
                }
            }
        }
    }
    if ((klass != null) && (!klass.contains(".")) && (packageDescr.getNamespace() != null && !packageDescr.getNamespace().isEmpty())) {
        for (AbstractClassTypeDeclarationDescr td : packageDescr.getClassAndEnumDeclarationDescrs()) {
            if (klass.equals(td.getTypeName())) {
                if (td.getType().getFullName().contains(".")) {
                    klass = td.getType().getFullName();
                }
            }
        }
    }
    return arrayIndex < 0 ? klass : klass + arraySuffix;
}
Also used : AbstractClassTypeDeclarationDescr(org.drools.compiler.lang.descr.AbstractClassTypeDeclarationDescr) ImportDescr(org.drools.compiler.lang.descr.ImportDescr) TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Aggregations

TypeDeclaration (org.drools.core.rule.TypeDeclaration)72 Test (org.junit.Test)15 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)12 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)11 PackageRegistry (org.drools.compiler.compiler.PackageRegistry)10 ClassDefinition (org.drools.core.factmodel.ClassDefinition)9 ClassObjectType (org.drools.core.base.ClassObjectType)7 TypeDeclarationDescr (org.drools.compiler.lang.descr.TypeDeclarationDescr)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 TypeDeclarationError (org.drools.compiler.compiler.TypeDeclarationError)4 AbstractClassTypeDeclarationDescr (org.drools.compiler.lang.descr.AbstractClassTypeDeclarationDescr)4 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)4 ObjectType (org.drools.core.spi.ObjectType)4 ArrayList (java.util.ArrayList)3 LinkedHashMap (java.util.LinkedHashMap)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 BindingDescr (org.drools.compiler.lang.descr.BindingDescr)3 TypeFieldDescr (org.drools.compiler.lang.descr.TypeFieldDescr)3 KnowledgePackageImpl (org.drools.core.definitions.impl.KnowledgePackageImpl)3