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.registry;
35
36 import info.magnolia.config.registry.decoration.DefinitionDecorator;
37
38 import java.util.ArrayList;
39 import java.util.Collections;
40 import java.util.List;
41
42
43
44
45
46
47
48
49
50 public class DefinitionProviderBuilder<T> {
51 public static <T> DefinitionProviderBuilder<T> newBuilder() {
52 return new DefinitionProviderBuilder<>();
53 }
54
55 private static final List<String> NO_ERRORS = Collections.emptyList();
56
57 private DefinitionMetadataBuilder metadata;
58 private DefinitionRawView rawView;
59 private T definition;
60 private List<String> errorMessages = null;
61
62 private DefinitionProviderBuilder() {
63 }
64
65 public DefinitionProviderBuilder<T> metadata(DefinitionMetadataBuilder metadata) {
66 this.metadata = metadata;
67 return this;
68 }
69
70 public DefinitionProviderBuilder<T> rawView(DefinitionRawView rawView) {
71 this.rawView = rawView;
72 return this;
73 }
74
75 public DefinitionProviderBuilder<T> definition(T definition) {
76 this.definition = definition;
77 return this;
78 }
79
80 public DefinitionProviderBuilder<T> addErrorMessage(String errorMessage) {
81
82 if (this.errorMessages == null) {
83 this.errorMessages = new ArrayList<>();
84 }
85 this.errorMessages.add(errorMessage);
86 return this;
87 }
88
89 public DefinitionProvider<T> build() {
90 return new DefinitionProviderImpl<>(
91 this.metadata.build(),
92 this.rawView,
93 this.definition,
94 this.errorMessages != null ? this.errorMessages : NO_ERRORS
95 );
96 }
97
98
99
100
101 static class DefinitionProviderImpl<T> implements DefinitionProvider<T> {
102 private final DefinitionMetadata metadata;
103 private final DefinitionRawView rawView;
104 private final T definition;
105 private final List<String> errorMessages;
106 private final boolean valid;
107
108 protected DefinitionProviderImpl(DefinitionMetadata metadata, DefinitionRawView rawView, T definition, List<String> errorMessages) {
109 this.metadata = metadata;
110 this.rawView = rawView;
111 this.definition = definition;
112 this.errorMessages = errorMessages;
113
114 this.valid = (metadata != null && rawView != null && definition != null && errorMessages.isEmpty());
115 }
116
117 @Override
118 public List<DefinitionDecorator<T>> getDecorators() {
119 return Collections.emptyList();
120 }
121
122 @Override
123 public DefinitionMetadata getMetadata() {
124 return metadata;
125 }
126
127 @Override
128 public DefinitionRawView getRaw() {
129 return rawView;
130 }
131
132 @Override
133 public T get() {
134 if (!isValid()) {
135 throw new Registry.InvalidDefinitionException(metadata.getReferenceId());
136 }
137 return definition;
138 }
139
140 @Override
141 public boolean isValid() {
142 return valid;
143 }
144
145 @Override
146 public List<String> getErrorMessages() {
147 return errorMessages;
148 }
149
150 }
151 }