读取Guvnor中的规则...

 

配合Guvnor一起使用,简单的实现如下:

 

直接使用Drools 的HelloWorld例子进行改动:

 

代码清单一:

 

 

package com.sample;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.agent.KnowledgeAgent;
import org.drools.agent.KnowledgeAgentFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;

/**
 * This is a sample class to launch a rule.
 */
public class DroolsTest {

 public static final void main(String[] args) {
  try {
   // load up the knowledge base
   KnowledgeBase kbase = readKnowledgeBase();
   StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
   KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
   // go !
   Message message = new Message();
   message.setMessage("Hello World");
   message.setStatus(Message.HELLO);
   ksession.insert(message);
   ksession.fireAllRules();
   logger.close();
  } catch (Throwable t) {
   t.printStackTrace();
  }
 }

 private static KnowledgeBase readKnowledgeBase() throws Exception {
  KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
  
  //修改此方法
  //kbuilder.add(ResourceFactory.newClassPathResource("Sample.drl"), ResourceType.DRL);
  kbuilder.add(ResourceFactory.newUrlResource("http://localhost:8080/drools-guvnor/org.drools.guvnor.Guvnor/package/com.chen.rules/LATEST"), ResourceType.PKG);
  KnowledgeBuilderErrors errors = kbuilder.getErrors();
  if (errors.size() > 0) {
   for (KnowledgeBuilderError error: errors) {
    System.err.println(error);
   }
   throw new IllegalArgumentException("Could not parse knowledge.");
  }
  KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
  kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
  //采用Agent的方式
/*  KnowledgeAgent kagent=KnowledgeAgentFactory.newKnowledgeAgent("/deploy.properties");
  
  KnowledgeBase kbase=kagent.getKnowledgeBase();*/
  return kbase;
 }

 public static class Message {
  
  public static final int HELLO = 0;
  public static final int GOODBYE = 1;

  private String message;

  private int status;

  public String getMessage() {
   return this.message;
  }

  public void setMessage(String message) {
   this.message = message;
  }

  public int getStatus() {
   return this.status;
  }

  public void setStatus(int status) {
   this.status = status;
  }
  
 }

}

 

部分截图:

Guvnor package

 

Code

 

Code2

 

图示:

Guvnor

 

测试结果:

 

 

结果输出

 

------Game Over----------------

 

 

 

你可能感兴趣的:(UP,Go)