Skip to contentPackage: DefaultResourceProperties$1
DefaultResourceProperties$1
Coverage
1: /*
2: * *************************************************************************************************************************************************************
3: *
4: * NorthernWind - lightweight CMS
5: * http://tidalwave.it/projects/northernwind
6: *
7: * Copyright (C) 2011 - 2025 Tidalwave s.a.s. (http://tidalwave.it)
8: *
9: * *************************************************************************************************************************************************************
10: *
11: * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
12: * You may obtain a copy of the License at
13: *
14: * http://www.apache.org/licenses/LICENSE-2.0
15: *
16: * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
17: * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
18: *
19: * *************************************************************************************************************************************************************
20: *
21: * git clone https://bitbucket.org/tidalwave/northernwind-src
22: * git clone https://github.com/tidalwave-it/northernwind-src
23: *
24: * *************************************************************************************************************************************************************
25: */
26: package it.tidalwave.northernwind.core.impl.model;
27:
28: import javax.annotation.Nonnull;
29: import java.time.ZonedDateTime;
30: import java.util.Collection;
31: import java.util.HashMap;
32: import java.util.List;
33: import java.util.Map;
34: import java.util.Optional;
35: import java.util.concurrent.CopyOnWriteArrayList;
36: import java.util.function.Function;
37: import java.io.IOException;
38: import it.tidalwave.util.As;
39: import it.tidalwave.util.Id;
40: import it.tidalwave.util.Key;
41: import it.tidalwave.util.NotFoundException;
42: import it.tidalwave.northernwind.core.model.ResourcePath;
43: import it.tidalwave.northernwind.core.model.ResourceProperties;
44: import lombok.Getter;
45: import lombok.ToString;
46: import lombok.experimental.Delegate;
47: import lombok.extern.slf4j.Slf4j;
48: import static java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME;
49: import static java.util.stream.Collectors.*;
50:
51: /***************************************************************************************************************************************************************
52: *
53: * The default implementation of {@link ResourceProperties}.
54: *
55: * @author Fabrizio Giudici
56: *
57: **************************************************************************************************************************************************************/
58: // FIXME: this is a patched copy, needs public constructor for builder - see NW-180
59: @Slf4j @ToString(exclude={"propertyResolver", "asSupport"})
60: public class DefaultResourceProperties implements ResourceProperties
61: {
62: @SuppressWarnings("squid:S1171")
63: private static final Map<Class<?>, Function<String, Object>> CONVERTER_MAP =
64: new HashMap<>()
65: {{
66: put(Integer.class, Integer::parseInt);
67: put(Float.class, Float::parseFloat);
68: put(Double.class, Double::parseDouble);
69: put(Boolean.class, Boolean::parseBoolean);
70: put(ZonedDateTime.class, o -> ZonedDateTime.parse(o, ISO_ZONED_DATE_TIME));
71: put(ResourcePath.class, ResourcePath::of);
72: }};
73:
74: @Nonnull @Getter
75: private final Id id;
76:
77: /* Use String as key, and not Key. In this way properties can be managed both in an untyped fashion - e.g. by means
78: of Key.of("foo", Object.class) - and typed at the same time - e.g. Key.of("foo", Boolean.class). */
79: private final Map<String, Object> propertyMap = new HashMap<>();
80:
81: private final Map<Id, DefaultResourceProperties> groupMap = new HashMap<>();
82:
83: @Nonnull
84: private final PropertyResolver propertyResolver;
85:
86: @Delegate
87: private final As asSupport = As.forObject(this);
88:
89: /***********************************************************************************************************************************************************
90: *
91: **********************************************************************************************************************************************************/
92: public DefaultResourceProperties (@Nonnull final ResourceProperties.Builder builder)
93: {
94: this.id = builder.getId();
95: this.propertyResolver = builder.getPropertyResolver();
96: this.propertyMap.putAll(builder.getValues());
97: // for (final Entry<Key<?>, Object> entry : builder.getValues().entrySet())
98: // {
99: // final String s = entry.getKey().stringValue();
100: // final Object value = entry.getValue();
101: // propertyMap.put(new Key<>(s) {}, value);
102: // }
103: }
104:
105: /***********************************************************************************************************************************************************
106: * Deep clone constructor.
107: **********************************************************************************************************************************************************/
108: public DefaultResourceProperties (@Nonnull final DefaultResourceProperties otherProperties)
109: {
110: this.id = otherProperties.id;
111: this.propertyResolver = otherProperties.propertyResolver;
112:
113: otherProperties.propertyMap.forEach(propertyMap::put); // FIXME: clone the property
114: otherProperties.groupMap.forEach((k, v) -> groupMap.put(k, new DefaultResourceProperties(v)));
115: }
116:
117: /***********************************************************************************************************************************************************
118: * Legacy code for converting from flat-style properties. This is different than passing from() in the Builder,
119: * since that approach doesn't support nested groups.
120: **********************************************************************************************************************************************************/
121: public DefaultResourceProperties (@Nonnull final Id id,
122: @Nonnull final Map<String, Object> map,
123: @Nonnull final PropertyResolver propertyResolver)
124: {
125: this.id = id;
126: this.propertyResolver = propertyResolver;
127:
128: final Map<Id, Map<String, Object>> othersMap = new HashMap<>();
129:
130: for (final var entry : map.entrySet())
131: {
132: final var s = entry.getKey();
133: final var value = entry.getValue();
134:
135: if (!s.contains("."))
136: {
137: propertyMap.put(s, value);
138: }
139: else
140: {
141: final var x = s.split("\\.");
142: final var groupId = new Id(x[0]);
143: final var otherMap = othersMap.computeIfAbsent(groupId, __ -> new HashMap<>());
144: otherMap.put(x[1], value);
145: }
146: }
147:
148: for (final var entry : othersMap.entrySet())
149: {
150: groupMap.put(entry.getKey(), new DefaultResourceProperties(entry.getKey(), entry.getValue(), propertyResolver));
151: }
152: }
153:
154: /***********************************************************************************************************************************************************
155: * {@inheritDoc}
156: **********************************************************************************************************************************************************/
157: @Override @Nonnull
158: public <T> Optional<T> getProperty (@Nonnull final Key<? extends T> key)
159: {
160: try
161: {
162: final var value = propertyMap.get(key.getName());
163: return Optional.of(convertValue(key, (value != null) ? value : propertyResolver.resolveProperty(id, key)));
164: }
165: catch (IOException e)
166: {
167: log.trace("Could not resolve property", e);
168: return Optional.empty();
169: }
170: catch (NotFoundException e)
171: {
172: log.trace("Could not resolve property {}", e.getMessage());
173: return Optional.empty();
174: }
175: }
176:
177: /***********************************************************************************************************************************************************
178: * {@inheritDoc}
179: **********************************************************************************************************************************************************/
180: @Override @Nonnull
181: public ResourceProperties getGroup (@Nonnull final Id id)
182: {
183: final var properties = groupMap.get(id);
184: return properties != null ? properties : new DefaultResourceProperties(this);
185: // : new DefaultResourceProperties(new Builder().withId(id).withPropertyResolver(propertyResolver));
186: }
187:
188: /***********************************************************************************************************************************************************
189: * {@inheritDoc}
190: **********************************************************************************************************************************************************/
191: @Override @Nonnull
192: public Collection<Key<?>> getKeys()
193: {
194: return propertyMap.keySet().stream().map(Key::of).collect(toList());
195: }
196:
197: /***********************************************************************************************************************************************************
198: * {@inheritDoc}
199: **********************************************************************************************************************************************************/
200: @Override @Nonnull
201: public Collection<Id> getGroupIds() // FIXME: should be a Set
202: {
203: return new CopyOnWriteArrayList<>(groupMap.keySet());
204: }
205:
206: /***********************************************************************************************************************************************************
207: * {@inheritDoc}
208: **********************************************************************************************************************************************************/
209: @Override @Nonnull
210: public <T> DefaultResourceProperties withProperty (@Nonnull final Key<T> key, @Nonnull final T value)
211: {
212: final var result = new DefaultResourceProperties(this);
213: result.propertyMap.put(key.getName(), value); // FIXME: clone property
214: return result;
215: }
216:
217: /***********************************************************************************************************************************************************
218: * {@inheritDoc}
219: **********************************************************************************************************************************************************/
220: @Override @Nonnull
221: public DefaultResourceProperties withoutProperty (@Nonnull final Key<?> key)
222: {
223: final var result = new DefaultResourceProperties(this);
224: result.propertyMap.remove(key.getName());
225: return result;
226: }
227:
228: /***********************************************************************************************************************************************************
229: * {@inheritDoc}
230: **********************************************************************************************************************************************************/
231: @Override @Nonnull
232: public DefaultResourceProperties withProperties (@Nonnull final ResourceProperties properties)
233: {
234: final var result = new DefaultResourceProperties(this);
235: result.groupMap.put(properties.getId(), new DefaultResourceProperties((DefaultResourceProperties)properties));
236: return result;
237: }
238:
239: /***********************************************************************************************************************************************************
240: * {@inheritDoc}
241: **********************************************************************************************************************************************************/
242: @Override @Nonnull
243: public ResourceProperties merged (@Nonnull final ResourceProperties properties)
244: {
245: final var otherProperties = (DefaultResourceProperties)properties;
246:
247: if (!id.equals(otherProperties.id))
248: {
249: throw new IllegalArgumentException("Id mismatch " + id + " vs " + otherProperties.id);
250: }
251:
252: ResourceProperties result = new DefaultResourceProperties(this);
253:
254: for (final var entry : otherProperties.propertyMap.entrySet())
255: {
256: result = result.withProperty(Key.of(entry.getKey()), entry.getValue());
257: }
258:
259: for (final var entry : otherProperties.groupMap.entrySet())
260: {
261: final var groupId = entry.getKey();
262: final ResourceProperties propertyGroup = entry.getValue();
263: result = (!groupMap.containsKey(groupId)) ? result.withProperties(propertyGroup)
264: : result.withProperties(groupMap.get(groupId).merged(propertyGroup));
265: }
266:
267: return result;
268: }
269:
270: /***********************************************************************************************************************************************************
271: * {@inheritDoc}
272: **********************************************************************************************************************************************************/
273: @Override @Nonnull
274: public ResourceProperties withId (@Nonnull final Id id)
275: {
276: return new DefaultResourceProperties(this);
277: // return new DefaultResourceProperties(new Builder().withId(id).withPropertyResolver(propertyResolver));
278: }
279:
280: /***********************************************************************************************************************************************************
281: * Converts a property value from String to its expected value. This is because properties are read by unmarshaller
282: * as string.
283: **********************************************************************************************************************************************************/
284: @Nonnull
285: /* visible for testing */ static <T> T convertValue (@Nonnull final Key<T> key, @Nonnull final Object value)
286: {
287: log.trace("convertValue({}, {})", key, value);
288: final T result;
289:
290: try
291: {
292: if (key.getType().isAssignableFrom(value.getClass()))
293: {
294: result = key.getType().cast(value);
295: }
296: else if ("tags".equals(key.getName())) // workaround as Zephyr stores it as a comma-separated string
297: {
298: result = (T)List.of(((String)value).split(","));
299: }
300: // else if (value instanceof List)
301: // {
302: // final List<Object> list = (List<Object>)value;
303: // Class<?> elementType = String.class; // FIXME: should get the generic of the list
304: //
305: // return (T)list.stream()
306: // .map(i -> CONVERTER_MAP.getOrDefault(elementType, o -> o).apply(value))
307: // .collect(toList());
308: // }
309: else
310: {
311: result = (T)CONVERTER_MAP.getOrDefault(key.getType(), o -> o).apply((String)value);
312: }
313:
314: log.trace(">>>> returning {} ({})", result, result.getClass().getName());
315: return result;
316: }
317: catch (Exception e)
318: {
319: throw new RuntimeException(String.format("Can't convert '%s' to %s(%s)", value, key, key.getType()), e);
320: }
321: }
322: }