protected Collection<KnowledgePackage> compileResources(
      Map<Resource, ResourceType> resources, boolean enablePropertySpecificFacts) {
    KnowledgeBuilderConfiguration conf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();

    if (enablePropertySpecificFacts) {
      conf.setOption(PropertySpecificOption.ALLOWED);
    } else {
      conf.setOption(PropertySpecificOption.DISABLED);
    }

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(conf);
    for (Map.Entry<Resource, ResourceType> entry : resources.entrySet()) {
      kbuilder.add(entry.getKey(), entry.getValue());
      if (kbuilder.hasErrors()) {
        Logger.getLogger(Case1.class.getName())
            .log(Level.SEVERE, "Compilation Errors in {0}", entry.getKey());
        Iterator<KnowledgeBuilderError> iterator = kbuilder.getErrors().iterator();
        while (iterator.hasNext()) {
          KnowledgeBuilderError knowledgeBuilderError = iterator.next();
          Logger.getLogger(Case1.class.getName())
              .log(Level.SEVERE, knowledgeBuilderError.getMessage());
          System.out.println(knowledgeBuilderError.getMessage());
        }
        throw new IllegalStateException("Compilation Errors");
      }
    }
    return kbuilder.getKnowledgePackages();
  }
  /**
   * Creates a ksession from a kbase containing process definition
   *
   * @return
   */
  public StatefulKnowledgeSession createKnowledgeSession() {
    // Create the kbuilder
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    // Add simpleProcess.bpmn to kbuilder
    kbuilder.add(new ClassPathResource("taskTypeVarietyProcess.bpmn2"), ResourceType.BPMN2);
    kbuilder.add(new ClassPathResource("taskTypeVarietyRules.drl"), ResourceType.DRL);
    System.out.println("Compiling resources");

    // Check for errors
    if (kbuilder.hasErrors()) {
      if (kbuilder.getErrors().size() > 0) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
          System.out.println("Error building kbase: " + error.getMessage());
        }
      }
      throw new RuntimeException("Error building kbase!");
    }

    // Create a knowledge base and add the generated package
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    // return a new stateful session
    return kbase.newStatefulKnowledgeSession();
  }
  public DroolsSession(File saved, String processXML, int initialProcessInstanceId)
      throws IOException {
    this.saved = saved;

    KnowledgeBuilder kbuilder =
        KnowledgeBuilderFactory.newKnowledgeBuilder(new PackageBuilderConfiguration());
    kbuilder.add(new ReaderResource(new StringReader(processXML)), ResourceType.DRF);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    StringBuilder sb = new StringBuilder();
    if (errors.size() > 0) {

      for (KnowledgeBuilderError error : errors) {
        sb.append(error.getMessage()).append("\n");
      }

      throw new IllegalArgumentException("Could not parse knowledge:\n" + sb);
    }

    Collection<KnowledgePackage> knowledgePackages = kbuilder.getKnowledgePackages();

    Process process = knowledgePackages.iterator().next().getProcesses().iterator().next();

    processId = process.getId();

    kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(knowledgePackages);

    marshaller = MarshallerFactory.newMarshaller(kbase);

    SessionConfiguration conf = new SessionConfiguration();
    Properties p = new Properties();
    p.setProperty(
        "drools.processInstanceManagerFactory",
        HudsonProcessInstanceManagerFactory.class.getName());
    conf.addProperties(p);
    Environment env = EnvironmentFactory.newEnvironment();
    if (!saved.exists() || saved.length() == 0) {
      session = kbase.newStatefulKnowledgeSession(conf, env);
    } else {
      InputStream is = null;
      try {
        is = new FileInputStream(saved);
        session = marshaller.unmarshall(is, conf, env);
      } catch (ClassNotFoundException e) {
        throw new IOException2("Class not found while unmarshalling " + saved.getAbsolutePath(), e);
      } catch (IOException e) {
        throw new IOException2("Error while unmarshalling " + saved.getAbsolutePath(), e);
      } finally {
        is.close();
      }
    }

    ((HudsonProcessInstanceManager)
            ((InternalWorkingMemoryEntryPoint) session)
                .getInternalWorkingMemory()
                .getProcessInstanceManager())
        .setProcessCounter(initialProcessInstanceId);
  }
  private KnowledgeBuilder compileRules(Reader reader) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add(ResourceFactory.newReaderResource(reader), ResourceType.DRL);

    if (kBuilder.hasErrors()) {
      for (KnowledgeBuilderError err : kBuilder.getErrors()) {
        System.err.println(err.toString());
      }
      throw new IllegalStateException("DRL errors");
    }
    return kBuilder;
  }
 private void handleKnowledgeBuilderErrors(KnowledgeBuilder knowledgeBuilder) {
   if (knowledgeBuilder.hasErrors()) {
     StringBuilder builder = new StringBuilder(1024);
     builder.append("Drools " + knowledgeBuilder.getClass().getSimpleName() + " error occurred:");
     for (KnowledgeBuilderError knowledgeBuilderError : knowledgeBuilder.getErrors()) {
       builder.append("Error in line(s) [");
       appendLinesTo(knowledgeBuilderError.getErrorLines(), builder);
       builder.append("]:");
       builder.append(knowledgeBuilderError.getMessage());
     }
     throw new TestFluxException(builder.toString());
   }
 }
 private Collection<KnowledgePackage> buildKnowledgePackage(
     Resource resource, ResourceType resourceType) {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(resource, resourceType);
   KnowledgeBuilderErrors errors = kbuilder.getErrors();
   if (errors != null && errors.size() > 0) {
     for (KnowledgeBuilderError error : errors) {
       System.err.println("Error: " + error.getMessage());
     }
     Assert.fail("KnowledgeBase did not build");
   }
   Collection<KnowledgePackage> packages = kbuilder.getKnowledgePackages();
   return packages;
 }
Exemple #7
0
  @Override
  public KnowledgeBuilder getKnowledgeBuilder(final ClassLoader cls) {
    final KnowledgeBuilderConfiguration conf =
        KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, cls);
    final KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder(conf);
    kb.add(ResourceFactory.newClassPathResource("basic_move_rules.drl", cls), ResourceType.DRL);

    if (kb.hasErrors()) {
      for (KnowledgeBuilderError error : kb.getErrors()) {
        LOG.warn(error.getMessage() + ": " + error.getResource());
      }
    }
    return kb;
  }
  private void initializeSession() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add(new ClassPathResource("InsuranceProcessV1.bpmn"), ResourceType.BPMN2);
    if (kbuilder.hasErrors()) {
      KnowledgeBuilderErrors errors = kbuilder.getErrors();

      for (KnowledgeBuilderError error : errors) {
        System.out.println(">>> Error:" + error.getMessage());
      }
      throw new IllegalStateException(">>> Knowledge couldn't be parsed! ");
    }

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    session = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLoggerFactory.newConsoleLogger(session);

    session.addEventListener(
        new DefaultAgendaEventListener() {

          @Override
          public void afterRuleFlowGroupActivated(
              org.drools.event.rule.RuleFlowGroupActivatedEvent event) {
            session.fireAllRules();
          }
        });

    // Registers an independent mocked work item handler for each task present
    // in the process.
    PatientDataServiceWorkItemHandler patientDataHandler = new PatientDataServiceWorkItemHandler();
    session.getWorkItemManager().registerWorkItemHandler("Gather Patient Data", patientDataHandler);
    InsuranceServiceWorkItemHandler insuranceServiceHandler = new InsuranceServiceWorkItemHandler();
    session
        .getWorkItemManager()
        .registerWorkItemHandler("Insurance Service", insuranceServiceHandler);
    CompanyGatewayWorkItemHandler companyGatewayHandler = new CompanyGatewayWorkItemHandler();
    session
        .getWorkItemManager()
        .registerWorkItemHandler("External Insurance Company Service", companyGatewayHandler);
    RatesServiceWorkItemHandler ratesServiceHandler = new RatesServiceWorkItemHandler();
    session.getWorkItemManager().registerWorkItemHandler("Rates Service", ratesServiceHandler);
    InvoiceServiceWorkItemHandler invoiceServiceHandler = new InvoiceServiceWorkItemHandler();
    session.getWorkItemManager().registerWorkItemHandler("Invoice Service", invoiceServiceHandler);
  }
  public static void main(String[] args) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add(ResourceFactory.newClassPathResource("drools/test1.drl"), ResourceType.DRL);
    if (kBuilder.hasErrors()) {
      System.out.println("rule has error : ");
      for (KnowledgeBuilderError kbError : kBuilder.getErrors()) {
        System.out.println(kbError.getMessage());
      }
    }

    KnowledgeBase kb = KnowledgeBaseFactory.newKnowledgeBase();
    kb.addKnowledgePackages(kBuilder.getKnowledgePackages());
    StatefulKnowledgeSession session = kb.newStatefulKnowledgeSession();

    Order order = new Order();
    order.setTid("1023222");
    List<String> productList = Lists.newArrayList();
    productList.add("123");
    productList.add("234");
    order.setHasProducts(productList);
    session.insert(order);
    session.fireAllRules();
    session.dispose();
  }
  public void execute() throws MojoExecutionException {
    // find all the rules items and load them into a package
    try {

      // Need to load the build classpath
      @SuppressWarnings("unchecked")
      List<Dependency> dependencies = project.getDependencies();
      List<URL> url = new ArrayList<URL>();
      url.add(outputDirectory.toURI().toURL());
      for (Dependency d : dependencies) {
        String scope = d.getScope();
        if (!Artifact.SCOPE_TEST.equals(scope)) {
          Artifact artifact =
              getArtifact(
                  d.getGroupId(),
                  d.getArtifactId(),
                  d.getVersion(),
                  d.getType(),
                  d.getClassifier());
          url.add(artifact.getFile().toURI().toURL());
        }
      }

      URL[] classpath = url.toArray(new URL[url.size()]);

      URLClassLoader uc =
          new URLClassLoader(classpath, this.getClass().getClassLoader()) {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
              getLog().debug("Loading Class for compile [" + name + "]");
              Class<?> c = super.loadClass(name);
              getLog().debug("Loading Class for compile [" + name + "] found [" + c + "]");
              return c;
            }

            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
              getLog().debug("Finding Class for compile [" + name + "]");
              Class<?> c = super.findClass(name);
              getLog().debug("Finding Class for compile [" + name + "] found [" + c + "]");
              return c;
            }
          };
      URLClassLoader uc2 =
          new URLClassLoader(classpath, this.getClass().getClassLoader()) {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
              getLog().debug("Loading Class for runtime [" + name + "]");
              Class<?> c = super.loadClass(name);
              getLog().debug("Loading Class for runtime [" + name + "] found [" + c + "]");
              return c;
            }

            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
              getLog().debug("Finding Class for runtime [" + name + "]");
              Class<?> c = super.findClass(name);
              getLog().debug("Finding Class for runtime [" + name + "] found [" + c + "]");
              return c;
            }
          };
      getLog().info("Package Class loader is using classpath " + Arrays.toString(uc.getURLs()));

      listClassloader("  ", uc);

      PackageBuilderConfiguration packageBuilderConfiguration = new PackageBuilderConfiguration(uc);
      PackageBuilder pb = new PackageBuilder(packageBuilderConfiguration);

      DirectoryScanner ds = new DirectoryScanner();
      ds.setIncludes(includes);
      ds.setExcludes(excludes);
      ds.setBasedir(rulesdir);
      ds.setCaseSensitive(true);
      ds.scan();

      String[] files = ds.getIncludedFiles();
      for (String file : files) {
        File f = new File(rulesdir, file);
        Reader reader = new FileReader(f);
        try {
          if (file.endsWith(".drl")) {
            getLog().info("Adding Rules " + f);
            pb.addPackageFromDrl(reader);
          } else if (file.endsWith(".xml")) {
            getLog().info("Adding Package definition " + f);
            pb.addPackageFromXml(reader);
          } else if (file.endsWith(".rf")) {
            getLog().info("Adding Rule Flow " + f);
            pb.addRuleFlow(reader);
          } else {
            getLog().info("Ignored Resource " + f);
          }

        } finally {
          reader.close();
        }
      }

      pb.compileAll();
      PackageBuilderErrors errors = pb.getErrors();
      if (errors.size() > 0) {
        for (KnowledgeBuilderError kberr : errors) {
          getLog().error(kberr.toString());
        }
        throw new MojoExecutionException("Package is not valid");
      }
      org.drools.rule.Package p = pb.getPackage();
      if (!p.isValid()) {
        getLog().error("Package is not valid ");
        throw new MojoExecutionException("Package is not valid");
      }

      File outputFile = getOutputFile();
      getLog().info("Saving compiled package to  " + outputFile.getPath());
      outputFile.getParentFile().mkdirs();
      FileOutputStream fout = new FileOutputStream(outputFile);
      DroolsStreamUtils.streamOut(fout, p);
      fout.close();

      getLog().info("Testing Compiled package " + outputFile.getPath());

      File inputFile = getOutputFile();
      FileInputStream fin = new FileInputStream(inputFile);

      RuleBaseConfiguration config = new RuleBaseConfiguration(uc2);
      RuleBase ruleBase = RuleBaseFactory.newRuleBase(config);
      Object o = DroolsStreamUtils.streamIn(fin, uc);

      ruleBase.addPackage((Package) o);
      KnowledgeBase kb = new KnowledgeBaseImpl(ruleBase);

      @SuppressWarnings("unused")
      StatelessKnowledgeSession session = kb.newStatelessKnowledgeSession();

      getLog().info("Testing passed ");

    } catch (Exception e) {
      getLog().error(e);
      throw new MojoExecutionException(e.getMessage());
    }
  }