Search code examples
javaeclipsefile-iodrools

Drools file not found exception


I have been able to succesfully read in rules from the directory src/main/rules and my drools project works just fine.

My issue arises however when I want to read a ruleset from a different directory for example I have a second drools project with identical rules. attempting to read in the rules from /home/user/Documents/workspace/OtherProject/src/main/ruls/Ruleset.drl results in the error

"/home/user/Documents/workspace/DroolsProject/src/main/rules/Ruleset.drl" cannot be opened because it does not exist

I have checked multiple times that the file exists, even copying and pasting the output from pwd to my PATH variable (in the drools project) with no luck.

private static KnowledgeBase readKnowledgeBase(String ruleSet) throws Exception {
    KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    builder.add(
            ResourceFactory.newClassPathResource(
                    "/home/user/Documents/workspace/DroolsProject/src/main/rules/Ruleset.drl"),
            ResourceType.DRL);
    KnowledgeBuilderErrors errors = builder.getErrors();
    if (errors.size() > 0) {
        for (KnowledgeBuilderError error : errors)
            System.err.println(error);
        throw new IllegalArgumentException("Could not parse knowledge :(");
    }
    KnowledgeBase base = KnowledgeBaseFactory.newKnowledgeBase();
    base.addKnowledgePackages(builder.getKnowledgePackages());
    return base;
}

This is the method that I am using to load the rules.

The end goal is to upload a rule file to a server (probably to /tmp) and run the the project using said rule file.


Solution

  • You can follow below approach to load rule file from filesystem:

    KieServices kieServices = KieServices.Factory.get();
    KieFileSystem kfs = kieServices.newKieFileSystem();
    
    File file = new File("path/to/Rule.drl");
    org.kie.api.io.Resource resource = kieServices.getResources().newFileSystemResource(file).setResourceType(ResourceType.DRL);
    kfs.write(resource);
    
    KieBuilder Kiebuilder = kieServices.newKieBuilder(kfs);
    Kiebuilder.buildAll();
    KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
    KieSession ksession = kieContainer.newKieSession();