-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathAbstractYAMLBasedConfiguration.java
More file actions
179 lines (166 loc) · 7.56 KB
/
Copy pathAbstractYAMLBasedConfiguration.java
File metadata and controls
179 lines (166 loc) · 7.56 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* 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 CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.configuration2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.io.ConfigurationLogger;
import org.apache.commons.configuration2.tree.ImmutableNode;
import org.apache.commons.lang3.StringUtils;
/**
* <p>
* A base class for configuration implementations based on YAML structures.
* </p>
* <p>
* This base class offers functionality related to YAML-like data structures based on maps. Such a map has strings as
* keys and arbitrary objects as values. The class offers methods to transform such a map into a hierarchy of
* {@link ImmutableNode} objects and vice versa.
* </p>
*
* @since 2.2
*/
public class AbstractYAMLBasedConfiguration extends BaseHierarchicalConfiguration {
/**
* Adds a key value pair to a map, taking list structures into account. If a key is added which is already present in
* the map, this method ensures that a list is created.
*
* @param map the map
* @param key the key
* @param value the value
*/
private static void addEntry(final Map<String, Object> map, final String key, final Object value) {
final Object oldValue = map.get(key);
if (oldValue == null) {
map.put(key, value);
} else if (oldValue instanceof Collection) {
// safe case because the collection was created by ourselves
@SuppressWarnings("unchecked")
final Collection<Object> values = (Collection<Object>) oldValue;
values.add(value);
} else {
final Collection<Object> values = new ArrayList<>();
values.add(oldValue);
values.add(value);
map.put(key, values);
}
}
/**
* Internal helper method to wrap an exception in a {@code ConfigurationException}.
*
* @param e the exception to be wrapped
* @throws ConfigurationException the resulting exception
*/
static void rethrowException(final Exception e) throws ConfigurationException {
if (e instanceof ClassCastException) {
throw new ConfigurationException("Error parsing", e);
}
throw new ConfigurationException("Unable to load the configuration", e);
}
/**
* Creates a new instance of {@code AbstractYAMLBasedConfiguration}.
*/
protected AbstractYAMLBasedConfiguration() {
initLogger(new ConfigurationLogger(getClass()));
}
/**
* Creates a new instance of {@code AbstractYAMLBasedConfiguration} as a copy of the specified configuration.
*
* @param c the configuration to be copied
*/
protected AbstractYAMLBasedConfiguration(final HierarchicalConfiguration<ImmutableNode> c) {
super(c);
initLogger(new ConfigurationLogger(getClass()));
}
/**
* Creates a part of the hierarchical nodes structure of the resulting configuration. The passed in element is converted into one or multiple configuration
* nodes. (If list structures are involved, multiple nodes are returned.)
* <p>
* If an element has already been visited along the current recursion path, it is skipped and a warning is logged. This protects against cyclic YAML
* aliases that would otherwise cause infinite recursion.
* </p>
*
* @param key the key of the new node(s).
* @param elem the element to be processed.
* @param visited the set of visited objects (identity-based).
* @return a list with configuration nodes representing the element
*/
@SuppressWarnings("unchecked")
private List<ImmutableNode> constructHierarchy(final String key, final Object elem, final Set<Object> visited) {
if (elem instanceof Map || elem instanceof Collection) {
if (visited.add(elem)) {
return elem instanceof Map ? parseMap((Map<String, Object>) elem, key, visited) : parseCollection((Collection<Object>) elem, key, visited);
}
getLogger().warn(String.format("Cycle detected in YAML structure at key '%s'; skipping reference to avoid infinite recursion.", key));
return Collections.emptyList();
}
return Collections.singletonList(new ImmutableNode.Builder().name(key).value(elem).create());
}
/**
* Constructs a YAML map, i.e. String -> Object from a given configuration node.
*
* @param node The configuration node to create a map from.
* @return A Map that contains the configuration node information.
*/
protected Map<String, Object> constructMap(final ImmutableNode node) {
final Map<String, Object> map = new HashMap<>(node.getChildren().size());
node.forEach(cNode -> addEntry(map, cNode.getNodeName(), cNode.getChildren().isEmpty() ? cNode.getValue() : constructMap(cNode)));
return map;
}
/**
* Loads this configuration from the content of the specified map. The data in the map is transformed into a hierarchy
* of {@link ImmutableNode} objects.
*
* @param map the map to be processed
*/
protected void load(final Map<String, Object> map) {
final List<ImmutableNode> roots = constructHierarchy(StringUtils.EMPTY, map, Collections.newSetFromMap(new IdentityHashMap<>()));
if (!roots.isEmpty()) {
getNodeModel().setRootNode(roots.get(0));
}
}
/**
* Parses a collection structure. The elements of the collection are processed recursively.
*
* @param col the collection to be processed.
* @param key the key under which this collection is to be stored.
* @param visited the set of visited objects.
* @return a node representing this collection.
*/
private List<ImmutableNode> parseCollection(final Collection<Object> col, final String key, final Set<Object> visited) {
return col.stream().flatMap(elem -> constructHierarchy(key, elem, visited).stream()).collect(Collectors.toList());
}
/**
* Parses a map structure. The single keys of the map are processed recursively.
*
* @param map the map to be processed.
* @param key the key under which this map is to be stored.
* @param visited the set of visited objects.
* @return a node representing this map
*/
private List<ImmutableNode> parseMap(final Map<String, Object> map, final String key, final Set<Object> visited) {
final ImmutableNode.Builder subtree = new ImmutableNode.Builder().name(key);
map.forEach((k, v) -> constructHierarchy(k, v, visited).forEach(subtree::addChild));
return Collections.singletonList(subtree.create());
}
}