ExpressionTest.java 2.18 KB
package cn.runsa.crmapp.common;

import com.alibaba.fastjson.JSON;

import cn.runsa.crmapp.common.expression.ExpGroup;
import cn.runsa.crmapp.common.expression.Expression;
import cn.runsa.crmapp.common.expression.ExpressionBuilder;
import cn.runsa.crmapp.common.expression.LogicTranslator;

public class ExpressionTest {
	
	public static void main(String[] args) {
		String str = "{\"logic\":\"or\",\"groups\":[{\"logic\":\"and\",\"exps\":[{\"key\":\"birthday\",\"op\":\"gt\",\"type\":\"function\",\"function\":\"WEEK\",\"val\":\"30\"},{\"key\":\"birthday\",\"op\":\"lt\",\"type\":\"function\",\"function\":\"YEAR\",\"val\":\"1980\"}]},{\"logic\":\"and\",\"exps\":[{\"key\":\"cstType\",\"op\":\"eq\",\"val\":\"1\"},{\"key\":\"sex\",\"op\":\"ne\",\"val\":\"0\"}]}]}";
		ExpGroup group = JSON.parseObject(str, ExpGroup.class);
		ExpressionBuilder builder  = new ExpressionBuilder(new LogicTranslator(){

			@Override
			public String translate(String logic) {
				// TODO Auto-generated method stub
				return logic;
			}
			
		}){

			@Override
			public String parseExpression(Expression exp) {
				StringBuilder sb = new StringBuilder();
				if(exp.getType() == null){
					sb.append(exp.getKey());
					switch (exp.getOp()) {
					case eq:
						sb.append(" = ");
						break;
					case ne:
						sb.append(" != ");
						break;
					case gt:
						sb.append(" > ");
						break;
					case lt:
						sb.append(" < ");
						break;
					case ge:
						sb.append(" >= ");
						break;
					case le:
						sb.append(" <= ");
						break;
					}
					sb.append(exp.getVal());
				}else if("function".equals(exp.getType())){
					sb.append(exp.getFunction());
					sb.append("(");
					sb.append(exp.getKey());
					sb.append(")");
					switch (exp.getOp()) {
					case eq:
						sb.append(" = ");
						break;
					case ne:
						sb.append(" != ");
						break;
					case gt:
						sb.append(" > ");
						break;
					case lt:
						sb.append(" < ");
						break;
					case ge:
						sb.append(" >= ");
						break;
					case le:
						sb.append(" <= ");
						break;
					}
					sb.append(exp.getVal());
				}
				return sb.toString();
			}
			
		};
		String stat = builder.buildStatement(group);
		System.out.println(stat);
	}

}