Search in sources :

Example 16 with ObjectType

use of org.drools.core.spi.ObjectType in project drools by kiegroup.

the class RuleContext method getDeclaration.

Declaration getDeclaration(Variable variable) {
    if (variable.isFact()) {
        Declaration declaration = innerDeclaration.get(variable);
        if (declaration == null) {
            declaration = queryDeclaration.get(variable);
        }
        if (declaration == null) {
            Pattern pattern = patterns.get(variable);
            declaration = pattern != null ? pattern.getDeclaration() : null;
        }
        return declaration;
    } else {
        Global global = ((Global) variable);
        ObjectType objectType = builder.getObjectType(global);
        InternalReadAccessor globalExtractor = new GlobalExtractor(global.getName(), objectType);
        return new Declaration(global.getName(), globalExtractor, new Pattern(0, objectType));
    }
}
Also used : Pattern(org.drools.core.rule.Pattern) ObjectType(org.drools.core.spi.ObjectType) GlobalExtractor(org.drools.core.spi.GlobalExtractor) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) Declaration(org.drools.core.rule.Declaration) Global(org.drools.model.Global)

Example 17 with ObjectType

use of org.drools.core.spi.ObjectType in project drools by kiegroup.

the class CepEspTest method testEventExpiration3.

@Test(timeout = 10000)
public void testEventExpiration3() throws Exception {
    // read in the source
    KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    conf.setOption(EventProcessingOption.STREAM);
    final KieBase kbase = loadKnowledgeBase(conf, "test_CEP_EventExpiration3.drl");
    Map<ObjectType, ObjectTypeNode> objectTypeNodes = ((KnowledgeBaseImpl) kbase).getRete().getObjectTypeNodes(EntryPointId.DEFAULT);
    ObjectTypeNode node = objectTypeNodes.get(new ClassObjectType(StockTick.class));
    assertNotNull(node);
    // the expiration policy @expires(10m) should override the temporal operator usage
    assertEquals(TimeIntervalParser.parse("10m")[0] + 1, node.getExpirationOffset());
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) ObjectType(org.drools.core.spi.ObjectType) ClassObjectType(org.drools.core.base.ClassObjectType) ClassObjectType(org.drools.core.base.ClassObjectType) StockTick(org.drools.compiler.StockTick) KieBase(org.kie.api.KieBase) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) Test(org.junit.Test)

Example 18 with ObjectType

use of org.drools.core.spi.ObjectType in project drools by kiegroup.

the class QueryElementBuilder method build.

@SuppressWarnings("unchecked")
public RuleConditionElement build(RuleBuildContext context, BaseDescr descr, QueryImpl query) {
    PatternDescr patternDescr = (PatternDescr) descr;
    Declaration[] params = query.getParameters();
    List<BaseDescr> args = (List<BaseDescr>) patternDescr.getDescrs();
    List<Declaration> requiredDeclarations = new ArrayList<Declaration>();
    ObjectType argsObjectType = ClassObjectType.ObjectArray_ObjectType;
    InternalReadAccessor arrayReader = new SelfReferenceClassFieldReader(Object[].class);
    Pattern pattern = new Pattern(context.getNextPatternId(), 0, argsObjectType, null);
    if (!StringUtils.isEmpty(patternDescr.getIdentifier())) {
        if (query.isAbductive()) {
            Declaration declr = context.getDeclarationResolver().getDeclaration(patternDescr.getIdentifier());
            if (declr != null && !patternDescr.isUnification()) {
                context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Duplicate declaration " + patternDescr.getIdentifier() + ", unable to bind abducted value"));
            }
        } else {
            context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Query binding is not supported by non-abductive queries : " + patternDescr.getIdentifier()));
        }
    }
    boolean addAbductiveReturnArgument = query.isAbductive() && !StringUtils.isEmpty(patternDescr.getIdentifier()) && args.size() < params.length;
    if (addAbductiveReturnArgument) {
        ExprConstraintDescr extraDescr = new ExprConstraintDescr(patternDescr.getIdentifier());
        extraDescr.setPosition(patternDescr.getConstraint().getDescrs().size());
        extraDescr.setType(ExprConstraintDescr.Type.POSITIONAL);
        args.add(extraDescr);
    }
    QueryArgument[] arguments = new QueryArgument[params.length];
    // Deal with the constraints, both positional and bindings
    for (BaseDescr base : args) {
        String expression = null;
        boolean isPositional = false;
        boolean isBinding = false;
        BindingDescr bind = null;
        ConstraintConnectiveDescr result = null;
        if (base instanceof BindingDescr) {
            bind = (BindingDescr) base;
            expression = bind.getVariable() + (bind.isUnification() ? " := " : " : ") + bind.getExpression();
            isBinding = true;
        } else {
            if (base instanceof ExprConstraintDescr) {
                ExprConstraintDescr ecd = (ExprConstraintDescr) base;
                expression = ecd.getExpression();
                isPositional = ecd.getType() == ExprConstraintDescr.Type.POSITIONAL;
            } else {
                expression = base.getText();
            }
            result = parseExpression(context, patternDescr, expression);
            if (result == null) {
                // error, can't parse expression.
                context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Unable to parse constraint: \n" + expression));
                continue;
            }
            isBinding = result.getDescrs().size() == 1 && result.getDescrs().get(0) instanceof BindingDescr;
            if (isBinding) {
                bind = (BindingDescr) result.getDescrs().get(0);
            }
        }
        if ((!isPositional) && (!isBinding)) {
            // error, can't have non binding slots.
            context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Query's must use positional or bindings, not field constraints:\n" + expression));
        } else if (isPositional && isBinding) {
            // error, can't have positional binding slots.
            context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Query's can't use positional bindings:\n" + expression));
        } else if (isPositional) {
            processPositional(context, query, params, arguments, requiredDeclarations, arrayReader, pattern, base, expression, result);
        } else {
            // it is binding
            processBinding(context, descr, params, arguments, requiredDeclarations, arrayReader, pattern, bind);
        }
    }
    List<Integer> varIndexList = new ArrayList<Integer>();
    for (int i = 0; i < arguments.length; i++) {
        if (!(arguments[i] instanceof QueryArgument.Declr)) {
            if (arguments[i] instanceof QueryArgument.Var) {
                varIndexList.add(i);
            }
            continue;
        }
        Class actual = ((QueryArgument.Declr) arguments[i]).getArgumentClass();
        Declaration formalArgument = query.getParameters()[i];
        Class formal = formalArgument.getDeclarationClass();
        // input argument require a broader type, while output types require a narrower type, so we check for both.
        if (!ClassUtils.isTypeCompatibleWithArgumentType(actual, formal) && !ClassUtils.isTypeCompatibleWithArgumentType(formal, actual)) {
            context.addError(new DescrBuildError(context.getParentDescr(), descr, null, "Query is being invoked with known argument of type " + actual + " at position " + i + ", but the expected query argument is of type " + formal));
        }
    }
    return new QueryElement(pattern, query.getName(), arguments, toIntArray(varIndexList), requiredDeclarations.toArray(new Declaration[requiredDeclarations.size()]), !patternDescr.isQuery(), query.isAbductive());
}
Also used : BindingDescr(org.drools.compiler.lang.descr.BindingDescr) QueryArgument(org.drools.core.rule.QueryArgument) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) ArrayList(java.util.ArrayList) QueryElement(org.drools.core.rule.QueryElement) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) ArrayList(java.util.ArrayList) List(java.util.List) Declaration(org.drools.core.rule.Declaration) ConstraintConnectiveDescr(org.drools.compiler.lang.descr.ConstraintConnectiveDescr) Pattern(org.drools.core.rule.Pattern) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) BaseDescr(org.drools.compiler.lang.descr.BaseDescr) ExprConstraintDescr(org.drools.compiler.lang.descr.ExprConstraintDescr)

Example 19 with ObjectType

use of org.drools.core.spi.ObjectType in project drools by kiegroup.

the class PatternBuilder method buildXPathDescr.

private Constraint buildXPathDescr(RuleBuildContext context, PatternDescr patternDescr, Pattern pattern, BaseDescr descr, MVELDumper.MVELDumperContext mvelCtx) {
    String expression = ((ExpressionDescr) descr).getExpression();
    XpathAnalysis xpathAnalysis = XpathAnalysis.analyze(expression);
    if (xpathAnalysis.hasError()) {
        registerDescrBuildError(context, patternDescr, "Invalid xpath expression '" + expression + "': " + xpathAnalysis.getError());
        return null;
    }
    XpathConstraint xpathConstraint = new XpathConstraint();
    ObjectType objectType = pattern.getObjectType();
    Class<?> patternClass = objectType.getClassType();
    List<Class<?>> backReferenceClasses = new ArrayList<Class<?>>();
    backReferenceClasses.add(patternClass);
    XpathBackReference backRef = new XpathBackReference(pattern, backReferenceClasses);
    pattern.setBackRefDeclarations(backRef);
    ObjectType originalType = pattern.getObjectType();
    ObjectType currentObjectType = originalType;
    mvelCtx.setInXpath(true);
    try {
        for (XpathAnalysis.XpathPart part : xpathAnalysis) {
            XpathConstraint.XpathChunk xpathChunk = xpathConstraint.addChunck(patternClass, part.getField(), part.getIndex(), part.isIterate(), part.isLazy());
            // make sure the Pattern is wired up to correct ClassObjectType and set as a target for rewiring
            context.getPkg().getClassFieldAccessorStore().wireObjectType(currentObjectType, xpathChunk);
            if (xpathChunk == null) {
                registerDescrBuildError(context, patternDescr, "Invalid xpath expression '" + expression + "': cannot access " + part.getField() + " on " + patternClass);
                pattern.setObjectType(originalType);
                return null;
            }
            if (part.getInlineCast() != null) {
                try {
                    patternClass = context.getDialect().getTypeResolver().resolveType(part.getInlineCast());
                } catch (ClassNotFoundException e) {
                    registerDescrBuildError(context, patternDescr, "Unknown class " + part.getInlineCast() + " in xpath expression '" + expression + "'");
                    return null;
                }
                part.addInlineCastConstraint(patternClass);
                currentObjectType = getObjectType(context, patternDescr, patternClass.getName());
                xpathChunk.setReturnedType(currentObjectType);
            } else {
                patternClass = xpathChunk.getReturnedClass();
                currentObjectType = getObjectType(context, patternDescr, patternClass.getName());
            }
            pattern.setObjectType(currentObjectType);
            backReferenceClasses.add(0, patternClass);
            backRef.reset();
            for (String constraint : part.getConstraints()) {
                ConstraintConnectiveDescr result = parseExpression(context, patternDescr, new ExprConstraintDescr(constraint), constraint);
                if (result == null) {
                    continue;
                }
                for (Constraint c : build(context, patternDescr, pattern, result, mvelCtx)) {
                    xpathChunk.addConstraint(c);
                }
            }
        }
    } finally {
        mvelCtx.setInXpath(false);
        pattern.setBackRefDeclarations(null);
        pattern.setObjectType(originalType);
    }
    xpathConstraint.setXpathStartDeclaration(patternDescr.getXpathStartDeclaration());
    if (descr instanceof BindingDescr) {
        xpathConstraint.setDeclaration(pattern.addDeclaration(((BindingDescr) descr).getVariable()));
    }
    return xpathConstraint;
}
Also used : XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) BindingDescr(org.drools.compiler.lang.descr.BindingDescr) XpathConstraint(org.drools.core.rule.constraint.XpathConstraint) NegConstraint(org.drools.core.rule.constraint.NegConstraint) Constraint(org.drools.core.spi.Constraint) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) EvaluatorConstraint(org.drools.core.rule.constraint.EvaluatorConstraint) PredicateConstraint(org.drools.core.rule.PredicateConstraint) ArrayList(java.util.ArrayList) XpathBackReference(org.drools.core.rule.XpathBackReference) AcceptsClassObjectType(org.drools.core.spi.AcceptsClassObjectType) FactTemplateObjectType(org.drools.core.facttemplates.FactTemplateObjectType) ObjectType(org.drools.core.spi.ObjectType) ClassObjectType(org.drools.core.base.ClassObjectType) ExpressionDescr(org.drools.compiler.lang.descr.ExpressionDescr) XpathPart(org.drools.compiler.rule.builder.XpathAnalysis.XpathPart) ConstraintConnectiveDescr(org.drools.compiler.lang.descr.ConstraintConnectiveDescr) ExprConstraintDescr(org.drools.compiler.lang.descr.ExprConstraintDescr)

Example 20 with ObjectType

use of org.drools.core.spi.ObjectType in project drools by kiegroup.

the class PatternBuilder method build.

/**
 * Build a pattern for the given descriptor in the current
 * context and using the given utils object
 */
public RuleConditionElement build(RuleBuildContext context, PatternDescr patternDescr, Pattern prefixPattern) {
    if (patternDescr.getObjectType() == null) {
        lookupObjectType(context, patternDescr);
    }
    if (patternDescr.getObjectType() == null || patternDescr.getObjectType().equals("")) {
        registerDescrBuildError(context, patternDescr, "ObjectType not correctly defined");
        return null;
    }
    ObjectType objectType = getObjectType(context, patternDescr);
    if (objectType == null) {
        // if the objectType doesn't exist it has to be query
        return buildQuery(context, patternDescr, patternDescr);
    }
    Pattern pattern = buildPattern(context, patternDescr, objectType);
    processClassObjectType(context, objectType, pattern);
    processAnnotations(context, patternDescr, pattern);
    processSource(context, patternDescr, pattern);
    processConstraintsAndBinds(context, patternDescr, pattern);
    processBehaviors(context, patternDescr, pattern);
    if (!pattern.hasNegativeConstraint() && "on".equals(System.getProperty("drools.negatable"))) {
        // this is a non-negative pattern, so we must inject the constraint
        pattern.addConstraint(new NegConstraint(false));
    }
    // poping the pattern
    context.getDeclarationResolver().popBuildStack();
    return pattern;
}
Also used : AcceptsClassObjectType(org.drools.core.spi.AcceptsClassObjectType) FactTemplateObjectType(org.drools.core.facttemplates.FactTemplateObjectType) ObjectType(org.drools.core.spi.ObjectType) ClassObjectType(org.drools.core.base.ClassObjectType) Pattern(org.drools.core.rule.Pattern) NegConstraint(org.drools.core.rule.constraint.NegConstraint)

Aggregations

ObjectType (org.drools.core.spi.ObjectType)33 ClassObjectType (org.drools.core.base.ClassObjectType)32 Test (org.junit.Test)17 Pattern (org.drools.core.rule.Pattern)13 Declaration (org.drools.core.rule.Declaration)7 FactTemplateObjectType (org.drools.core.facttemplates.FactTemplateObjectType)5 ObjectTypeNode (org.drools.core.reteoo.ObjectTypeNode)5 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)5 InternalFactHandle (org.drools.core.common.InternalFactHandle)4 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)4 KnowledgePackageImpl (org.drools.core.definitions.impl.KnowledgePackageImpl)4 TypeDeclaration (org.drools.core.rule.TypeDeclaration)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)3 DialectCompiletimeRegistry (org.drools.compiler.compiler.DialectCompiletimeRegistry)3 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)3 RuleBuildContext (org.drools.compiler.rule.builder.RuleBuildContext)3 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)3 StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)3