文章标题

/**
*
*/
package com.pingan.drlgen.service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.pingan.drlgen.common.DrlGenConstant;
import com.pingan.drlgen.common.DrlGenLogger;
import com.pingan.drlgen.model.DrlFile;
import com.pingan.drlgen.model.RuleExpression;
import com.pingan.drlgen.model.RuleExpressionElement;
import com.pingan.drlgen.model.element.Field;
import com.pingan.drlgen.model.element.LogicOperator;
import com.pingan.drlgen.model.element.Operator;
import com.pingan.drlgen.model.element.RelationalOperator;
import com.pingan.drlgen.model.element.SpecialOperator;
import com.pingan.drlgen.model.element.Value;
import com.pingan.drlgen.model.element.ValueList;

/**
* @author Administrator
*
*


* 本类负责:1、生成DRL文件;
*


*
*/
public class DrlFileService {
/**
 * 
 */
public DrlFileService() {

}

/**
 * 获取需要import的类
 * 
 * @param list
 *            规则元素列表
 * @return
 * @throws Exception
 */
private String getImportInfo(List<RuleExpressionElement> list)
        throws Exception {
    StringBuffer importStr = new StringBuffer();
    // 01、判断参数是否为空
    if (null == list || 0 >= list.size()) {
        throw new Exception("getImportInfo异常,参数list为空!");
    }

    // 02、遍历列表获取需要import类
    for (int i = 0; i < list.size(); i++) {
        RuleExpressionElement elem = list.get(i);
        if (DrlGenConstant.ELEM_FIELD.equals(elem.getElementType())) {
            Field field = (Field) elem;
            String fullClassName = field.getFullClassName();
            if (-1 == importStr.indexOf(fullClassName)) {
                importStr.append("import " + fullClassName + ";\r\n");
            }
        }
    }
    return importStr.toString();
}

/**
 * 获取DRL定义的变量名字
 * 
 * @param columnName
 *            属性列名字
 * @return
 */
private String getVarName(String columnName) {
    if (-1 != columnName.indexOf(".")) {
        return "$" + columnName.replaceAll("\\.", "_");
    } else {
        return "$" + columnName;
    }
}

/**
 * 获取需要变量定义信息
 * 
 * @param list
 *            规则元素列表
 * @return
 * @throws Exception
 */
private String getVarDefInfo(List<RuleExpressionElement> list)
        throws Exception {
    StringBuffer defStr = new StringBuffer();
    Map<String, List<String>> defMap = new HashMap<String, List<String>>();
    // 01、判断参数是否为空
    if (null == list || 0 >= list.size()) {
        throw new Exception("getVarDefInfo异常,参数list为空!");
    }
    // 02、遍历列表获取需要定义变量的元素
    for (int i = 0; i < list.size(); i++) {
        RuleExpressionElement elem = list.get(i);
        if (DrlGenConstant.ELEM_FIELD.equals(elem.getElementType())) {
            Field field = (Field) elem;
            String fullClassName = field.getFullClassName();
            String columnName = field.getColumnName();
            Set<String> keySet = defMap.keySet();
            if (!keySet.contains(fullClassName)) {
                List<String> colList = new ArrayList<String>();
                colList.add(columnName);
                defMap.put(fullClassName, colList);
            } else {
                List<String> colList = defMap.get(fullClassName);
                if (!colList.contains(columnName)) {
                    colList.add(columnName);
                }
            }

        }
    }
    // 03、将获取到的Map准换为变量定义语句
    Set<String> keySet = defMap.keySet();
    Iterator<String> it = keySet.iterator();
    while (it.hasNext()) {
        StringBuffer rowBuf = new StringBuffer();
        String key = (String) it.next();
        int idx = key.lastIndexOf(".") + 1;
        String className = key.substring(idx);
        rowBuf.append(DrlGenConstant.TAB + DrlGenConstant.TAB + className
                + "(");
        List<String> colList = defMap.get(key);
        for (int i = 0; i < colList.size(); i++) {
            String columnName = colList.get(i);
            String varName = getVarName(columnName);
            rowBuf.append(varName + ":" + columnName);
            if (i != colList.size() - 1) {
                rowBuf.append(",");
            } else {
                rowBuf.append(")");
            }
        }
        defStr.append(rowBuf.toString() + ";" + DrlGenConstant.NEW_LINE);
    }
    return defStr.toString();
}

/**
 * 获取DRL的判断条件信息
 * 
 * @param list
 *            规则元素列表
 * @return
 * @throws Exception
 */
private String getConditionInfo(List<RuleExpressionElement> list)
        throws Exception {
    StringBuffer conditionStr = new StringBuffer();
    // 01、判断参数是否为空
    if (null == list || 0 >= list.size()) {
        throw new Exception("getConditionInfo异常,参数list为空!");
    }

    // 02、遍历列表获取DRL的判断条件信息
    for (int i = 0; i < list.size(); i++) {
        RuleExpressionElement elem = list.get(i);
        String elementType = elem.getElementType();
        if (DrlGenConstant.ELEM_FIELD.equals(elementType)) {
            Field field = (Field) elem;
            String columnName = field.getColumnName();
            String varName = getVarName(columnName);
            conditionStr.append(varName);
        } else if (DrlGenConstant.ELEM_VALUE_LIST.equals(elementType)) {
            ValueList valueList = (ValueList) elem;
            if (1 == valueList.getList().size()) {
                Value valueObj = valueList.getList().get(0);
                String value = valueObj.getValue();
                conditionStr.append(" \"" + value + "\" ");
            } else {
                DrlGenLogger.info("暂不支持多值情况!");
            }
        } else if (DrlGenConstant.ELEM_OPERATOR.equals(elementType)) {
            Operator operator = (Operator) elem;
            String symbol = operator.getSymbol();
            if (DrlGenConstant.VALUE_LEFT_BRACKET.equals(symbol)) {
                conditionStr.append(" ( ");
            } else if (DrlGenConstant.VALUE_RIGHT_BRACKET.equals(symbol)) {
                conditionStr.append(" ) ");
            }
        } else if (DrlGenConstant.ELEM_RELATIONAL_OPERATOR
                .equals(elementType)) {
            RelationalOperator relationalOperator = (RelationalOperator) elem;
            String symbol = relationalOperator.getSymbol();
            if (DrlGenConstant.VALUE_GT.equals(symbol)) {
                conditionStr.append(" > ");
            } else if (DrlGenConstant.VALUE_LT.equals(symbol)) {
                conditionStr.append(" < ");
            } else if (DrlGenConstant.VALUE_EQ.equals(symbol)) {
                conditionStr.append(" == ");
            } else if (DrlGenConstant.VALUE_GTEQ.equals(symbol)) {
                conditionStr.append(" >= ");
            } else if (DrlGenConstant.VALUE_LTEQ.equals(symbol)) {
                conditionStr.append(" <= ");
            } else if (DrlGenConstant.VALUE_NOTEQ.equals(symbol)) {
                conditionStr.append(" != ");
            }
        } else if (DrlGenConstant.ELEM_LOGIC_OPERATOR.equals(elementType)) {
            LogicOperator logicOperator = (LogicOperator) elem;
            String symbol = logicOperator.getSymbol();
            if (DrlGenConstant.VALUE_AND.equals(symbol)) {
                conditionStr.append(" && ");
            } else if (DrlGenConstant.VALUE_OR.equals(symbol)) {
                conditionStr.append(" || ");
            } else if (DrlGenConstant.VALUE_NOT.equals(symbol)) {
                conditionStr.append(" ! ");
            }
        } else if (DrlGenConstant.ELEM_SPECIAL_OPERATOR.equals(elementType)) {
            SpecialOperator specialOperator = (SpecialOperator) elem;
            String symbol = specialOperator.getSymbol();
            if (DrlGenConstant.VALUE_IN.equals(symbol)) {
                DrlGenLogger.info("暂没实现特殊操作符:in!");
            } else if (DrlGenConstant.VALUE_NOTIN.equals(symbol)) {
                DrlGenLogger.info("暂没实现特殊操作符:not in!");
            }
        }
    }
    String condition = DrlGenConstant.TAB + DrlGenConstant.TAB + "eval("
            + conditionStr.toString() + ")" + DrlGenConstant.NEW_LINE;
    return condition;
}

/**
 * 生成DRL规则文件
 * 
 * @param ruleExpression
 *            规则表达式
 * @return
 * @throws Exception
 */
public DrlFile generateDrlFile(RuleExpression ruleExpression)
        throws Exception {
    DrlFile drlFile = new DrlFile();
    BufferedWriter bufWriter = null;
    try {
        // 01、判断参数是否合法
        if (null == ruleExpression) {
            throw new Exception("参数:ruleExpression为空!");
        }
        // 02、准备分别生成各个drl要素
        StringBuffer drlContent = new StringBuffer();
        // 03、生成package
        drlContent.append("package ")
                .append(ruleExpression.getPackagePath())
                .append(DrlGenConstant.NEW_LINE_DOUBLE);
        // 04、生成import
        drlContent.append(getImportInfo(ruleExpression.getList())).append(
                DrlGenConstant.NEW_LINE);
        // 05、生成规则名
        drlContent.append("rule \"").append(ruleExpression.getRuleId())
                .append("\"").append(DrlGenConstant.NEW_LINE);
        // 06、生成when
        drlContent.append(DrlGenConstant.TAB).append("when")
                .append(DrlGenConstant.NEW_LINE);
        // 07、生成变量定义
        drlContent.append(getVarDefInfo(ruleExpression.getList())).append(
                DrlGenConstant.NEW_LINE);
        // 08、生成条件
        drlContent.append(getConditionInfo(ruleExpression.getList()))
                .append(DrlGenConstant.NEW_LINE);
        // 09、生成then
        drlContent.append(DrlGenConstant.TAB).append("then")
                .append(DrlGenConstant.NEW_LINE);
        // 10、生成结果

        // 11、生成end
        drlContent.append("end").append(DrlGenConstant.NEW_LINE);
        // 12、输出生成的DRL文件内容
        DrlGenLogger.info(drlContent.toString());
        // 13、输出到文件
        String fileFullPath = DrlGenConstant.DRL_FILE_SAVE_PATH
                + ruleExpression.getRuleId()
                + DrlGenConstant.DRL_FILE_EXT_NAME;
        File file = new File(fileFullPath);
        bufWriter = new BufferedWriter(new FileWriter(file));
        bufWriter.write(drlContent.toString());
        bufWriter.flush();
        bufWriter.close();
        bufWriter = null;
    } catch (Exception e) {
        DrlGenLogger.error(e,
                "执行:generateDrlFile发生异常!异常信息:" + e.getMessage());
        throw e;
    } finally {
        if (null != bufWriter) {
            bufWriter.close();
        }
    }
    return drlFile;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值