Search in sources :

Example 16 with KiePackage

use of org.kie.api.definition.KiePackage in project drools by kiegroup.

the class AddRuleTest method testDynamicallyAddInitialFactRule.

@Test
public void testDynamicallyAddInitialFactRule() throws Exception {
    String rule = "package org.drools.compiler.test\n" + "global java.util.List list\n" + "rule xxx when\n" + "   i:Integer()\n" + "then\n" + "   list.add(i);\n" + "end";
    final InternalKnowledgeBase kbase = (InternalKnowledgeBase) SerializationHelper.serializeObject(loadKnowledgeBaseFromString(rule));
    final KieSession session = createKnowledgeSession(kbase);
    final List list = new ArrayList();
    session.setGlobal("list", list);
    session.insert(5);
    session.fireAllRules();
    assertEquals(5, list.get(0));
    rule = "package org.drools.compiler.test\n" + "global java.util.List list\n" + "rule xxx when\n" + "then\n" + "   list.add(\"x\");\n" + "end";
    final Collection<KiePackage> kpkgs = loadKnowledgePackagesFromString(rule);
    kbase.addPackages(kpkgs);
    session.fireAllRules();
    assertEquals("x", list.get(1));
}
Also used : KiePackage(org.kie.api.definition.KiePackage) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 17 with KiePackage

use of org.kie.api.definition.KiePackage 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 18 with KiePackage

use of org.kie.api.definition.KiePackage 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 19 with KiePackage

use of org.kie.api.definition.KiePackage in project drools by kiegroup.

the class KieMetaInfoBuilder method generateKieModuleMetaInfo.

public KieModuleMetaInfo generateKieModuleMetaInfo(ResourceStore trgMfs) {
    // TODO: I think this method is wrong because it is only inspecting packages that are included
    // in at least one kbase, but I believe it should inspect all packages, even if not included in
    // any kbase, as they could be included in the future
    Map<String, TypeMetaInfo> typeInfos = new HashMap<String, TypeMetaInfo>();
    Map<String, Set<String>> rulesPerPackage = new HashMap<String, Set<String>>();
    KieModuleModel kieModuleModel = kModule.getKieModuleModel();
    for (String kieBaseName : kieModuleModel.getKieBaseModels().keySet()) {
        KnowledgeBuilderImpl kBuilder = (KnowledgeBuilderImpl) kModule.getKnowledgeBuilderForKieBase(kieBaseName);
        Map<String, PackageRegistry> pkgRegistryMap = kBuilder.getPackageRegistry();
        KieModuleCache.KModuleCache.Builder _kmoduleCacheBuilder = createCacheBuilder();
        KieModuleCache.CompilationData.Builder _compData = createCompilationData();
        for (KiePackage kPkg : kBuilder.getKnowledgePackages()) {
            PackageRegistry pkgRegistry = pkgRegistryMap.get(kPkg.getName());
            JavaDialectRuntimeData runtimeData = (JavaDialectRuntimeData) pkgRegistry.getDialectRuntimeRegistry().getDialectData("java");
            List<String> types = new ArrayList<String>();
            for (FactType factType : kPkg.getFactTypes()) {
                Class<?> typeClass = ((ClassDefinition) factType).getDefinedClass();
                TypeDeclaration typeDeclaration = pkgRegistry.getPackage().getTypeDeclaration(typeClass);
                if (typeDeclaration != null) {
                    typeInfos.put(typeClass.getName(), new TypeMetaInfo(typeDeclaration));
                }
                String className = factType.getName();
                String internalName = className.replace('.', '/') + ".class";
                if (trgMfs != null) {
                    byte[] bytes = runtimeData.getBytecode(internalName);
                    if (bytes != null) {
                        trgMfs.write(internalName, bytes, true);
                    }
                }
                types.add(internalName);
            }
            Set<String> rules = rulesPerPackage.get(kPkg.getName());
            if (rules == null) {
                rules = new HashSet<String>();
            }
            for (Rule rule : kPkg.getRules()) {
                if (!rules.contains(rule.getName())) {
                    rules.add(rule.getName());
                }
            }
            if (!rules.isEmpty()) {
                rulesPerPackage.put(kPkg.getName(), rules);
            }
            addToCompilationData(_compData, runtimeData, types);
        }
        _kmoduleCacheBuilder.addCompilationData(_compData.build());
        if (trgMfs != null) {
            writeCompilationDataToTrg(_kmoduleCacheBuilder.build(), kieBaseName, trgMfs);
        }
    }
    return new KieModuleMetaInfo(typeInfos, rulesPerPackage);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) ClassDefinition(org.drools.core.factmodel.ClassDefinition) KiePackage(org.kie.api.definition.KiePackage) JavaDialectRuntimeData(org.drools.core.rule.JavaDialectRuntimeData) FactType(org.kie.api.definition.type.FactType) TypeMetaInfo(org.drools.core.rule.TypeMetaInfo) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) KieModuleModel(org.kie.api.builder.model.KieModuleModel) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) KieModuleMetaInfo(org.drools.core.rule.KieModuleMetaInfo) Rule(org.kie.api.definition.rule.Rule) TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Example 20 with KiePackage

use of org.kie.api.definition.KiePackage in project drools by kiegroup.

the class DescrBuilderTest method testDeclare.

@Test
public void testDeclare() throws InstantiationException, IllegalAccessException {
    PackageDescr pkg = DescrFactory.newPackage().name("org.beans").newDeclare().type().name("StockTick").newAnnotation("role").value("event").end().newAnnotation("author").value("bob").end().newField("symbol").type("String").end().newField("price").type("double").end().end().newDeclare().enumerative().name("Planets").newAnnotation("kind").value("enum").end().newEnumLiteral("earth").constructorArg("6.0").constructorArg("10.0").end().newEnumLiteral("jupiter").constructorArg("44.0").constructorArg("50.0").end().newField("mass").type("double").end().newField("radius").type("double").end().end().getDescr();
    assertEquals(1, pkg.getTypeDeclarations().size());
    assertEquals(1, pkg.getEnumDeclarations().size());
    KiePackage kpkg = compilePkgDescr(pkg);
    assertEquals("org.beans", kpkg.getName());
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(Collections.singletonList(kpkg));
    FactType stType = kbase.getFactType("org.beans", "StockTick");
    assertNotNull(stType);
    Object st = stType.newInstance();
    stType.set(st, "symbol", "RHT");
    stType.set(st, "price", 10);
    assertEquals("RHT", stType.get(st, "symbol"));
// stType.getAnnotation("author"); TODO: implement support for this
}
Also used : KiePackage(org.kie.api.definition.KiePackage) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) FactType(org.kie.api.definition.type.FactType) Test(org.junit.Test)

Aggregations

KiePackage (org.kie.api.definition.KiePackage)124 Test (org.junit.Test)93 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)80 KieSession (org.kie.api.runtime.KieSession)70 ArrayList (java.util.ArrayList)44 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)39 List (java.util.List)25 Cheese (org.drools.compiler.Cheese)22 Person (org.drools.compiler.Person)18 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)17 InternalFactHandle (org.drools.core.common.InternalFactHandle)15 IteratorToList (org.drools.compiler.integrationtests.IteratorToList)11 EntryPoint (org.kie.api.runtime.rule.EntryPoint)10 Resource (org.kie.api.io.Resource)9 StringReader (java.io.StringReader)8 HashMap (java.util.HashMap)8 FactHandle (org.kie.api.runtime.rule.FactHandle)8 Map (java.util.Map)7 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)7 KieBase (org.kie.api.KieBase)7