1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.basepom.mojo.propertyhelper;
16
17 import static com.google.common.base.Preconditions.checkNotNull;
18
19 import org.basepom.mojo.propertyhelper.beans.IgnoreWarnFail;
20
21 import java.io.IOException;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.regex.Pattern;
25
26 import com.google.common.collect.ImmutableList;
27 import org.apache.maven.model.Model;
28 import org.codehaus.plexus.interpolation.EnvarBasedValueSource;
29 import org.codehaus.plexus.interpolation.InterpolationException;
30 import org.codehaus.plexus.interpolation.Interpolator;
31 import org.codehaus.plexus.interpolation.MapBasedValueSource;
32 import org.codehaus.plexus.interpolation.ObjectBasedValueSource;
33 import org.codehaus.plexus.interpolation.PrefixAwareRecursionInterceptor;
34 import org.codehaus.plexus.interpolation.PrefixedValueSourceWrapper;
35 import org.codehaus.plexus.interpolation.PropertiesBasedValueSource;
36 import org.codehaus.plexus.interpolation.StringSearchInterpolator;
37
38 public final class InterpolatorFactory {
39
40 private static final List<String> SYNONYM_PREFIXES = ImmutableList.of("project", "pom");
41 private static final String PREFIX = "#{";
42 private static final String POSTFIX = "}";
43
44 private final Model model;
45
46 public InterpolatorFactory(final Model model) {
47 this.model = model;
48 }
49
50 public String interpolate(final String value, final IgnoreWarnFail onMissingProperty, final Map<String, String> properties)
51 throws IOException, InterpolationException {
52 checkNotNull(value, "value is null");
53 checkNotNull(properties, "properties is null");
54
55 final Interpolator interpolator = new StringSearchInterpolator(PREFIX, POSTFIX);
56 interpolator.addValueSource(new EnvarBasedValueSource());
57 interpolator.addValueSource(new PropertiesBasedValueSource(System.getProperties()));
58
59 if (model != null) {
60 final Model pomModel = model;
61 interpolator.addValueSource(new PrefixedValueSourceWrapper(new ObjectBasedValueSource(pomModel),
62 SYNONYM_PREFIXES,
63 true));
64
65 interpolator.addValueSource(new PrefixedValueSourceWrapper(new PropertiesBasedValueSource(pomModel.getProperties()),
66 SYNONYM_PREFIXES,
67 true));
68 }
69
70 interpolator.addValueSource(new MapBasedValueSource(properties));
71
72 final String result = interpolator.interpolate(value, new PrefixAwareRecursionInterceptor(SYNONYM_PREFIXES, true));
73 final String stripped = result.replaceAll(Pattern.quote(PREFIX) + ".*?" + Pattern.quote(POSTFIX), "");
74 IgnoreWarnFail.checkState(onMissingProperty, stripped.equals(result), "property");
75 return stripped;
76 }
77 }