1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.javadpkg.replace;
20
21 import net.sourceforge.javadpkg.Context;
22
23
24
25
26
27
28
29
30
31
32 public class ReplacerImpl implements Replacer {
33
34
35
36
37
38
39
40 public ReplacerImpl() {
41 super();
42 }
43
44
45 @Override
46 public String replace(String line, Replacements replacements, Context context) throws ReplacementException {
47 int lastIndex, index;
48 StringBuilder sb = null;
49 String name, value;
50
51
52 if (line == null)
53 throw new IllegalArgumentException("Argument line is null.");
54 if (replacements == null)
55 throw new IllegalArgumentException("Argument replacements is null.");
56 if (context == null)
57 throw new IllegalArgumentException("Argument context is null.");
58
59
60 if (line.isEmpty())
61 return line;
62
63
64
65
66
67
68 lastIndex = 0;
69 index = 0;
70 while (index != -1) {
71 index = line.indexOf("${", index);
72 if (index >= 0) {
73 if (sb == null) {
74 sb = new StringBuilder();
75 }
76 sb.append(line.substring(lastIndex, index));
77 lastIndex = index + 2;
78 index = line.indexOf("}", lastIndex);
79 if (index == -1)
80 throw new ReplacementException("Found the beginning of a variable |" + line.substring(lastIndex)
81 + "|, but no end in line |" + line + "|.");
82 name = line.substring(lastIndex, index);
83 lastIndex = index + 1;
84 index = lastIndex;
85
86 value = replacements.getValue(name);
87 if (value == null) {
88 context.addWarning(new ReplacementVariableUnknownWarning(name));
89 sb.append("${");
90 sb.append(name);
91 sb.append('}');
92 } else {
93 sb.append(value);
94 }
95 } else if (sb != null) {
96 sb.append(line.substring(lastIndex));
97 }
98 }
99
100 if (sb == null)
101 return line;
102 return sb.toString();
103 }
104
105
106 }