Posted on 2010-03-10 22:29
斷點 閱讀(1268)
評論(0) 編輯 收藏 所屬分類:
Drools
package com.premium.rules;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.drools.rule.Package;
public class DrlPackageManager {
// 用于緩存Drools的Package,key為Excel的完整路徑,value為此文件編譯過后的Package
static Map<String, Package> pkgMap = new HashMap<String, Package>();
private static Logger logger = Logger.getLogger(DrlPackageManager.class);
/**
* 通過Excel的文件名緩存Drools的Package
*
* @param fileName
* @return
* @throws Exception
*/
public static Package getPackageByXsl(String fileName) throws Exception {
Package pkg = (Package) pkgMap.get(fileName);
if (pkg != null)
return pkg;
final SpreadsheetCompiler converter = new SpreadsheetCompiler();
InputStream is = null;
try {
is = DrlPackageManager.class.getResourceAsStream(fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
is.close();
throw new Exception("====讀取規則的資源文件" + fileName + "出錯,請檢查文件"+ fileName + "=====", e);
}
String drl = null;
try {
drl = converter.compile(is, InputType.XLS);
logger.debug("Drools Excel規則文件:" + fileName + "編譯成.drl文件的結果:"+ drl);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
is.close();
throw new Exception("xls文件編譯成drl文件出錯", e);
}
PackageBuilder builder = new PackageBuilder();
StringReader srd = new StringReader(drl);
builder.addPackageFromDrl(srd);
pkg = builder.getPackage();
pkgMap.put(fileName, pkg);
is.close();
return pkg;
}
}