Search in sources :

Example 1 with KnowledgePackageImpl

use of org.drools.core.definitions.impl.KnowledgePackageImpl in project drools by kiegroup.

the class MarshallingTest method testScheduledActivation.

@Test
@Ignore("This test is suspicious to say the least...")
public void testScheduledActivation() {
    KnowledgeBaseImpl knowledgeBase = (KnowledgeBaseImpl) KnowledgeBaseFactory.newKnowledgeBase();
    KnowledgePackageImpl impl = new KnowledgePackageImpl("test");
    BuildContext buildContext = new BuildContext(knowledgeBase);
    // simple rule that fires after 10 seconds
    final RuleImpl rule = new RuleImpl("test-rule");
    new RuleTerminalNode(1, new MockTupleSource(2), rule, rule.getLhs(), 0, buildContext);
    final List<String> fired = new ArrayList<String>();
    rule.setConsequence(new Consequence() {

        public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {
            fired.add("a");
        }

        public String getName() {
            return "default";
        }
    });
    rule.setTimer(new DurationTimer(10000));
    rule.setPackage("test");
    impl.addRule(rule);
    knowledgeBase.addPackages(Collections.singleton(impl));
    SessionConfiguration config = SessionConfiguration.newInstance();
    config.setClockType(ClockType.PSEUDO_CLOCK);
    KieSession ksession = knowledgeBase.newKieSession(config, KieServices.get().newEnvironment());
    PseudoClockScheduler scheduler = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock();
    Marshaller marshaller = MarshallerFactory.newMarshaller(knowledgeBase);
    ksession.insert("cheese");
    assertTrue(fired.isEmpty());
    // marshall, then unmarshall session
    readWrite(knowledgeBase, ksession, config);
    // the activations should fire after 10 seconds
    assertTrue(fired.isEmpty());
    scheduler.advanceTime(12, TimeUnit.SECONDS);
    assertFalse(fired.isEmpty());
}
Also used : Marshaller(org.kie.api.marshalling.Marshaller) WorkingMemory(org.drools.core.WorkingMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) ArrayList(java.util.ArrayList) Consequence(org.drools.core.spi.Consequence) KnowledgeBaseImpl(org.drools.core.impl.KnowledgeBaseImpl) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) IOException(java.io.IOException) PseudoClockScheduler(org.drools.core.time.impl.PseudoClockScheduler) DurationTimer(org.drools.core.time.impl.DurationTimer) MockTupleSource(org.drools.core.reteoo.MockTupleSource) BuildContext(org.drools.core.reteoo.builder.BuildContext) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) KieSession(org.kie.api.runtime.KieSession) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) SessionConfiguration(org.drools.core.SessionConfiguration) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 2 with KnowledgePackageImpl

use of org.drools.core.definitions.impl.KnowledgePackageImpl in project drools by kiegroup.

the class KnowledgeBuilderImpl method addPackageFromInputStream.

void addPackageFromInputStream(final Resource resource) throws IOException, ClassNotFoundException {
    InputStream is = resource.getInputStream();
    Object object = DroolsStreamUtils.streamIn(is, this.configuration.getClassLoader());
    is.close();
    if (object instanceof Collection) {
        // KnowledgeBuilder API
        @SuppressWarnings("unchecked") Collection<KiePackage> pkgs = (Collection<KiePackage>) object;
        for (KiePackage kpkg : pkgs) {
            overrideReSource((KnowledgePackageImpl) kpkg, resource);
            addPackage((KnowledgePackageImpl) kpkg);
        }
    } else if (object instanceof KnowledgePackageImpl) {
        // KnowledgeBuilder API
        KnowledgePackageImpl kpkg = (KnowledgePackageImpl) object;
        overrideReSource(kpkg, resource);
        addPackage(kpkg);
    } else {
        results.add(new DroolsError(resource) {

            @Override
            public String getMessage() {
                return "Unknown binary format trying to load resource " + resource.toString();
            }

            @Override
            public int[] getLines() {
                return new int[0];
            }
        });
    }
}
Also used : DroolsError(org.drools.compiler.compiler.DroolsError) KiePackage(org.kie.api.definition.KiePackage) InputStream(java.io.InputStream) Collection(java.util.Collection) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl)

Example 3 with KnowledgePackageImpl

use of org.drools.core.definitions.impl.KnowledgePackageImpl in project drools by kiegroup.

the class AbstractKieModule method createKieBase.

public InternalKnowledgeBase createKieBase(KieBaseModelImpl kBaseModel, KieProject kieProject, ResultsImpl messages, KieBaseConfiguration conf) {
    Collection<KiePackage> pkgs = getKnowledgePackagesForKieBase(kBaseModel.getName());
    if (pkgs == null) {
        KnowledgeBuilder kbuilder = kieProject.buildKnowledgePackages(kBaseModel, messages);
        if (kbuilder.hasErrors()) {
            // Messages already populated by the buildKnowlegePackages
            return null;
        }
    }
    // if we get to here, then we know the pkgs is now cached
    pkgs = getKnowledgePackagesForKieBase(kBaseModel.getName());
    if (kBaseModel.getEventProcessingMode() == EventProcessingOption.CLOUD && (conf == null || conf.getOption(EventProcessingOption.class) == EventProcessingOption.CLOUD)) {
        for (KiePackage kpkg : pkgs) {
            if (((KnowledgePackageImpl) kpkg).needsStreamMode()) {
                throw new RuntimeException("The requested KieBase \"" + kBaseModel.getName() + "\" has been set to run in CLOUD mode but requires features only available in STREAM mode");
            }
        }
    }
    ClassLoader cl = kieProject.getClassLoader();
    if (conf == null) {
        conf = getKnowledgeBaseConfiguration(kBaseModel, cl);
    } else if (conf instanceof RuleBaseConfiguration) {
        ((RuleBaseConfiguration) conf).setClassLoader(cl);
    }
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kBaseModel.getName(), conf);
    kBase.addPackages(pkgs);
    return kBase;
}
Also used : RuleBaseConfiguration(org.drools.core.RuleBaseConfiguration) CompositeKnowledgeBuilder(org.kie.internal.builder.CompositeKnowledgeBuilder) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) KiePackage(org.kie.api.definition.KiePackage) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase)

Example 4 with KnowledgePackageImpl

use of org.drools.core.definitions.impl.KnowledgePackageImpl in project drools by kiegroup.

the class KieBaseUpdater method updateResourcesIncrementally.

private int updateResourcesIncrementally(KnowledgeBuilderImpl kbuilder, CompositeKnowledgeBuilder ckbuilder) {
    int fileCount = ctx.modifiedClasses.size();
    for (ResourceChangeSet rcs : ctx.cs.getChanges().values()) {
        if (rcs.getChangeType() != ChangeType.REMOVED) {
            String resourceName = rcs.getResourceName();
            if (!resourceName.endsWith(".properties") && isFileInKBase(ctx.newKM, ctx.newKieBaseModel, resourceName)) {
                List<ResourceChange> changes = rcs.getChanges();
                if (!changes.isEmpty()) {
                    // we need to deal with individual parts of the resource
                    fileCount += AbstractKieModule.updateResource(ckbuilder, ctx.newKM, resourceName, rcs) ? 1 : 0;
                } else {
                    // the whole resource has to handled
                    if (rcs.getChangeType() == ChangeType.UPDATED) {
                        Resource resource = ctx.currentKM.getResource(resourceName);
                        kbuilder.removeObjectsGeneratedFromResource(resource);
                    }
                    fileCount += ctx.newKM.addResourceToCompiler(ckbuilder, ctx.newKieBaseModel, resourceName, rcs) ? 1 : 0;
                }
            }
        }
        for (ResourceChangeSet.RuleLoadOrder loadOrder : rcs.getLoadOrder()) {
            KnowledgePackageImpl pkg = (KnowledgePackageImpl) ctx.kBase.getKiePackage(loadOrder.getPkgName());
            if (pkg != null) {
                RuleImpl rule = pkg.getRule(loadOrder.getRuleName());
                if (rule != null) {
                    // rule can be null, if it didn't exist before
                    rule.setLoadOrder(loadOrder.getLoadOrder());
                }
            }
        }
    }
    return fileCount;
}
Also used : Resource(org.kie.api.io.Resource) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) ResourceChangeSet(org.kie.internal.builder.ResourceChangeSet) ResourceChange(org.kie.internal.builder.ResourceChange) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) InternalWorkingMemoryEntryPoint(org.drools.core.common.InternalWorkingMemoryEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint)

Example 5 with KnowledgePackageImpl

use of org.drools.core.definitions.impl.KnowledgePackageImpl in project drools by kiegroup.

the class MVELConsequenceBuilderTest method testImperativeCodeError.

@Test
public void testImperativeCodeError() throws Exception {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.setConsequence("if (cheese.price == 10) { cheese.price = 5; }");
    Properties properties = new Properties();
    properties.setProperty("drools.dialect.default", "mvel");
    KnowledgeBuilderConfigurationImpl cfg1 = new KnowledgeBuilderConfigurationImpl(properties);
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg, cfg1);
    PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect(pkgRegistry.getDialect());
    final RuleBuildContext context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);
    final InstrumentedDeclarationScopeResolver declarationResolver = new InstrumentedDeclarationScopeResolver();
    final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjeectType);
    final PatternExtractor extractor = new PatternExtractor(cheeseObjeectType);
    final Declaration declaration = new Declaration("cheese", extractor, pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("cheese", declaration);
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);
    final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
    builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final Cheese cheddar = new Cheese("cheddar", 10);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
    final AgendaItem item = new AgendaItemImpl(0, tuple, 10, null, null, null);
    final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
    kbHelper.setActivation(item);
    try {
        ((MVELConsequence) context.getRule().getConsequence()).compile((MVELDialectRuntimeData) pkgBuilder.getPackageRegistry(pkg.getName()).getDialectRuntimeRegistry().getDialectData("mvel"));
        context.getRule().getConsequence().evaluate(kbHelper, ksession);
        fail("should throw an exception, as 'if' is not allowed");
    } catch (Exception e) {
    }
    assertEquals(10, cheddar.getPrice());
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) HashMap(java.util.HashMap) Cheese(org.drools.compiler.Cheese) MVELConsequence(org.drools.core.base.mvel.MVELConsequence) Properties(java.util.Properties) AgendaItem(org.drools.core.common.AgendaItem) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) LeftTupleImpl(org.drools.core.reteoo.LeftTupleImpl) AgendaItemImpl(org.drools.core.common.AgendaItemImpl) Declaration(org.drools.core.rule.Declaration) ImportDeclaration(org.drools.core.rule.ImportDeclaration) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Pattern(org.drools.core.rule.Pattern) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) DefaultKnowledgeHelper(org.drools.core.base.DefaultKnowledgeHelper) PatternExtractor(org.drools.core.spi.PatternExtractor) DroolsParserException(org.drools.compiler.compiler.DroolsParserException) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) CompositeObjectSinkAdapterTest(org.drools.core.reteoo.CompositeObjectSinkAdapterTest) Test(org.junit.Test)

Aggregations

KnowledgePackageImpl (org.drools.core.definitions.impl.KnowledgePackageImpl)41 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)26 Test (org.junit.Test)19 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)18 ClassObjectType (org.drools.core.base.ClassObjectType)13 Pattern (org.drools.core.rule.Pattern)11 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)9 ClassFieldAccessorCache (org.drools.core.base.ClassFieldAccessorCache)9 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)8 WorkingMemory (org.drools.core.WorkingMemory)7 Consequence (org.drools.core.spi.Consequence)7 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)7 KnowledgeBuilderConfigurationImpl (org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl)6 DialectCompiletimeRegistry (org.drools.compiler.compiler.DialectCompiletimeRegistry)6 RuleBuildContext (org.drools.compiler.rule.builder.RuleBuildContext)6 Declaration (org.drools.core.rule.Declaration)6 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)6 IOException (java.io.IOException)5 PackageRegistry (org.drools.compiler.compiler.PackageRegistry)5 KnowledgeBaseImpl (org.drools.core.impl.KnowledgeBaseImpl)5