您的位置:首页 > 其它

Gunvor 5.5.0.Final rest api汇总

2014-09-20 19:33 169 查看
因为工作变动, 去年从商用BRMS转行到开源世界,选择了JBoss Drools, 也意味着想要一个可用的规则管理系统,必须拥抱Guvnor。

在商用软件的世界里, 有大量内部资料可以参阅,开源世界除了文档和网上的只言片语,还有源码这一利器。

独乐乐不如众乐乐,分享出来,只要对哪怕一个人起到帮助,那么足矣。

注: 以下代码和接口仅在5.5.0.Final版本中测试并运行。

常用接口

GET:
http://localhost:8080/guvnor/rest/packages 展示所有的package
http://localhost:8080/guvnor/rest/packages/${packageName} 展示该package信息
http://localhost:8080/guvnor/rest/packages/${packageName}/assets 展示该package下全部asset信息
http://localhost:8080/guvnor/rest/packages/${packageName}/assets/${assetName}
展示该asset信息
http://localhost:8080/guvnor/rest/packages/${packageName}/assets/${assetName}/versions 展示asset
历史版本列表
http://localhost:8080/guvnor/rest/packages/${packageName}/assets/${assetName}/versions/1 展示具体的历史版本,同一asset不同的历史版本uuid不同,但是保证最新的asset的uuid一直不变,
即 版本1 时候uuid 在更新到版本2 时, 历史版本1的uuid会变成新的内容,而版本2保留原版本1的值

POST:
http://localhost:8080/guvnor/rest/packages/${packageName}/snapshot/${snapshotName}
创建snapshot如果存在则覆盖
http://localhost:8080/guvnor/org.drools.guvnor.Guvnor/api/packages/${packageName}/${assetNameWithExtention}
新建asset 如果asset不存在则新建,如果存在且被归档,则会将归档删除且新建一个,如果未被归档,则出错 asset名字需要带扩展名 如果扩展名是package则创建package . 该接口需要声明enctype为multiple/form-data, 示例:

http://localhost:8080/guvnor/org.drools.guvnor.Guvnor/api/packages/mortgages/history2.brl
conn.setRequestProperty("enctype", "multipart/form-data");
具体代码在RestAPI类中

编译:
org.drools.guvnor.Guvnor/action/compile
String link = baseUrl + "org.drools.guvnor.Guvnor/action/compile";
String urlParameters = "package-name=" + encode(pkg);
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
conn.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
conn.getInputStream();
conn.disconnect();


新建package : test.test.test
http://localhost:8080/guvnor/rest/packages
Content-Type: application/octet-stream
raw text
package test.test.test

DELETE:
http://localhost:8080/guvnor/org.drools.guvnor.Guvnor/api/packages/${packageName}/${assetNameWithExtention}
将指定asset进行归档

实现代码

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.catalina.util.URLEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.drools.KnowledgeBase;
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.definition.KnowledgePackage;
import org.drools.definition.rule.Rule;
import org.drools.io.ResourceFactory;
import org.drools.io.impl.UrlResource;
import org.drools.runtime.StatefulKnowledgeSession;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.yihaodian.bi.rulemanagement.model.PackageModel;
import com.yihaodian.bi.rulemanagement.model.RuleModel;

public class DroolsUtil {
private static Log log = LogFactory.getLog(DroolsUtil.class);
private String userName = "admin";
private String password = "admin";
private String baseUrl = "http://localhost:8080/guvnor/";
private final String REST = "rest/";
private final String API = "org.drools.guvnor.Guvnor/api/";
private static final String ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
private String ruleFileCharset = "GBK";
public static final String RULE_TYPE_USER = "user";
public static final String RULE_TYPE_MOBILE = "mobile";
public static final String SNAPSHOT_NAME = "deployment";
public static final String META_STATUS_DRAFT = "Draft";
public static final String META_STATUS_TEST = "Test";

public String getRuleFileCharset() {
return ruleFileCharset;
}

public void setRuleFileCharset(String ruleFileCharset) {
this.ruleFileCharset = ruleFileCharset;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getBaseUrl() {
return baseUrl;
}

public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}

/**
* Construction Initialize authentication with given userName and password
* It is required by methods which interacts with guvnor rest api
*/
public DroolsUtil() {
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password
.toCharArray());
}
});
}

/**
* Build KnowledgeBase according to given list of package names
*
* @param pkgList
* @return
*/
public KnowledgeBase readKnowledgeBaseFromGuvnor(List<String> pkgList) {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
.newKnowledgeBuilder();
if (pkgList != null) {
for (String pkg : pkgList) {
String url = baseUrl + REST + "packages/" + encode(pkg)
+ "/binary";
UrlResource res = (UrlResource) ResourceFactory
.newUrlResource(url);
res.setBasicAuthentication("enabled");
res.setUsername(userName);
res.setPassword(password);
kbuilder.add(res, 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 = kbuilder.newKnowledgeBase();
return kbase;

}

/**
* Build KnowledgeBase according to given list of package name and snapshot
* name
*
* @param pkgList
* @return
*/
public KnowledgeBase readKnowledgeBaseFromGuvnor(String pkg, String snapshot) {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
.newKnowledgeBuilder();
// http://localhost:8080/guvnor/org.drools.guvnor.Guvnor/package/%E5%A5%B6%E7%B2%89/deployment String url = baseUrl + "org.drools.guvnor.Guvnor/package/"
+ encode(pkg) + "/" + encode(snapshot);
UrlResource res = (UrlResource) ResourceFactory.newUrlResource(url);
res.setBasicAuthentication("enabled");
res.setUsername(userName);
res.setPassword(password);
kbuilder.add(res, 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 = kbuilder.newKnowledgeBase();
return kbase;

}

/**
* encode string with UTF-8
*
* @param str
* @return
*/
private String encode(String str) {
URLEncoder enc = new URLEncoder();
return enc.encode(str);
}

public StatefulKnowledgeSession getStatefullSession(String... pkg) {
List<String> pkgList = new ArrayList<String>();
for (String packageName : pkg) {
pkgList.add(packageName);
}
return getStatefullSession(pkgList);
}

/**
* create StatefulKnowledgeSession with a given list of package names
*
* @param pkgList
* @return
*/
public StatefulKnowledgeSession getStatefullSession(List<String> pkgList) {
StatefulKnowledgeSession session = readKnowledgeBaseFromGuvnor(pkgList)
.newStatefulKnowledgeSession();
return session;
}

public StatefulKnowledgeSession getStatefullSession(String pkg,
String snapshot) {
StatefulKnowledgeSession session = readKnowledgeBaseFromGuvnor(pkg,
snapshot).newStatefulKnowledgeSession();
return session;
}

/**
* dispose a KnowledgeSession
*
* @param session
*/
public void dispose(StatefulKnowledgeSession session) {
session.dispose();
}

/**
* Get a list of PackageModel from guvnor with given package name list the
* package model contains a list of RuleModel
*
* For RuleModel, fields of name ,namespace, id and package are filled , the
* others are null For PackageModel, only field of name is filled.
*
* This method connect to guvnor and create local Knowledge session,
* information are retrieved by drools API
*
* @param pkgList
* @return a map for package name and rule names key: name of package value
* list of rule names
* @deprecated
*/
public List<PackageModel> getPkgList(List<String> pkgList) {
List<PackageModel> packageList = new ArrayList<PackageModel>();
KnowledgeBase kbase = readKnowledgeBaseFromGuvnor(pkgList);
for (KnowledgePackage pkg : kbase.getKnowledgePackages()) {
PackageModel pkgModel = new PackageModel();
packageList.add(pkgModel);
pkgModel.setName(pkg.getName());

for (Rule rule : pkg.getRules()) {
RuleModel ruleModel = new RuleModel();
ruleModel.setName(rule.getName());
ruleModel.setNamespace(rule.getNamespace());
ruleModel.setId(rule.getId());
ruleModel.setPkg(pkg.getName());
pkgModel.add(ruleModel);
}
}
return packageList;
}

/**
* wrapper for getPkgListByRest(List<String> pkgList)
*
* @param pkgNames
* @return
*/
public List<PackageModel> getPkgListByRest(String... pkgNames) {
List<String> pkgList = new ArrayList<String>();
for (String pkg : pkgNames) {
pkgList.add(pkg);
}
return getPkgListByRest(pkgList);
}

/**
* Get a list of PackageModel from guvnor with given package name list the
* package model contains a list of RuleModel
*
* For RuleModel, fields of name , pkg and uuid are filled , the others are
* null For PackageModel, only field of name is filled.
*
* This method will use rest api of Guvnor:
* http://localhost:8080/packages/{packageName}/assets *
* @param pkgList
* @return
*/
public List<PackageModel> getPkgListByRest(List<String> pkgList) {
List<PackageModel> packageList = new ArrayList<PackageModel>();
for (String pkgName : pkgList) {
String link = baseUrl + REST + "packages/" + encode(pkgName)
+ "/assets";
try {
URL url = new URL(link);
URLConnection conn = url.openConnection();
// the default type is json, force server to return xml
conn.setRequestProperty("Accept", DroolsUtil.ACCEPT);
InputStream is = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(is, "UTF-8");
SAXReader xmlReader = new SAXReader();
Document doc = xmlReader.read(reader);
PackageModel pkg = new PackageModel();
pkg.setName(pkgName);
packageList.add(pkg);
@SuppressWarnings("unchecked")
List<Element> elementList = doc
.selectNodes("//asset[./metadata/format='brl']");
for (Element e : elementList) {
RuleModel rule = new RuleModel();
String checkInComment = e.element("metadata").elementText(
"checkInComment");
if ("archived".equals(checkInComment)
|| "<removed remotely>".equals(checkInComment)) {
rule.setRemoved(true);
}
rule.setName(e.elementText("title"));
rule.setUuid(e.element("metadata").elementText("uuid"));
rule.setPkg(pkgName);
rule.setVersion(e.element("metadata").elementText(
"versionNumber"));
rule.setStatus(e.element("metadata").elementText("state"));
pkg.add(rule);

}
} catch (IOException e) {
log.error("", e);
e.printStackTrace();
} catch (DocumentException e) {
log.error("", e);
e.printStackTrace();
}
}
return packageList;
}

/**
* Get a list of packagenames This method will use rest api of Guvnor:
* http://localhost:8080/packages *
* @return
*/
public List<String> getAllPkgList() {
List<String> pkgList = new ArrayList<String>();
String link = baseUrl + REST + "packages";
try {
URL url = new URL(link);
URLConnection conn = url.openConnection();
// the default type is json, force server to return xml
conn.setRequestProperty("Accept", DroolsUtil.ACCEPT);
InputStream is = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(is, "UTF-8");
SAXReader xmlReader = new SAXReader();
Document doc = xmlReader.read(reader);
@SuppressWarnings("unchecked")
List<Element> eList = doc.selectNodes("//title");
for (Element e : eList) {
pkgList.add(e.getText());
}
} catch (IOException e) {
log.error("", e);
e.printStackTrace();
} catch (DocumentException e) {
log.error("", e);
e.printStackTrace();
}
return pkgList;
}

/**
* Get RuleModel for a rule with given name and package This method will use
* rest api of Guvnor:
* http://localhost:8080/packages/{packageName}/assets/{ruleName} *
* @param pkg
* @param rule
* @return
*/
public RuleModel getRuleModel(String pkg, String rule) {
String link = baseUrl + REST + "packages/" + encode(pkg) + "/assets/"
+ encode(rule);
try {
URL url = new URL(link);
URLConnection conn = url.openConnection();
// the default type is json, force server to return xml
conn.setRequestProperty("Accept", DroolsUtil.ACCEPT);
InputStream is = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(is, "UTF-8");
SAXReader xmlReader = new SAXReader();
Document doc = xmlReader.read(reader);
RuleModel ruleModel = new RuleModel();
ruleModel.setPkg(pkg);
ruleModel.setName(rule);
ruleModel.setUuid(doc.selectSingleNode("//uuid").getText());
ruleModel.setVersion(doc.selectSingleNode("//versionNumber")
.getText());
ruleModel.setStatus(doc.selectSingleNode("//state").getText());
String checkInComment = doc.selectSingleNode("//checkInComment")
.getText();
if ("archived".equals(checkInComment)
|| "<removed remotely>".equals(checkInComment)) {
ruleModel.setRemoved(true);
}
return ruleModel;
} catch (IOException e) {
log.error("", e);
// e.printStackTrace();
} catch (DocumentException e) {
log.error("", e);
// e.printStackTrace();
}
return null;
}

/**
* Get RuleModel for a rule with given name and package and version This
* method will use rest api of Guvnor:
* http://localhost:8080/packages/{packageName * }/assets/{ruleName}/versions/${versionNumber}
*
* @param pkg
* @param rule
* @return
*/
public RuleModel getRuleModel(String pkg, String rule, String version) {
String link = baseUrl + REST + "packages/" + encode(pkg) + "/assets/"
+ encode(rule) + "/versions/" + version;
try {
URL url = new URL(link);
URLConnection conn = url.openConnection();
// the default type is json, force server to return xml
conn.setRequestProperty("Accept", DroolsUtil.ACCEPT);
InputStream is = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(is, "UTF-8");
SAXReader xmlReader = new SAXReader();
Document doc = xmlReader.read(reader);
RuleModel ruleModel = new RuleModel();
ruleModel.setPkg(pkg);
ruleModel.setName(rule);
ruleModel.setUuid(doc.selectSingleNode("//uuid/value").getText());
String archived = doc.selectSingleNode("//archived/value")
.getText();
if ("true".equals(archived)) {
ruleModel.setRemoved(true);
}
ruleModel.setVersion(version);
return ruleModel;
} catch (IOException e) {
log.error("", e);
e.printStackTrace();
} catch (DocumentException e) {
log.error("", e);
e.printStackTrace();
}
return null;
}

/**
* create snapshot "deployment" for given package This method will use rest
* api of Guvnor: [POST]
* http://localhost:8080/packages/{packageName}/snapshot/${snapshotname} *
* @param pkg
*/
public void deploy(String pkg) {
String link = baseUrl + REST + "packages/" + encode(pkg) + "/snapshot/"
+ SNAPSHOT_NAME;
try {
compile(pkg);
// System.out.println(link);
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setDoOutput(true);
// conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.connect();
// get the input stream is a mandatory for this operation, otherwise
// this method will not take effect.
conn.getInputStream();
conn.disconnect();
} catch (IOException e) {
log.error("", e);
e.printStackTrace();
}
}

/**
* deploy rules in package AntiWSExecutor AntiWSExecutor will only contain
* the rule which are deployed by system manager
*
* Rules under Antiws will be changed after deployment, but system need to
* use the previous deployed version. snapshot for AntiWSExecutor is used
* for executing rules
*
* @param pkg
* @throws IOException
*/
public void deployExecutor(String pkg) throws IOException {
PackageModel pModel = getPkgListByRest("AntiWS").get(0);
String executorPkg = "AntiWSExecutor";
String prefix = pkg + "_";
for (RuleModel rModel : pModel.getRuleList()) {
if (rModel.getName().startsWith(prefix)) {
RuleModel rule = getRuleModel(executorPkg, rModel.getName());
if (rModel.isRemoved()) {
if (!rule.isRemoved()) {
deleteRule(executorPkg, rModel.getName());
}
} else {
if (rule.isRemoved()) {
restoreRule(executorPkg, rModel.getName());
}
}
}
}
deploy(executorPkg);
}

/**
* delete a rule from package
*
* @param pkg
* @param rule
* @throws IOException
*/
public void deleteRule(String pkg, String rule) throws IOException {
deleteAsset(pkg, rule+".brl");
}

/**
* delete a rule from package
*
* @param pkg
* @param rule
* @throws IOException
*/
public void deleteAsset(String pkg, String asset) throws IOException {
String link = baseUrl + API + "packages/" + encode(pkg) + "/"
+ encode(asset);
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.connect();
conn.getInputStream();
conn.disconnect();
}

/**
* create a new rule in package with template
*
* @param pkg
* @param rule
* @throws MalformedURLException
* @throws IOException
*/
public void createNewRule(String pkg, String rule, String type)
throws MalformedURLException, IOException {
createNewRule(pkg, rule, type, rule);
}

/**
* using template to create new BRL rule
*
* @param pkg
* @param rule
* @param type
* @param token
* @throws MalformedURLException
* @throws IOException
*/
public void createNewRule(String pkg, String rule, String type, String token)
throws MalformedURLException, IOException {
InputStream is = null;
InputStreamReader reader = null;
BufferedReader br = null;
try {
is = DroolsUtil.class.getResourceAsStream(type);
reader = new InputStreamReader(is, "GBK");
br = new BufferedReader(reader);
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String newRuleStr = sb.toString().replaceAll("@name@", token);
createRuleByAPI(pkg, rule, newRuleStr);
} finally {
if (br != null) {
br.close();
}
if (reader != null) {
reader.close();
}
if (is != null) {
is.close();
}
}
}

/**
* compile the whole package, using following api:
* http://servername:port/action/compile parameter: package-name
*
* @param pkg
* @throws IOException
*/
public void compile(String pkg) throws IOException {

String link = baseUrl + "org.drools.guvnor.Guvnor/action/compile"; String urlParameters = "package-name=" + encode(pkg); URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); conn.setUseCaches(false); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); conn.getInputStream(); conn.disconnect();
}

/**
* create rule with given content
*
* @param pkg
* @param rule
* @param content
* @throws MalformedURLException
* @throws IOException
*/
public void createRuleByAPI(String pkg, String rule, String content)
throws MalformedURLException, IOException {
createAssetByAPI(pkg, rule + ".brl",
content.getBytes(getRuleFileCharset()));
}

/**
* create asset for package
*
* @param pkg
* @param asset
* @param content
* @throws MalformedURLException
* @throws IOException
*/
public void createAssetByAPI(String pkg, String asset, byte[] content)
throws MalformedURLException, IOException {
String link = baseUrl + API + "packages/" + encode(pkg) + "/"
+ encode(asset);
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("enctype", "multipart/form-data");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
OutputStream out = conn.getOutputStream();
out.write(content);
out.flush();
out.close();
conn.connect();
// get the input stream is a mandatory for this operation, otherwise
// this method will not take effect.
conn.getInputStream();
conn.disconnect();
}

/**
* create binary asset for package
*
* @param pkg
* @param asset
* @param content
* @throws MalformedURLException
* @throws IOException
*/
public void createBinaryAssetByAPI(String pkg, String asset, String fileName)
throws MalformedURLException, IOException {
FileInputStream fis = null;
try{
File file = new File(fileName);
fis = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
fis.read(content);
createAssetByAPI(pkg, asset, content);
} finally {
if(fis!=null){
fis.close();
}
}
}

/**
* create package with given name
*
* @param pkg
* @throws MalformedURLException
* @throws IOException
*/
public void createPackageByAPI(String pkg) throws MalformedURLException,
IOException {
String link = baseUrl + REST + "packages";
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
OutputStream out = conn.getOutputStream();
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><package><description></description><title>"+pkg+"</title></package>";
//out.write(("package " + pkg).getBytes(getRuleFileCharset()));
out.write(xml.getBytes("UTF-8"));
out.flush();
out.close();
conn.connect();
// get the input stream is a mandatory for this operation, otherwise
// this method will not take effect.
conn.getInputStream();
conn.disconnect();
}

public void changeRuleStatus(String pkg, String rule, String status)
throws MalformedURLException, IOException {
String content = getAtomRuleByAPI(pkg, rule);
content = content.replaceAll("<state><value>.*</value></state>",
"<state><value>" + status + "</value></state>");
String link = baseUrl + REST + "packages/" + encode(pkg) + "/assets/"
+ encode(rule);
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/atom+xml");
conn.setRequestProperty("Content-Length",
String.valueOf(content.getBytes().length));
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("PUT");
conn.setUseCaches(false);
OutputStream out = conn.getOutputStream();
out.write(content.getBytes("UTF-8"));
out.flush();
out.close();
conn.connect();
// get the input stream is a mandatory for this operation, otherwise
// this method will not take effect.
conn.getInputStream();
conn.disconnect();
}

/**
* get the atom xml of a given rule
*
* @param pkg
* @param rule
* @return
* @throws MalformedURLException
* @throws IOException
*/
public String getAtomRuleByAPI(String pkg, String rule)
throws MalformedURLException, IOException {
String link = baseUrl + REST + "packages/" + encode(pkg) + "/assets/"
+ encode(rule);
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept", "application/atom+xml");
conn.setRequestMethod("GET");
conn.setUseCaches(false);
conn.connect();

InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
conn.disconnect();
return sb.toString();
}

/**
* get rule content
*
* @param pkg
* @param rule
* @return
* @throws MalformedURLException
* @throws IOException
*/
public String getRuleContentByAPI(String pkg, String rule)
throws MalformedURLException, IOException {
String link = baseUrl + REST + "packages/" + encode(pkg) + "/assets/"
+ encode(rule) + "/binary";
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Accept", DroolsUtil.ACCEPT);
InputStream is = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(reader);
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}

/**
* update rule action for test rules
*
* @param pkg
* @param rule
* @throws MalformedURLException
* @throws IOException
*/
public void updateRuleContent(String pkg, String rule)
throws MalformedURLException, IOException {
String content = getRuleContentByAPI(pkg, rule);
content = content.replaceAll("监控该订单", "设置为嫌疑订单");
String link = baseUrl + REST + "packages/" + encode(pkg) + "/assets/"
+ encode(rule) + "/source";
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "text/plain;charset=gbk");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("PUT");
conn.setUseCaches(false);
OutputStream out = conn.getOutputStream();
out.write(content.getBytes("GBK"));
out.flush();
out.close();
conn.connect();
// get the input stream is a mandatory for this operation, otherwise
// this method will not take effect.
conn.getInputStream();
conn.disconnect();
}

public void updatePackageImport(String pkg, byte[] packageImport)
throws MalformedURLException, IOException {
String link = baseUrl + REST + "packages/" + encode(pkg) + "/assets/drools/source";
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "text/plain;charset=gbk");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("PUT");
conn.setUseCaches(false);
OutputStream out = conn.getOutputStream();
out.write(packageImport);
out.flush();
out.close();
conn.connect();
// get the input stream is a mandatory for this operation, otherwise
// this method will not take effect.
conn.getInputStream();
conn.disconnect();
}

/**
* restore removed rule
*
* @param pkg
* @param rule
* @throws MalformedURLException
* @throws IOException
*/
public void restoreRule(String pkg, String rule)
throws MalformedURLException, IOException {
String content = getRuleContentByAPI(pkg, rule);
createRuleByAPI(pkg, rule, content);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: