如何在具有包含无限循环的函数(监视器)时触发Drools中的规则?

时间:2016-03-03 12:33:49

标签: java drools rule-engine business-rules

我有一个包含无限循环的函数(MonitorLog);这是必要的,因为我想要监视文件并在修改时执行操作。但是,Drools中的然后部分并不想开始(" WS已更新"不会出现)。有些帮助吗?

package smartWssec ;
dialect "mvel"
rule "SmartWssec"
when
$log :PolicyUpdateWssec(flag == true ,changelog == true)
then
$log.UpdateXml("D:\\Mod\\policy.xml")// consequence
System.out.println("Ws-Policy Updated")
end

/////////////////////////////////////////////// ///////

package smartWssec;


import java.io.IOException;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;



    public class MainPolicyUpdateWssec {


    public static void main(String[] args) throws IOException, InterruptedException {
                //create a Session 
    KieServices ks = KieServices.Factory.get();
    KieContainer kContainer = ks.getKieClasspathContainer();
    KieSession kSession =     kContainer.newKieSession("ksession-rules");
            try {

                //create fact
                PolicyUpdateWssec LogModSecurity = new PolicyUpdateWssec();
                LogModSecurity.MonitorLog("D:\\Mod");
                LogModSecurity.ReadLog("D:\\Mod\\Modsecurity.txt");
                //insert fact and fire Rules
                kSession.insert(LogModSecurity);
                kSession.fireAllRules();

            }
            finally {
            kSession.dispose();
            }
            }

/////////////////////////////////////////////// //////////////////////////////

 public  class PolicyUpdateWssec {
private boolean flag;
private boolean changelog;



public boolean getchangelog(){
    return changelog;
}
public void setChangelog(boolean changelog){
    this.changelog=changelog;
}

public boolean getflag(){
    return flag;
    }

public void setflag(boolean flag){
    this.flag=flag;
}


public void Update(String filename){

    try (PrintStream ps = new PrintStream("D:\\Mod\\Wspolicyupdate.txt");
            Stream<String> stream = Files.lines(Paths.get(filename))) {
            stream.map(line -> line.replaceAll("</wsp:Policy>","<wssp:Integrity>\r\n\r\n<wssp:SignatureAlgorithm URI=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\r\n\r\n<wssp:CanonicalizationAlgorithm URI=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/>\r\n\r\n<!-- Require the Timestamp header to be signed -->\r\n\r\n<wssp:Target>\r\n\r\n<wssp:DigestAlgorithm URI=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\r\n\r\n<wssp:MessageParts Dialect=\"http://www.bea.com/wls90/security/policy/wsee#part\">\r\n\r\nwls:SecurityHeader(wsu:Timestamp)\r\n\r\n</wssp:MessageParts>\r\n\r\n</wssp:Target>\r\n\r\n<!-- Require the message body to be signed -->\r\n\r\n<wssp:Target>\r\n\r\n<wssp:DigestAlgorithm URI=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\r\n\r\n<wssp:MessageParts Dialect=\"http://schemas.xmlsoap.org/2002/12/wsse#part\">\r\n\r\nwsp:Body()\r\n\r\n</wssp:MessageParts>\r\n\r\n</wssp:Target>\r\n\r\n</wssp:Integrity>\r\n\r\n</wsp:Policy>")).forEach(ps::println);
            System.out.println("Ws-Policy updated");
        } catch (IOException e) {
            e.printStackTrace();
        }}

 public void ReadLog(String filename) throws IOException{

String line =null;
boolean flag=false;

 // FileReader reads text files in the default encoding

 FileReader fileReader = new FileReader(filename);

 // Always wrap FileReader in BufferedReader

 BufferedReader bufferedReader = new BufferedReader(fileReader);

  while((line = bufferedReader.readLine()) != null) {


    flag=line.matches("(.*)sql_injection_attacks(.*)");
    if(flag==true) setflag(flag);

    }

   // Always close files
   bufferedReader.close();         
}

public void MonitorLog(String path) throws InterruptedException{

boolean changelog=false;

    try {
        WatchService watcher = FileSystems.getDefault().newWatchService();
        Path dir = Paths.get(path);
        dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

        System.out.println("Watch Service registered for : " + dir.getFileName());

             WatchKey key = watcher.poll(10, TimeUnit.SECONDS);

            try {

            // wait for a key to be available

                key = watcher.take();
            } catch (InterruptedException ex) {
                return;
            }

            for (WatchEvent<?> event : key.pollEvents()) {
                // get event type
                WatchEvent.Kind<?> kind = event.kind();

                // get file name
                @SuppressWarnings("unchecked")
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path fileName = ev.context();

                System.out.println(kind.name() + ": " + fileName);

                if (kind == ENTRY_MODIFY ) {
                    changelog=true;
                    setChangelog(changelog);
                    System.out.println("WS-Policy is being Updated .......");


                }

            }



        watcher.close();            
    }
    catch (IOException ex) {
        System.err.println(ex);
    }


    } 




public void UpdateXml(String filename) {

ArrayList<String> lines = new ArrayList<String>();
String line = null;

File f1=null;
FileReader fr=null;

BufferedReader br=null;
FileWriter fw=null;
BufferedWriter out=null;
try {
    f1 = new File(filename);
    fr = new FileReader(f1);
    br = new BufferedReader(fr);
    while ((line = br.readLine()) != null) {
        if (line.contains("</wsp:Policy>"))
        line = line.replace("</wsp:Policy>", "<wssp:Integrity>\r\n\r\n<wssp:SignatureAlgorithm URI=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\r\n\r\n<wssp:CanonicalizationAlgorithm URI=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/>\r\n\r\n<!-- Require the Timestamp header to be signed -->\r\n\r\n<wssp:Target>\r\n\r\n<wssp:DigestAlgorithm URI=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\r\n\r\n<wssp:MessageParts Dialect=\"http://www.bea.com/wls90/security/policy/wsee#part\">\r\n\r\nwls:SecurityHeader(wsu:Timestamp)\r\n\r\n</wssp:MessageParts>\r\n\r\n</wssp:Target>\r\n\r\n<!-- Require the message body to be signed -->\r\n\r\n<wssp:Target>\r\n\r\n<wssp:DigestAlgorithm URI=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\r\n\r\n<wssp:MessageParts Dialect=\"http://schemas.xmlsoap.org/2002/12/wsse#part\">\r\n\r\nwsp:Body()\r\n\r\n</wssp:MessageParts>\r\n\r\n</wssp:Target>\r\n\r\n</wssp:Integrity>\r\n\r\n</wsp:Policy>");
        lines.add(line);
    }

    fw = new FileWriter(f1);
    out = new BufferedWriter(fw);
    for (String s : lines)
    out.write(s);
    out.flush();

} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    try{
    fr.close();
    br.close();
    out.close();
    }catch(IOException ioe)

    {
        ioe.printStackTrace();
    }

}
}}

1 个答案:

答案 0 :(得分:1)

仅更改类成员以触发规则是不够的。您必须通知Drools引擎才能实现这一目标。修改您的代码,以便您拥有插入事实的事实句柄:

class LitRf
{
    const char* data_;
    Sz size_;
public:
    // Called by the macro MakeLitRf. Unlikely to be called directly unless the user knows what he's doing.
    LitRf(const char *s, void *)
        : data_{s}, size_{N}
    {}

    // Called without macro! Throw a compiler error, explaining what's wrong.
    LitRf(const char *s)
    {
        static_assert(false, "Please use the macro `MakeLitRf` with a string literal to construct a `LitRf`.");
    }
};

#define MakeLitRf(s) LitRf(s "", nullptr)

然后在修改后调用update:

FactHandle fh = kSession.insert(LogModSecurity);

由于缺少大量代码,我无法告诉您如何整合此内容。

编辑 setChangelog(changelog); // assuming this is code in PolicyUpdateWssec kSession.update( fh, this ); 中的代码似乎等待某个目录中某个文件的修改,然后尝试对修改后的文件执行某些操作。 (WatchService方法轮询并从两组密钥中删除一些东西 - 你在那里丢失了一个密钥。)如果没有任何反应,则轮询返回null,因此可以预期NPE。然后,如果它是MODIFY,则changelog设置为true。然后调用fireAllRules。但规则不会触发,因为MonitorLog永远不会设置为真。

据我所见,没有必要制定规则。您希望更改文件:等待它,然后执行需要完成的任何操作。该规则由于该更改而触发(并且可能某些文件必须包含某些特定文本)。这里没有任何内容可以保证使用生产规则系统。

相关问题