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.config.source.yaml;
35
36 import info.magnolia.config.map2bean.Map2BeanTransformer;
37 import info.magnolia.config.registry.Registry;
38 import info.magnolia.config.source.AbstractConfigurationSourceBuilder;
39 import info.magnolia.resourceloader.ResourceOrigin;
40
41 import java.io.IOException;
42 import java.util.regex.Pattern;
43 import java.util.regex.PatternSyntaxException;
44
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48
49
50
51 public class YamlConfigurationSourceBuilder extends AbstractConfigurationSourceBuilder {
52
53 private static final Logger log = LoggerFactory.getLogger(YamlConfigurationSourceBuilder.class);
54
55
56
57
58
59
60 private static final String MODULE_CONVENTIONS_FORMAT = "^/(?<module>[a-zA-Z0-9-_]+)/(?<deftype>%s)/(?<relPath>.*/)?(?<name>[a-zA-Z0-9-_\\.]+)\\.yaml$";
61
62 private final ResourceOrigin origin;
63 private final YamlReader yamlReader;
64 private final Map2BeanTransformer map2BeanTransformer;
65 private String pathPattern;
66
67 public YamlConfigurationSourceBuilder(ResourceOrigin origin, Map2BeanTransformer map2BeanTransformer, YamlReader yamlReader) {
68 this.origin = origin;
69 this.map2BeanTransformer = map2BeanTransformer;
70 this.yamlReader = yamlReader;
71 }
72
73 public YamlConfigurationSourceBuilder withPattern(String pathPattern) {
74 this.pathPattern = pathPattern;
75 return this;
76 }
77
78 @Override
79 public void bindTo(Registry<?> registry) {
80 final Pattern pathPattern = validatePathPattern(this.pathPattern);
81 if (registry == null) {
82 throw new NullPointerException("Must pass a registry instance");
83 }
84
85 try {
86 final YamlConfigurationSource<?> yamlConfigurationSource = new YamlConfigurationSource<>(origin, map2BeanTransformer, registry, pathPattern, yamlReader);
87 yamlConfigurationSource.start();
88 } catch (IOException e) {
89 throw new RuntimeException(e);
90 }
91 }
92
93 public void bindWithDefaults(Registry registry) {
94 if (pathPattern != null) {
95 throw new IllegalStateException(this + " is already partially configured, don't use bindWithDefaults().");
96 }
97 withPattern(moduleConventionsFormatFor(registry)).bindTo(registry);
98 }
99
100 protected Pattern validatePathPattern(String regex) {
101 if (pathPattern == null) {
102 throw new IllegalStateException(this + " is incomplete.");
103 }
104 try {
105 final Pattern pattern = Pattern.compile(regex);
106
107 return pattern;
108 } catch (PatternSyntaxException e) {
109 log.warn("Pattern {} is invalid: {}", regex, e.getMessage());
110 return Pattern.compile("$^");
111 }
112 }
113
114
115 protected String moduleConventionsFormatFor(Registry registry) {
116 final String pluralTypeName = pluralTypeNameOf(registry);
117 return String.format(MODULE_CONVENTIONS_FORMAT, pluralTypeName);
118 }
119
120 }