1 | |
package org.codehaus.plexus.util.interpolation; |
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
|
20 | |
|
21 | |
|
22 | |
import org.codehaus.plexus.util.StringUtils; |
23 | |
|
24 | |
import java.util.ArrayList; |
25 | |
import java.util.Iterator; |
26 | |
import java.util.List; |
27 | |
import java.util.regex.Matcher; |
28 | |
import java.util.regex.Pattern; |
29 | |
|
30 | |
|
31 | |
public class RegexBasedInterpolator |
32 | |
{ |
33 | |
|
34 | |
private List valueSources; |
35 | |
|
36 | |
public RegexBasedInterpolator() |
37 | 0 | { |
38 | 0 | valueSources = new ArrayList(); |
39 | 0 | } |
40 | |
|
41 | |
public RegexBasedInterpolator( List valueSources ) |
42 | 0 | { |
43 | 0 | this.valueSources = new ArrayList( valueSources ); |
44 | 0 | } |
45 | |
|
46 | |
public void addValueSource( ValueSource valueSource ) |
47 | |
{ |
48 | 0 | this.valueSources.add( valueSource ); |
49 | 0 | } |
50 | |
|
51 | |
public void removeValuesSource( ValueSource valueSource ) |
52 | |
{ |
53 | 0 | this.valueSources.remove( valueSource ); |
54 | 0 | } |
55 | |
|
56 | |
public String interpolate( String input, String thisPrefixPattern ) |
57 | |
{ |
58 | 0 | String result = input; |
59 | |
|
60 | 0 | Pattern expressionPattern = Pattern.compile( "\\$\\{(" + thisPrefixPattern + ")?([^}]+)\\}" ); |
61 | 0 | Matcher matcher = expressionPattern.matcher( result ); |
62 | |
|
63 | 0 | while ( matcher.find() ) |
64 | |
{ |
65 | 0 | String wholeExpr = matcher.group( 0 ); |
66 | 0 | String realExpr = matcher.group( 2 ); |
67 | |
|
68 | 0 | if ( realExpr.startsWith( "." ) ) |
69 | |
{ |
70 | 0 | realExpr = realExpr.substring( 1 ); |
71 | |
} |
72 | |
|
73 | 0 | Object value = null; |
74 | 0 | for ( Iterator it = valueSources.iterator(); it.hasNext() && value == null; ) |
75 | |
{ |
76 | 0 | ValueSource vs = (ValueSource) it.next(); |
77 | |
|
78 | 0 | value = vs.getValue( realExpr ); |
79 | |
} |
80 | |
|
81 | |
|
82 | 0 | if ( wholeExpr.equals( value ) ) |
83 | |
{ |
84 | 0 | throw new IllegalArgumentException( "Expression: \'" + wholeExpr + "\' references itself." ); |
85 | |
} |
86 | |
|
87 | 0 | if ( value != null ) |
88 | |
{ |
89 | 0 | result = StringUtils.replace( result, wholeExpr, String.valueOf( value ) ); |
90 | |
|
91 | |
|
92 | |
|
93 | 0 | matcher.reset( result ); |
94 | |
} |
95 | |
} |
96 | |
|
97 | 0 | return result; |
98 | |
} |
99 | |
|
100 | |
} |