package com.vci.server.common;
|
|
import java.io.IOException;
|
import java.io.StringReader;
|
import java.io.StringWriter;
|
import java.io.Writer;
|
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.Method;
|
import java.util.ArrayList;
|
import java.util.Enumeration;
|
import java.util.HashMap;
|
import java.util.Iterator;
|
import java.util.LinkedHashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
import freemarker.core.TemplateElement;
|
import freemarker.template.Configuration;
|
import freemarker.template.Template;
|
|
public class FreeMarkerCommon {
|
/**
|
* 根据模板属性配置的规则获取解析后的值
|
* <p>Description: </p>
|
* @author ligang
|
* @time 2012-11-27
|
* @param rootMap 属性值的组合
|
* @param ruleInfo 规则
|
* @return
|
* @throws Exception
|
* @throws IOException
|
*/
|
static String CLASS_NAME="";
|
static String METHOD_NAME ="";
|
static String PARAMATER_VALUE = "";
|
private final static String PACKAGENAME= "com.vci.freemaker";
|
public final static String SPLIT_PARAMERS="&";
|
public static final String SPLIT_TODO = "#";
|
/**
|
* ${attrName}-${attrName?className&methodName¶m1,param2....}
|
* ${身份证号}-${学历列表}-${加工方法#className&methodName&车,铣}
|
*/
|
@SuppressWarnings({ "unchecked", "rawtypes" })
|
public static String getValueByTempRule(Map<String, FreemarkerParamObject> rootMap,String attrRule) {
|
List<String> keys = getFreemarkExpressionKey(attrRule);
|
Map<String, String> map = constructExpressionMap(keys);
|
for (String key : keys) {
|
if (map.keySet().contains(key)) {
|
attrRule = attrRule.replaceAll(key, map.get(key));
|
}
|
}
|
map.keySet();
|
String formateAttrRule = checkDataParamers(rootMap,attrRule);
|
if(formateAttrRule.length()<attrRule.length()){//表示存在需要被处理的数据信息
|
attrRule = formateAttrRule;
|
Object obj = getDateDetail(rootMap);
|
if(obj!=null){
|
if(obj instanceof Map){
|
rootMap = (Map)obj;
|
}
|
}
|
}
|
String fremakerValue = new FreeMarkerCommon().getRusultByTempRule(rootMap,attrRule);
|
keys = getFreemarkExpressionKey(fremakerValue);
|
for (String key : keys) {
|
if (map.keySet().contains(key)) {
|
fremakerValue = fremakerValue.replaceAll(key, map.get(key));
|
}
|
}
|
return fremakerValue;
|
}
|
|
public static boolean isFreemarkExpression(String expression){
|
try {
|
boolean res = true;
|
String field = expression;
|
int begin = field.indexOf("${");
|
int end = field.indexOf("}");
|
int len = field.length();
|
String key = null;
|
while(!"".equals(field) && begin >= 0 && end < len){
|
key = field.substring(begin + 2, end);
|
if (key == null || key.trim().equals("")) {
|
return false;
|
}
|
field = field.substring(end + 1);
|
begin = field.indexOf("${");
|
end = field.indexOf("}");
|
len = field.length();
|
res = true;
|
}
|
if (key == null || key.trim().equals("")) {
|
return false;
|
}
|
return res;
|
} catch (Exception e) {
|
return false;
|
}
|
}
|
|
public static List<String> getFreemarkExpressionKey(String expression) {
|
List<String> list = new ArrayList<String>();
|
try {
|
String field = expression;
|
int begin = field.indexOf("${");
|
int end = field.indexOf("}");
|
int len = field.length();
|
String key = null;
|
while(!"".equals(field) && begin >= 0 && end < len){
|
key = field.substring(begin + 2, end);
|
if (key != null && !key.trim().equals("")) {
|
list.add(key);
|
}
|
field = field.substring(end + 1);
|
begin = field.indexOf("${");
|
end = field.indexOf("}");
|
len = field.length();
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
|
return list;
|
}
|
|
public static Map<String, String> constructExpressionMap(List<String> list) {
|
Map<String, String> map = new HashMap<String, String>();
|
for (String key : list) {
|
if (key.indexOf(".") < 0) {
|
continue;
|
}
|
map.put(key.replace(".", "_"), key);
|
map.put(key, key.replace(".", "_"));
|
}
|
|
return map;
|
}
|
|
public static Map<String, FreemarkerParamObject> convertValueMapToFPOMap(Map<String, String> map){
|
Map<String, FreemarkerParamObject> rootMap = new LinkedHashMap<String, FreemarkerParamObject>();
|
Iterator<String> it = map.keySet().iterator();
|
while(it.hasNext()){
|
String key = it.next();
|
String value = map.get(key);
|
if(value == null){
|
value = "";
|
}
|
String newKey = key.replace(".", "_");
|
FreemarkerParamObject fpo = new FreemarkerParamObject(newKey, value);
|
rootMap.put(newKey, fpo);
|
}
|
return rootMap;
|
}
|
|
public String getValByRule(Template t,Map<String, FreemarkerParamObject> rootMap,String attrRule,Configuration cfg) {
|
Writer out = new StringWriter();
|
try {
|
t = new Template("name", new StringReader(attrRule),cfg);
|
t.process(rootMap, out);
|
} catch(Exception ex){
|
out = new StringWriter();
|
((StringWriter)out).write(attrRule);
|
//((StringWriter)out).write("");
|
ex.printStackTrace();
|
}
|
return out.toString();
|
}
|
|
private void checkAllKeyInMap(Map<String, FreemarkerParamObject> rootMap,String attrRule){
|
String field = attrRule;
|
int begin = field.indexOf("${");
|
int end = field.indexOf("}");
|
int len = field.length();
|
String key = "";
|
while(!"".equals(field) && begin >= 0 && end < len){
|
key = field.substring(begin + 2, end);
|
if(!rootMap.containsKey(key)){
|
rootMap.put(key, new FreemarkerParamObject(key, "${"+key+"}"));
|
//rootMap.put(key, new FreemarkerParamObject(key, ""));
|
}
|
field = field.substring(end + 1);
|
begin = field.indexOf("${");
|
end = field.indexOf("}");
|
len = field.length();
|
}
|
}
|
|
public String getRusultByTempRule(Map<String, FreemarkerParamObject> rootMap,String attrRule) {
|
checkAllKeyInMap(rootMap, attrRule);
|
Configuration cfg = new Configuration();
|
Template t;
|
String ruleVal = "";
|
try {
|
String result = "";//组合规则的结果
|
t = new Template("name", new StringReader(attrRule),cfg);
|
TemplateElement templateElement = t.getRootTreeNode();
|
String[] elementValue = new String[templateElement.getChildCount()];//组合规则中各元素的值
|
int index = 0;
|
String a = "";
|
Map<Integer, String> connMap = new HashMap<Integer, String>();//存储连接符的对象
|
for (@SuppressWarnings("rawtypes")
|
Enumeration children = templateElement.children(); children.hasMoreElements();) {
|
Object object = children.nextElement();
|
String realVal = object.toString();
|
String str = getValByRule(t,rootMap, realVal,cfg);//获取组合规则对应的值
|
if (str.equals("")) {
|
a = "str";
|
}
|
//如果是模板属性规则
|
if(realVal.contains("${")) {
|
result += str;
|
elementValue[index] = str;
|
} else {//连接符的处理
|
if (a.equals("")) {
|
result += realVal;
|
elementValue[index] = realVal;
|
connMap.put(index, realVal);
|
|
}else {
|
a = "";
|
result += realVal;
|
elementValue[index] = realVal;
|
connMap.put(index, realVal);
|
}
|
|
}
|
|
index++;
|
}
|
|
if(elementValue.length <= 0) {
|
result = getValByRule(t,rootMap, attrRule,cfg);//获取组合规则对应的值
|
return result;
|
}
|
|
ruleVal = getResult(elementValue,result,connMap);
|
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
return ruleVal;
|
}
|
|
private String getResult(String[] elementValue,String result,Map<Integer, String> connMap) {
|
//获取需要过滤掉的关键字
|
String filetVal = "";//ConfigUtils.getConfigValue("Special.data.filter");
|
String ruleVal = "";
|
//对根据组合规则获取的值进行处理,过滤掉值为无的数据
|
for(int k = 0;k < elementValue.length;k++) {
|
if(k == 0 && !elementValue[k].equals("") && filetVal.contains(elementValue[k])) {
|
result = connMap.containsKey(k+1) ? result.replaceFirst(elementValue[k], "").replaceFirst(connMap.get(k+1), "") : result.replaceFirst(elementValue[k], "");
|
} else if(k != elementValue.length - 1 && !elementValue[k].equals("") && filetVal.contains(elementValue[k])) {
|
int index = result.indexOf(elementValue[k]);
|
String newResult = result.replaceFirst(elementValue[k], "");
|
if(index == 0 && connMap.containsKey(k-1)) {//如果为0,标示第一个节点是无
|
index = connMap.get(k-1).length();
|
}
|
result = newResult.length() > 0 && connMap.containsKey(k-1) ? newResult.substring(0,index - connMap.get(k-1).length()) + newResult.substring(index)
|
:newResult ;
|
} else if(k == elementValue.length - 1 && !elementValue[k].equals("") && filetVal.contains(elementValue[k])) {
|
result = result.replaceFirst(elementValue[k], "");
|
result = result.length() > 0 && connMap.containsKey(k-1) ? result.substring(0,result.length() - (connMap.get(k-1).length()))
|
:result.replaceFirst(elementValue[k], "") ;
|
}
|
}
|
|
ruleVal = result;
|
return ruleVal;
|
}
|
|
/**
|
* 检查是否存在需要被特殊处理的属性信息
|
* <p>Description: </p>
|
* @time 2013-7-17
|
* @param attrRuleParamers:纯文本组合: ${attrName}-${attrName#className&methodName¶m1,param2....}
|
* 取子串处理:${attrName}-${attrName?subString(0,1)#className&methodName¶m1,param2....}
|
* @return 组合规则信息
|
*/
|
private static String checkDataParamers(Map<String, FreemarkerParamObject> rootMap,String attrRuleParamers){
|
StringBuilder result = new StringBuilder();
|
StringBuilder atrrValue= new StringBuilder();
|
String[] attrArrays = attrRuleParamers.split("-");
|
for(int i = 0 ; i<attrArrays.length;i++){
|
String[] ontAttrArray = attrArrays[i].split(SPLIT_TODO);
|
if(ontAttrArray.length>1){
|
String attrAllName = ontAttrArray[0];
|
int start = attrAllName.indexOf("${");
|
int end = attrAllName.length();
|
if(attrAllName.contains("?")){
|
end = attrAllName.lastIndexOf("?");
|
}
|
String attrName = attrAllName.substring(start+2,end);
|
String[] classMthodPara = ontAttrArray[1].split("&");
|
if(classMthodPara.length>2){// 包含类,方法,参数信息
|
CLASS_NAME = classMthodPara[0];
|
METHOD_NAME = classMthodPara[1];
|
String[] attrVal = classMthodPara[2].split("}");
|
boolean isShowSubString = true;
|
atrrValue.append(attrName).append("=").append(attrVal[0]);
|
//处理含有截取子串的规则中,如果输入的数据值在该属性不需要显示的属性值范围内,则是组合规则编程纯文本的组合方式
|
if(attrAllName.contains("?")){
|
String attrValInput = rootMap.get(attrName).getValue();
|
String[] methodParams = attrVal[0].split(",");
|
for(String notShowAttr:methodParams){
|
if(attrValInput.equals(notShowAttr) ||attrValInput.equals("")){
|
String rightAttr = attrAllName.substring(0, attrAllName.lastIndexOf("?"));
|
isShowSubString = false;
|
attrArrays[i] = rightAttr+"}";
|
break;
|
}
|
}
|
}
|
if(isShowSubString){
|
attrArrays[i] = attrAllName+"}";
|
}
|
atrrValue.append("&");
|
}
|
}
|
result.append(attrArrays[i]).append("-");
|
}
|
if(atrrValue.length()>1){
|
PARAMATER_VALUE = atrrValue.substring(0,atrrValue.lastIndexOf("&"));
|
}
|
if(result.length()>1){
|
return result.substring(0,result.lastIndexOf("-"));
|
}
|
return "";
|
}
|
|
private static Object getDateDetail(Map<String, FreemarkerParamObject> rootMap){
|
Object result = new Object();
|
try {
|
Class<?> className = Class.forName(PACKAGENAME+"."+CLASS_NAME);
|
Object object = className.newInstance();
|
Method method = getMethod(className);
|
if(method != null){
|
result = method.invoke(object, rootMap,PARAMATER_VALUE);
|
}
|
} catch (InstantiationException e) {
|
e.printStackTrace();
|
} catch (IllegalAccessException e) {
|
e.printStackTrace();
|
} catch (IllegalArgumentException e) {
|
e.printStackTrace();
|
} catch (InvocationTargetException e) {
|
e.printStackTrace();
|
} catch (SecurityException e) {
|
e.printStackTrace();
|
} catch (ClassNotFoundException e) {
|
e.printStackTrace();
|
}
|
return result;
|
}
|
|
private static Method getMethod(Class<?> className){
|
Method method = null;
|
ArrayList<Class<?>> paramerClass = new ArrayList<Class<?>>();
|
paramerClass.add(Map.class);
|
paramerClass.add(String.class);
|
try {
|
method = className.getMethod(METHOD_NAME, paramerClass.toArray(new Class[]{}));
|
} catch (SecurityException e) {
|
e.printStackTrace();
|
} catch (NoSuchMethodException e) {
|
e.printStackTrace();
|
}
|
return method;
|
}
|
|
|
public static void main(String[] args){
|
// Map<String, FreemarkerParamObject> rootMap = new HashMap<String, FreemarkerParamObject>();
|
// rootMap.put("a", new FreemarkerParamObject("a","a"));
|
// rootMap.put("b", new FreemarkerParamObject("b","b"));
|
// rootMap.put("c", new FreemarkerParamObject("c","c"));
|
// rootMap.put("d", new FreemarkerParamObject("d","d"));
|
// rootMap.put("a.b.c.d", new FreemarkerParamObject("a.b.c.d","a.b.c.dval"));
|
// String rule = "${a} ${b} ${c} ${d} ${e} ${x.y.z} xxx ${a.b.c.d}";
|
// String res = new FreeMarkerCommon().getRusultByTempRule(rootMap, rule);
|
// System.out.println("rule:" + rule);
|
// System.out.println(" res:" + res);
|
|
String abc = "${t_oid_a}(${t_oid_b})${c}";
|
Map<String, String> map = new HashMap<String, String>();
|
map.put("t_oid.a", "eddie");
|
map.put("t_oid.b", "1972");
|
map.put("c", "c");
|
|
boolean is = FreeMarkerCommon.isFreemarkExpression(abc);
|
if (is) {
|
Map<String, FreemarkerParamObject> ff = FreeMarkerCommon.convertValueMapToFPOMap(map);
|
String value = FreeMarkerCommon.getValueByTempRule(ff, abc);
|
|
//System.out.println(value);
|
}
|
}
|
|
}
|