Package org.drools.builder

Examples of org.drools.builder.KnowledgeBuilder


                      processInstance.getVariable( "Number" ) );
    }

    @Test
    public void testAbortWorkItem() {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

        String str = "";
        str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        str += "<process xmlns=\"http://drools.org/drools-5.0/process\"\n";
        str += "         xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
        str += "         xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n";
        str += "         type=\"RuleFlow\" name=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n";
        str += "\n";
        str += "  <header>\n";
        str += "    <variables>\n";
        str += "      <variable name=\"UserName\" >\n";
        str += "        <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
        str += "        <value>John Doe</value>\n";
        str += "      </variable>\n";
        str += "      <variable name=\"Person\" >\n";
        str += "        <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"org.drools.camel.testdomain.Person\" />\n";
        str += "      </variable>\n";
        str += "      <variable name=\"MyObject\" >\n";
        str += "        <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"java.lang.Object\" />\n";
        str += "      </variable>\n";
        str += "      <variable name=\"Number\" >\n";
        str += "        <type name=\"org.drools.process.core.datatype.impl.type.IntegerDataType\" />\n";
        str += "      </variable>\n";
        str += "    </variables>\n";
        str += "  </header>\n";
        str += "\n";
        str += "  <nodes>\n";
        str += "    <start id=\"1\" name=\"Start\" />\n";
        str += "    <workItem id=\"2\" name=\"HumanTask\" >\n";
        str += "      <work name=\"Human Task\" >\n";
        str += "        <parameter name=\"ActorId\" >\n";
        str += "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
        str += "          <value>#{UserName}</value>\n";
        str += "        </parameter>\n";
        str += "        <parameter name=\"Content\" >\n";
        str += "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
        str += "          <value>#{Person.name}</value>\n";
        str += "        </parameter>\n";
        str += "        <parameter name=\"TaskName\" >\n";
        str += "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
        str += "          <value>Do something</value>\n";
        str += "        </parameter>\n";
        str += "        <parameter name=\"Priority\" >\n";
        str += "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
        str += "        </parameter>\n";
        str += "        <parameter name=\"Comment\" >\n";
        str += "          <type name=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n";
        str += "        </parameter>\n";
        str += "        <parameter name=\"Attachment\" >\n";
        str += "          <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"java.lang.Object\" />\n";
        str += "        </parameter>\n";
        str += "      </work>\n";
        str += "      <mapping type=\"in\" from=\"MyObject\" to=\"Attachment\" />";
        str += "      <mapping type=\"in\" from=\"Person.name\" to=\"Comment\" />";
        str += "      <mapping type=\"out\" from=\"Result\" to=\"MyObject\" />";
        str += "      <mapping type=\"out\" from=\"Result.length()\" to=\"Number\" />";
        str += "    </workItem>\n";
        str += "    <end id=\"3\" name=\"End\" />\n";
        str += "  </nodes>\n";
        str += "\n";
        str += "  <connections>\n";
        str += "    <connection from=\"1\" to=\"2\" />\n";
        str += "    <connection from=\"2\" to=\"3\" />\n";
        str += "  </connections>\n";
        str += "\n";
        str += "</process>";

        Reader source = new StringReader( str );
        kbuilder.add( ResourceFactory.newReaderResource( source ),
                      ResourceType.DRF );

        Collection<KnowledgePackage> kpkgs = kbuilder.getKnowledgePackages();
        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addKnowledgePackages( kpkgs );
        StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

        TestWorkItemHandler handler = new TestWorkItemHandler();
View Full Code Here


        assertXMLEqual( expectedXml2,
                        outXml2 );
    }
   
    private StatelessKnowledgeSession getStatelessKnowledgeSession(Resource resource) throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( resource,
                      ResourceType.DRL );

        if ( kbuilder.hasErrors() ) {
            System.out.println( kbuilder.getErrors() );
        }

        assertFalse( kbuilder.hasErrors() );
        Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();

        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

        kbase.addKnowledgePackages( pkgs );
        StatelessKnowledgeSession session = kbase.newStatelessKnowledgeSession();
View Full Code Here

        return session;
    }

    private StatefulKnowledgeSession getStatefulKnowledgeSession(Resource resource) throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( resource,
                      ResourceType.DRL );

        if ( kbuilder.hasErrors() ) {
            System.out.println( kbuilder.getErrors() );
        }

        assertFalse( kbuilder.hasErrors() );
        Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();

        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

        kbase.addKnowledgePackages( pkgs );
        StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();
View Full Code Here

        return session;
    }
   
    private StatefulKnowledgeSession getStatefulKnowledgeSession2(Resource resource) throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( resource,
                      ResourceType.DRL );

        if ( kbuilder.hasErrors() ) {
            System.out.println( kbuilder.getErrors() );
        }

        assertFalse( kbuilder.hasErrors() );
        Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();

        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

        kbase.addKnowledgePackages( pkgs );
        StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();
View Full Code Here

      return loadKnowledgeBase(ruleSource);

    }

    // Load the rules
    KnowledgeBuilder localBuilder = KnowledgeBuilderFactory
    .newKnowledgeBuilder();

    for (String ruleFile : ruleSource.getRulesLocation()) {
      log.info("Loading file: " + ruleFile);

      // Check the type of rule file, then load it
      if (ruleFile.endsWith(RedConstants.XLS_FILE_EXTENSION)) {

        log.info("Loading Excel file: " + ruleFile);
        loadExcelRules(ruleFile, localBuilder);
      } else {

        log.info("Loading Drl file: " + ruleFile);
        loadDrlRules(ruleFile, ruleSource.getDslFileLocation(),
            ruleSource.getRuleFlowFileUrl(), localBuilder);
      }

    }

    // check that there are no errors
    if (localBuilder.hasErrors()) {

      log.severe("Drools Errors");
      KnowledgeBuilderErrors errors = localBuilder.getErrors();
      Iterator<KnowledgeBuilderError> itErrors = errors.iterator();
      int[] errorLines;
      StringBuffer errorLineMessage;
      while (itErrors.hasNext()) {
        KnowledgeBuilderError thisError = itErrors.next();
        log.severe(thisError.getMessage());
        log.severe(thisError.toString());
        errorLines = thisError.getErrorLines();
        errorLineMessage = new StringBuffer();
        if (errorLines != null) {
          for (int errorLine : errorLines) {
            errorLineMessage.append(errorLine);
            errorLineMessage.append(",");
          }
          log.severe("Error Lines:" + errorLineMessage.toString());
        }

      }

      log.severe("****/nDrools Errors:"
          + localBuilder.getErrors().toString());
      log.severe("****/nEnd Drools Errors");

      throw new RuntimeException("Error in Rules File:"
          + localBuilder.getErrors().toString());

    } else {
      log.info("No Drools Errors");
    }

    // Print out what we know of the built packages
    logKnowledgePackages(localBuilder);

    // Use these
    log.info("Creating new knowledgebase");
    KnowledgeBase localBase = KnowledgeBaseFactory.newKnowledgeBase();

    log.info("Adding packages to localBase");
    localBase.addKnowledgePackages(localBuilder.getKnowledgePackages());

    return localBase;
  }
View Full Code Here

                buildResourcesList(kBaseQualifier, kBaseQualifier.getName(), list);
                map.put(kBaseQualifier, list);
            }
        }

        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        CompositeKnowledgeBuilder ckbuilder = kbuilder.batch();

        for ( Map.Entry<Class, List<String>> entry : map.entrySet() ) {
            Class cls = entry.getKey();
            List<String> files = entry.getValue();
            if ( !files.isEmpty() ) {
                for ( String file : files ) {
                    if ( file.endsWith(".drl" ) ) {
                        ckbuilder.add( ResourceFactory.newUrlResource( cls.getResource("/" + file.trim()) ), ResourceType.DRL );
                    }
                }
            }
        }

        ckbuilder.build();


        if ( kbuilder.hasErrors() ) {
            throw new RuntimeException( "Unable to compile " + kBaseQualifiers[0].getName() + ":\n" + kbuilder.getErrors() );
        }

        KnowledgeBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
        kconf.setOption( eventProcessingMode);
        kconf.setOption( equalsBehaviour );
        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf);
        kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
        return kbase;
    }
View Full Code Here

    public KnowledgeBaseAddKnowledgePackagesCommand() {
    }

    public Void execute(Context context) {
        KnowledgeBuilder kbuilder = ((KnowledgeCommandContext) context).getKnowledgeBuilder();
        if (kbuilder.hasErrors()) {
            throw new IllegalStateException("There are rule compilation errors:\n" + kbuilder.getErrors().toString());
        }
        KnowledgeBase kbase = ((KnowledgeCommandContext) context).getKnowledgeBase();
        kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
        return null;
    }
View Full Code Here

     * @param changeSetState the object containing the added resources list and
     * created pacages list.
     */
    private void addResourcesToKnowledgeBase(ChangeSetState changeSetState) {

        KnowledgeBuilder kbuilder =  KnowledgeBuilderFactory.newKnowledgeBuilder();
        List<Package> packages = new ArrayList<Package>();


        for (Resource resource : changeSetState.addedResources) {
            KnowledgePackageImp createdPackage = this.createPackageFromResource(resource, kbuilder);
            changeSetState.createdPackages.put(resource, createdPackage);
        }


        for (Map.Entry<Resource, KnowledgePackage> entry : changeSetState.createdPackages.entrySet()) {
            // For PKG (.pks) just add them
            Resource resource = entry.getKey();
            this.listener.debug("KnowledgeAgent obtaining pkg resource="
                    + resource);

            try {
                Package pkg = ((KnowledgePackageImp) entry.getValue()).pkg;
                for (Rule rule : pkg.getRules()) {
                    rule.setResource(resource);
                }
                packages.add(pkg);

                this.buildResourceMapping(pkg, resource);
            } catch (Exception e) {
                this.listener.exception(new RuntimeException(
                        "KnowledgeAgent exception while trying to deserialize KnowledgeDefinitionsPackage  ",
                        e));
            }
        }

        if (kbuilder
                != null) {
            // Log any errors we come across
            if (kbuilder.hasErrors()) {
                this.listener.warning(
                        "KnowledgeAgent has KnowledgeBuilder errors ", kbuilder.getErrors());
            }
            this.listener.debug("KnowledgeAgent adding KnowledgePackages from KnowledgeBuilder");
            this.kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
        }
        /*
         * Add all the packages we found, but did not build, from the resources
         * now
         */
 
View Full Code Here

        GridServiceDescription<GridNode> n1Gsd = grid.get(WhitePages.class).lookup("n1");
        GridConnection<GridNode> conn = grid.get(ConnectionFactoryService.class).createConnection(n1Gsd);
        GridNode remoteN1 = conn.connect();


        KnowledgeBuilder kbuilder = remoteN1.get(KnowledgeBuilderFactoryService.class).newKnowledgeBuilder();

        //kbuilder.add(new ByteArrayResource(IOUtils.toByteArray(new ClassPathResource("rules/patient.drl").getInputStream())), ResourceType.DRL);
        kbuilder.add(new ByteArrayResource(IOUtils.toByteArray(new ClassPathResource("rules/patient.dsl").getInputStream())), ResourceType.DSL);
        kbuilder.add(new ByteArrayResource(IOUtils.toByteArray(new ClassPathResource("rules/patient.dslr").getInputStream())), ResourceType.DSLR);

        KnowledgeBuilderErrors errors = kbuilder.getErrors();
        if (errors != null && errors.size() > 0) {
            for (KnowledgeBuilderError error : errors) {
                System.out.println(">>>>>>> Error: " + error.getMessage());

            }
            throw new IllegalStateException("Failed to parse knowledge!");
        }
        KnowledgeBaseConfiguration kbaseConf = remoteN1.get(KnowledgeBaseFactoryService.class).newKnowledgeBaseConfiguration();
        kbaseConf.setOption(EventProcessingOption.STREAM);
        KnowledgeBase kbase = remoteN1.get(KnowledgeBaseFactoryService.class).newKnowledgeBase(kbaseConf);


        kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

        StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();

        remoteN1.set("AmbulanceMonitorSession" + vehicleId, session);
View Full Code Here

    }
    @Test
    public void hello(){}
   
    protected StatefulKnowledgeSession createSession(){
        KnowledgeBuilder kbuilder = remoteN1.get( KnowledgeBuilderFactoryService.class ).newKnowledgeBuilder();

        assertNotNull( kbuilder );

         String rule = "package test\n"
                 + "import com.wordpress.salaboy.MyObject;\n"
                 + "global MyObject myGlobalObj;\n"
                 + "rule \"test\""
                 + "  when"
                 + "       $o: MyObject()"
                 + "  then"
                 + "      System.out.println(\"My Global Object -> \"+myGlobalObj.getName());"
                 + "      System.out.println(\"Rule Fired! ->\"+$o.getName());"
                 + " end";

        kbuilder.add( new ByteArrayResource( rule.getBytes() ),
                      ResourceType.DRL );

        KnowledgeBuilderErrors errors = kbuilder.getErrors();
        if ( errors != null && errors.size() > 0 ) {
            for ( KnowledgeBuilderError error : errors ) {
                System.out.println( "Error: " + error.getMessage() );

            }
            fail("KnowledgeBase did not build");
        }

        KnowledgeBase kbase = remoteN1.get( KnowledgeBaseFactoryService.class ).newKnowledgeBase();

        assertNotNull( kbase );

        kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );

        StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();
        return session;
   
    }
View Full Code Here

TOP

Related Classes of org.drools.builder.KnowledgeBuilder

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.