1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.krad.util;
17
18 import java.util.HashSet;
19 import java.util.Map;
20 import java.util.Set;
21
22 public class MessageUtils {
23
24
25
26
27
28
29
30
31
32 public static String interpolate(String message, String... data) {
33 if (message != null) {
34 for (int i = 0; i < data.length; i++) {
35 message = message.replaceAll("\\$\\{" + i + "\\}", "" + escape(data[i]));
36 }
37 }
38 return message;
39 }
40
41
42
43
44
45
46
47
48
49
50 public static String interpolate(String message, Map<String, Object> data) {
51 if (message != null && data != null) {
52 Set<String> fields = findFields(message);
53 for (String s : fields) {
54 if(data.get(s) != null){
55 message = message.replaceAll("\\$\\{" + s + "\\}", "" + escape(data.get(s).toString()));
56 }
57 }
58 }
59 return message;
60 }
61
62
63
64
65
66
67
68
69
70 public static String interpolate(String message, String parameter, Object value){
71 message = message.replaceAll("\\$\\{" + parameter + "\\}", "" + escape(value.toString()));
72 return message;
73 }
74
75
76
77
78
79
80
81 private static String escape(String input) {
82 char[] toEscape = {'\\', '$', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}'};
83 for (char c : toEscape) {
84 input = input.replaceAll("\\" + c, "\\\\\\" + c);
85 }
86 return input;
87 }
88
89
90
91
92
93
94
95
96 public static Set<String> findFields(String input) {
97 Set<String> result = new HashSet<String>();
98 int begin = input.indexOf("${");
99 while (begin != -1) {
100 int end = input.indexOf("}", begin);
101 result.add(input.substring(begin + 2, end));
102 begin = input.indexOf("${", end);
103 }
104 return result;
105 }
106
107 }