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 package info.magnolia.cms.util;
35
36 import info.magnolia.cms.core.Content;
37 import info.magnolia.cms.core.NodeData;
38
39 import java.util.Collection;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42
43
44
45
46
47
48
49
50
51
52 public class SearchReplace implements ContentUtil.Visitor {
53 private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SearchReplace.class);
54
55 final String propertyNamePattern;
56 final String search;
57 final String replace;
58
59 private final Pattern searchPattern;
60
61
62
63
64
65 public SearchReplace(String propertyNamePattern, String search, String replace) {
66 this(propertyNamePattern, search, replace, Pattern.LITERAL);
67 }
68
69
70
71
72 public SearchReplace(String propertyNamePattern, String search, String replace, int regexFlags) {
73 this.propertyNamePattern = propertyNamePattern;
74 this.search = search;
75 this.replace = replace;
76
77 this.searchPattern = Pattern.compile(search, regexFlags);
78 }
79
80 public void visit(Content node) throws Exception {
81 final Collection<NodeData> props = node.getNodeDataCollection(propertyNamePattern);
82 for (NodeData prop : props) {
83 if (prop.isExist()) {
84 final String oldValue = prop.getString();
85 final StringBuffer newValue = new StringBuffer();
86 final Matcher matcher = searchPattern.matcher(oldValue);
87 int count = 0;
88 while (matcher.find()) {
89 final String group = matcher.group();
90 matcher.appendReplacement(newValue, replace);
91 count++;
92 }
93 matcher.appendTail(newValue);
94 onPropertyVisit(prop, count, oldValue, newValue);
95 prop.setValue(newValue.toString());
96 }
97 }
98 }
99
100 protected void onPropertyVisit(NodeData prop, int count, String oldValue, StringBuffer newValue) {
101 log.debug(String.format("Found %d occurences of %s at %s", count, search, prop.getHandle()));
102 log.debug(String.format(" old value:\n %s\n\nnew value:\n%s", oldValue, newValue.toString()));
103 }
104
105 }