ludc
2025-01-16 986aa62ed00bee39363bab41b4eeb8259d446efd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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&param1,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&param1,param2....}
     *            取子串处理:${attrName}-${attrName?subString(0,1)#className&methodName&param1,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);
        }
    }
    
}