如何从DMN文件读取规则条目并添加到Java中的HashMap

时间:2019-02-20 13:33:06

标签: java hashmap rules camunda camunda-modeler

我需要将所有Input和Ouput变量-键/值对即哈希表中DMN文件/ XML下面的规则条目存储。

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/DMN/20151101/dmn.xsd" xmlns:camunda="http://camunda.org/schema/1.0/dmn" id="Definitions_1eoxrnj" name="DRD" namespace="http://camunda.org/schema/1.0/dmn">
  <decision id="dmn" name="dmnsch">
    <decisionTable id="decisionTable_1">
      <input id="input_1" label="Name" camunda:inputVariable="Name">
        <inputExpression id="inputExpression_1" typeRef="string">
          <text>Name</text>
        </inputExpression>
      </input>
      <output id="OutputClause_1n5q2uk" label="RollNo" name="RollNo" typeRef="string" />
      <rule id="DecisionRule_17f7eht">
        <inputEntry id="UnaryTests_0508jm1">
          <text>"Name1"</text>
        </inputEntry>
        <outputEntry id="LiteralExpression_0fbksp6">
          <text>"1"</text>
        </outputEntry>
      </rule>
      <rule id="DecisionRule_0a5bujl">
        <inputEntry id="UnaryTests_0xvk4es">
          <text>"Name2"</text>
        </inputEntry>
        <outputEntry id="LiteralExpression_0j3sowv">
          <text>"2"</text>
        </outputEntry>
      </rule>
    </decisionTable>
  </decision>
</definitions>

如果我以这种方式传递输入变量值,我就能获得输出变量值。

    VariableMap variables = Variables
              .putValue("Name", "Name1");
    DmnDecisionTableResult result = dmnEngine.evaluateDecisionTable(decision, variables);
    rollNo = result.getSingleResult().getSingleEntry().toString();
    System.out.println("Passed key and got value :" + rollNo);

此外,我能够从DMN读取输入和输出变量作为键值对,并以此方式添加到哈希表中。

    // find element instance by ID
    DecisionTable decisionTable = modelInstance.getModelElementById("decisionTable_1");
    //System.out.println("decisionTable " + decisionTable);

    // find all elements of the type DecisionTable
    ModelElementType decisionTableType = modelInstance.getModel()
      .getType(DecisionTable.class);
    Collection<ModelElementInstance> decisionTableInstances = 
      modelInstance.getModelElementsByType(decisionTableType);
    //System.out.println("decisionTableInstances " + decisionTableInstances);

    // read attributes by helper methods
    Collection<Rule> rules = modelInstance.getModelElementsByType(Rule.class);
     //System.out.println(rules.size());

      for(Rule r :rules) {
          InputEntry inputEntry = r.getInputEntries().iterator().next();
          String name = inputEntry.getTextContent();
          System.out.println(" inputEntry :: " + name);
          OutputEntry outputEntry = r.getOutputEntries().iterator().next();
          String rollno = outputEntry.getTextContent();
          System.out.println(" outputEntry :: " + rollno);
          classMap.put(name, rollno);
      }

我的哈希图应该看起来像

classMap :: {"Name1"="1", "Name2"="2"}

这是完整的代码。

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.camunda.bpm.dmn.engine.DmnDecision;
import org.camunda.bpm.dmn.engine.DmnDecisionTableResult;
import org.camunda.bpm.dmn.engine.DmnEngine;
import org.camunda.bpm.dmn.engine.DmnEngineConfiguration;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.model.dmn.Dmn;
import org.camunda.bpm.model.dmn.DmnModelInstance;
import org.camunda.bpm.model.dmn.instance.DecisionTable;
import org.camunda.bpm.model.dmn.instance.InputEntry;
import org.camunda.bpm.model.dmn.instance.OutputEntry;
import org.camunda.bpm.model.dmn.instance.Rule;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;
import org.camunda.bpm.model.xml.type.ModelElementType;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 * Schedule Maintenance for the machine based on frequency resulted from DMN
 *
 */
public class ReadDmn {

    private String dmnId = "dmn";
    private String dmnEvaluationKey = "dmnXml";

    public static void main(String[] args) throws Exception {   
        ReadDmn readDmn = new ReadDmn();
        Map<String, String> classMap = readDmn.loadDmnToMap();
        System.out.println("classMap :: " + classMap);
    }

    private Map<String, String> loadDmnToMap() throws Exception  {

        String rollNo;
        InputStream inputStream = null;
        Map<String, String> classMap = new HashMap<String, String>();

        try {
            String dmnresponse = getDMNXml();
            DmnEngine dmnEngine = DmnEngineConfiguration.createDefaultDmnEngineConfiguration().buildEngine();
            inputStream = new ByteArrayInputStream(dmnresponse.getBytes(Charset.forName("UTF-8")));

DmnModelInstance modelInstance = Dmn.readModelFromStream(inputStream);

            // find element instance by ID
            DecisionTable decisionTable = modelInstance.getModelElementById("decisionTable_1");
            //System.out.println("decisionTable " + decisionTable);

            // find all elements of the type DecisionTable
            ModelElementType decisionTableType = modelInstance.getModel()
              .getType(DecisionTable.class);
            Collection<ModelElementInstance> decisionTableInstances = 
              modelInstance.getModelElementsByType(decisionTableType);
            //System.out.println("decisionTableInstances " + decisionTableInstances);

            // read attributes by helper methods
            Collection<Rule> rules = modelInstance.getModelElementsByType(Rule.class);
             //System.out.println(rules.size());

              for(Rule r :rules) {
                  InputEntry inputEntry = r.getInputEntries().iterator().next();
                  String name = inputEntry.getTextContent();
                  System.out.println(" inputEntry :: " + name);
                  OutputEntry outputEntry = r.getOutputEntries().iterator().next();
                  String rollno = outputEntry.getTextContent();
                  System.out.println(" outputEntry :: " + rollno);
                  classMap.put(name, rollno);
              }
        }
        catch(Exception e){
        }
        finally {
              try {
                  if(inputStream != null) {
                      inputStream.close();
                  }
              }
              catch (IOException e) {
              }
         }
        return classMap;            
    }

    private String getDMNXml () throws Exception{
        try {   
            String dmnurl = "http://localhost:8080/engine-rest/decision-definition/key/" + dmnId  + "/xml";
            String dmnresponse = getDMNProperties(dmnurl);
            return dmnresponse;
        } catch (Exception e) {
        }
        return null;
    }

    private String getDMNProperties(String url) throws Exception {

        String dmnString = "";
        try {
            if (url.equals("")) {
                return null;
            }
            URL Url = new URL(url);
            HttpURLConnection con = (HttpURLConnection) Url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Content-Type", "application/json");
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();

            String output = content.toString();
            JSONParser parser = new JSONParser();
            Object output_obj = parser.parse(output);
            JSONObject jsonObject = (JSONObject) output_obj;
            dmnString = jsonObject.get(dmnEvaluationKey).toString();
            return dmnString;

        } catch (Exception e) {
        }
        return null;
    }
}

这是从DMN提取ruleEntry的正确方法,还是还有其他更好的方法?

有人可以在这方面帮助我吗?谢谢。

0 个答案:

没有答案