Search in sources :

Example 11 with ClassDefinition

use of org.drools.core.factmodel.ClassDefinition in project drools by kiegroup.

the class DialectUtil method parseInsertDescr.

private static void parseInsertDescr(RuleBuildContext context, JavaBlockDescr block) {
    String expr = block.getTargetExpression();
    if (expr.startsWith("new ")) {
        int argsStart = expr.indexOf('(');
        if (argsStart > 0) {
            String className = expr.substring(4, argsStart).trim();
            Class<?> typeClass = findClassByName(context, className);
            TypeDeclaration typeDeclaration = typeClass == null ? null : context.getKnowledgeBuilder().getTypeDeclaration(typeClass);
            if (typeDeclaration != null) {
                ConsequenceMetaData.Statement statement = new ConsequenceMetaData.Statement(ConsequenceMetaData.Statement.Type.INSERT, typeClass);
                context.getRule().getConsequenceMetaData().addStatement(statement);
                String constructorParams = expr.substring(argsStart + 1, expr.indexOf(')')).trim();
                List<String> args = splitArgumentsList(constructorParams);
                ClassDefinition classDefinition = typeDeclaration.getTypeClassDef();
                List<FactField> fields = classDefinition.getFields();
                if (args.size() == fields.size()) {
                    for (int i = 0; i < args.size(); i++) {
                        statement.addField(fields.get(i).getName(), args.get(i));
                    }
                }
            }
        }
    }
}
Also used : FactField(org.kie.api.definition.type.FactField) ConsequenceMetaData(org.drools.core.rule.ConsequenceMetaData) ClassDefinition(org.drools.core.factmodel.ClassDefinition) TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Example 12 with ClassDefinition

use of org.drools.core.factmodel.ClassDefinition in project drools by kiegroup.

the class StandaloneTraitFactory method extendAsProperTrait.

private Class<T> extendAsProperTrait(Class<T> trait) {
    String extName = trait.getName() + TraitFactory.SUFFIX;
    if (!classLoader.isClassInUse(extName)) {
        try {
            ClassDefinition extDef = new ClassDefinition(extName);
            extDef.setSuperClass(Object.class.getName());
            AnnotationDefinition annot = new AnnotationDefinition(Trait.class.getName());
            extDef.addAnnotation(annot);
            String[] supers = new String[] { Thing.class.getName(), trait.getName() };
            extDef.setInterfaces(supers);
            byte[] ext = getComponentFactory().getClassBuilderFactory().getTraitBuilder().buildClass(extDef, classLoader);
            Class<?> klass = registerAndLoadTypeDefinition(extName, ext);
            ClassDefinition tDef = buildClassDefinition(trait, trait);
            tDef.setDefinedClass(klass);
            getTraitRegistry().addTrait(tDef);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    try {
        return (Class<T>) Class.forName(extName, false, classLoader);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : AnnotationDefinition(org.drools.core.factmodel.AnnotationDefinition) Trait(org.drools.core.factmodel.traits.Trait) ClassDefinition(org.drools.core.factmodel.ClassDefinition) IOException(java.io.IOException) LogicalTypeInconsistencyException(org.drools.core.factmodel.traits.LogicalTypeInconsistencyException)

Example 13 with ClassDefinition

use of org.drools.core.factmodel.ClassDefinition 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 14 with ClassDefinition

use of org.drools.core.factmodel.ClassDefinition in project drools by kiegroup.

the class TypeDeclarationCache method setClassDefinitionOnTypeDeclaration.

private ClassDefinition setClassDefinitionOnTypeDeclaration(Class<?> cls, TypeDeclaration typeDeclaration) {
    ClassDefinition clsDef = new ClassDefinition();
    ClassDefinitionFactory.populateDefinitionFromClass(clsDef, typeDeclaration.getResource(), cls, cls.getAnnotation(Trait.class) != null);
    typeDeclaration.setTypeClassDef(clsDef);
    return clsDef;
}
Also used : ClassDefinition(org.drools.core.factmodel.ClassDefinition)

Example 15 with ClassDefinition

use of org.drools.core.factmodel.ClassDefinition in project drools by kiegroup.

the class PatternBuilder method processPositional.

protected void processPositional(final RuleBuildContext context, final PatternDescr patternDescr, final Pattern pattern, final ExprConstraintDescr descr) {
    if (descr.getType() == ExprConstraintDescr.Type.POSITIONAL && pattern.getObjectType() instanceof ClassObjectType) {
        Class<?> klazz = ((ClassObjectType) pattern.getObjectType()).getClassType();
        TypeDeclaration tDecl = context.getKnowledgeBuilder().getTypeDeclaration(klazz);
        if (tDecl == null) {
            registerDescrBuildError(context, patternDescr, "Unable to find @positional definitions for :" + klazz + "\n");
            return;
        }
        ClassDefinition clsDef = tDecl.getTypeClassDef();
        if (clsDef == null) {
            registerDescrBuildError(context, patternDescr, "Unable to find @positional field " + descr.getPosition() + " for class " + tDecl.getTypeName() + "\n");
            return;
        }
        FieldDefinition field = clsDef.getField(descr.getPosition());
        if (field == null) {
            registerDescrBuildError(context, patternDescr, "Unable to find @positional field " + descr.getPosition() + " for class " + tDecl.getTypeName() + "\n");
            return;
        }
        String expr = descr.getExpression();
        boolean isSimpleIdentifier = isIdentifier(expr);
        if (isSimpleIdentifier) {
            // create a binding
            BindingDescr binder = new BindingDescr();
            binder.setUnification(true);
            binder.setExpression(field.getName());
            binder.setVariable(descr.getExpression());
            buildRuleBindings(context, patternDescr, pattern, binder);
        } else {
            // create a constraint
            build(context, patternDescr, pattern, descr, field.getName() + " == " + descr.getExpression());
        }
    }
}
Also used : BindingDescr(org.drools.compiler.lang.descr.BindingDescr) AcceptsClassObjectType(org.drools.core.spi.AcceptsClassObjectType) ClassObjectType(org.drools.core.base.ClassObjectType) FieldDefinition(org.drools.core.factmodel.FieldDefinition) ClassDefinition(org.drools.core.factmodel.ClassDefinition) TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Aggregations

ClassDefinition (org.drools.core.factmodel.ClassDefinition)20 TypeDeclaration (org.drools.core.rule.TypeDeclaration)9 FieldDefinition (org.drools.core.factmodel.FieldDefinition)6 ArrayList (java.util.ArrayList)4 TypeDeclarationError (org.drools.compiler.compiler.TypeDeclarationError)4 PackageRegistry (org.drools.compiler.compiler.PackageRegistry)3 AbstractClassTypeDeclarationDescr (org.drools.compiler.lang.descr.AbstractClassTypeDeclarationDescr)3 TypeDeclarationDescr (org.drools.compiler.lang.descr.TypeDeclarationDescr)3 IOException (java.io.IOException)2 BitSet (java.util.BitSet)2 ClassFieldAccessor (org.drools.core.base.ClassFieldAccessor)2 ClassFieldAccessorStore (org.drools.core.base.ClassFieldAccessorStore)2 EnumClassDefinition (org.drools.core.factmodel.EnumClassDefinition)2 Traitable (org.drools.core.factmodel.traits.Traitable)2 TraitableBean (org.drools.core.factmodel.traits.TraitableBean)2 JavaDialectRuntimeData (org.drools.core.rule.JavaDialectRuntimeData)2 FactField (org.kie.api.definition.type.FactField)2 ByteString (com.google.protobuf.ByteString)1 Serializable (java.io.Serializable)1 Field (java.lang.reflect.Field)1