Search in sources :

Example 6 with ObjectType

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

the class MVELSalienceBuilderTest method setUp.

@Before
public void setUp() throws Exception {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.addAttribute(new AttributeDescr("salience", "(p.age + 20)/2"));
    ruleDescr.setConsequence("");
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
    DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect("mvel");
    context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);
    final InstrumentedDeclarationScopeResolver declarationResolver = new InstrumentedDeclarationScopeResolver();
    final ObjectType personObjeectType = new ClassObjectType(Person.class);
    final Pattern pattern = new Pattern(0, personObjeectType);
    final PatternExtractor extractor = new PatternExtractor(personObjeectType);
    final Declaration declaration = new Declaration("p", extractor, pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("p", declaration);
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);
    kBase = KnowledgeBaseFactory.newKnowledgeBase();
    SalienceBuilder salienceBuilder = new MVELSalienceBuilder();
    salienceBuilder.build(context);
    ((MVELSalienceExpression) context.getRule().getSalience()).compile((MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel"));
}
Also used : Pattern(org.drools.core.rule.Pattern) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) ClassObjectType(org.drools.core.base.ClassObjectType) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) HashMap(java.util.HashMap) SalienceBuilder(org.drools.compiler.rule.builder.SalienceBuilder) PatternExtractor(org.drools.core.spi.PatternExtractor) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) MVELSalienceExpression(org.drools.core.base.mvel.MVELSalienceExpression) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) Declaration(org.drools.core.rule.Declaration) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) AttributeDescr(org.drools.compiler.lang.descr.AttributeDescr) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Before(org.junit.Before)

Example 7 with ObjectType

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

the class QueryBuilder method build.

public Pattern build(final RuleBuildContext context, final QueryDescr queryDescr) {
    ObjectType queryObjectType = ClassObjectType.DroolsQuery_ObjectType;
    final Pattern pattern = new Pattern(context.getNextPatternId(), // offset is 0 by default
    0, queryObjectType, null);
    final InternalReadAccessor extractor = PatternBuilder.getFieldReadAccessor(context, queryDescr, pattern, "name", null, true);
    final QueryNameConstraint constraint = new QueryNameConstraint(extractor, queryDescr.getName());
    PatternBuilder.registerReadAccessor(context, queryObjectType, "name", constraint);
    // adds appropriate constraint to the pattern
    pattern.addConstraint(constraint);
    ObjectType argsObjectType = ClassObjectType.DroolsQuery_ObjectType;
    InternalReadAccessor arrayExtractor = PatternBuilder.getFieldReadAccessor(context, queryDescr, null, argsObjectType, "elements", null, true);
    QueryImpl query = ((QueryImpl) context.getRule());
    String[] params;
    String[] types;
    int numParams = queryDescr.getParameters().length;
    if (query.isAbductive()) {
        params = Arrays.copyOf(queryDescr.getParameters(), queryDescr.getParameters().length + 1);
        types = Arrays.copyOf(queryDescr.getParameterTypes(), queryDescr.getParameterTypes().length + 1);
    } else {
        params = queryDescr.getParameters();
        types = queryDescr.getParameterTypes();
    }
    Declaration[] declarations = new Declaration[params.length];
    Class<?> abductionReturnKlass = null;
    if (query.isAbductive()) {
        Abductive abductive = queryDescr.getTypedAnnotation(Abductive.class);
        abductionReturnKlass = abductive.target();
        params[numParams] = "";
        types[numParams] = abductionReturnKlass.getName();
    }
    int i = 0;
    try {
        for (i = 0; i < params.length; i++) {
            Declaration declr = pattern.addDeclaration(params[i]);
            // this bit is different, notice its the ArrayElementReader that we wire up to, not the declaration.
            ArrayElementReader reader = new ArrayElementReader(arrayExtractor, i, context.getDialect().getTypeResolver().resolveType(types[i]));
            PatternBuilder.registerReadAccessor(context, argsObjectType, "elements", reader);
            declr.setReadAccessor(reader);
            declarations[i] = declr;
        }
        query.setParameters(declarations);
    } catch (ClassNotFoundException e) {
        context.addError(new DescrBuildError(context.getParentDescr(), queryDescr, e, "Unable to resolve type '" + types[i] + " for parameter" + params[i]));
    }
    context.setPrefixPattern(pattern);
    if (query.isAbductive()) {
        String returnName = "";
        try {
            AnnotationDescr ann = queryDescr.getAnnotation(Abductive.class);
            Object[] argsVal = ((Object[]) ann.getValue("args"));
            String[] args = argsVal != null ? Arrays.copyOf(argsVal, argsVal.length, String[].class) : null;
            returnName = types[numParams];
            ObjectType objectType = new ClassObjectType(abductionReturnKlass, false);
            objectType = context.getPkg().getClassFieldAccessorStore().wireObjectType(objectType, (AbductiveQuery) query);
            ((AbductiveQuery) query).setReturnType(objectType, params, args, declarations);
        } catch (NoSuchMethodException e) {
            context.addError(new DescrBuildError(context.getParentDescr(), queryDescr, e, "Unable to resolve abducible constructor for type : " + returnName + " with types " + Arrays.toString(types)));
        } catch (IllegalArgumentException e) {
            context.addError(new DescrBuildError(context.getParentDescr(), queryDescr, e, e.getMessage()));
        }
    }
    return pattern;
}
Also used : Pattern(org.drools.core.rule.Pattern) QueryNameConstraint(org.drools.core.rule.constraint.QueryNameConstraint) ClassObjectType(org.drools.core.base.ClassObjectType) Abductive(org.drools.core.beliefsystem.abductive.Abductive) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) QueryNameConstraint(org.drools.core.rule.constraint.QueryNameConstraint) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) QueryImpl(org.drools.core.rule.QueryImpl) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) Declaration(org.drools.core.rule.Declaration) AbductiveQuery(org.drools.core.rule.AbductiveQuery)

Example 8 with ObjectType

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

the class CepEspTest method testEventExpiration2.

@Test(timeout = 10000)
public void testEventExpiration2() throws Exception {
    // read in the source
    KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(EventProcessingOption.STREAM);
    KieBase kbase = loadKnowledgeBase(kbc, "test_CEP_EventExpiration2.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 9 with ObjectType

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

the class CrossProductTest method setUp.

@Before
public void setUp() throws Exception {
    final ObjectType list1ObjectType = new ClassObjectType(String.class);
    final ObjectType list2ObjectType = new ClassObjectType(String.class);
    final RuleImpl rule = new RuleImpl("rule-1");
    final Pattern list1Pattern = new Pattern(0, list1ObjectType, "s1");
    final Pattern list2Pattern = new Pattern(1, list2ObjectType, "s2");
    rule.addPattern(list1Pattern);
    rule.addPattern(list2Pattern);
    final Declaration s1Declaration = rule.getDeclaration("s1");
    final Declaration s2Declaration = rule.getDeclaration("s2");
    this.values = new ArrayList();
    rule.setConsequence(new Consequence() {

        private static final long serialVersionUID = 510l;

        public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
            final String s1 = (String) knowledgeHelper.get(s1Declaration);
            final String s2 = (String) knowledgeHelper.get(s2Declaration);
            CrossProductTest.this.values.add(new String[] { s1, s2 });
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        }

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            return "default";
        }
    });
    this.pkg = new KnowledgePackageImpl("org.drools");
    this.pkg.addRule(rule);
}
Also used : Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectOutput(java.io.ObjectOutput) WorkingMemory(org.drools.core.WorkingMemory) ArrayList(java.util.ArrayList) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) IOException(java.io.IOException) IOException(java.io.IOException) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration) ObjectInput(java.io.ObjectInput) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) Before(org.junit.Before)

Example 10 with ObjectType

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

the class PatternBuilder method attachObjectTypeNode.

private void attachObjectTypeNode(final BuildContext context, final BuildUtils utils, final Pattern pattern) {
    boolean objectMemory = context.isObjectTypeNodeMemoryEnabled();
    ObjectType objectType = pattern.getObjectType();
    if (pattern.getObjectType() instanceof ClassObjectType) {
        // Is this the query node, if so we don't want any memory
        if (DroolsQuery.class == ((ClassObjectType) pattern.getObjectType()).getClassType()) {
            context.setTupleMemoryEnabled(false);
            context.setObjectTypeNodeMemoryEnabled(false);
        }
    }
    ObjectTypeNode otn = context.getComponentFactory().getNodeFactoryService().buildObjectTypeNode(context.getNextId(), (EntryPointNode) context.getObjectSource(), objectType, context);
    if (objectType.isEvent() && EventProcessingOption.STREAM.equals(context.getKnowledgeBase().getConfiguration().getEventProcessingMode())) {
        ExpirationSpec expirationSpec = getExpirationForType(context, objectType);
        if (expirationSpec.offset != NEVER_EXPIRES && expirationSpec.hard) {
            // hard expiration is set, so use it
            otn.setExpirationOffset(expirationSpec.offset);
        } else {
            // otherwise calculate it based on behaviours and temporal constraints
            long offset = NEVER_EXPIRES;
            for (Behavior behavior : pattern.getBehaviors()) {
                if (behavior.getExpirationOffset() != NEVER_EXPIRES) {
                    offset = Math.max(behavior.getExpirationOffset(), offset);
                }
            }
            // if there's no implicit expiration uses the (eventually set) soft one
            if (offset == NEVER_EXPIRES && !expirationSpec.hard) {
                offset = expirationSpec.offset;
            }
            long distance = context.getExpirationOffset(pattern);
            if (distance == NEVER_EXPIRES) {
                // it means the rules have no temporal constraints, or
                // the constraints require events to be hold forever. In this
                // case, we allow type declarations to override the implicit
                // expiration offset by defining an expiration policy with the
                // @expires tag
                otn.setExpirationOffset(offset);
            } else {
                otn.setExpirationOffset(Math.max(distance, offset));
            }
        }
    }
    context.setObjectSource(utils.attachNode(context, otn));
    context.setObjectTypeNodeMemoryEnabled(objectMemory);
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) Behavior(org.drools.core.rule.Behavior)

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