com.xboxng.config.ReferenceResolver Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of XNConfig Show documentation
Show all versions of XNConfig Show documentation
A Java library that manages configurations for multiple environments
/*
* Copyright Qiang Yu (qiangyu #### gmail.com)
*
* Licensed 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
*
* http://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 com.xboxng.config;
import com.xboxng.config.exception.XNConfigException;
import com.xboxng.config.tree.ConfigList;
import com.xboxng.config.tree.ConfigMap;
import com.xboxng.config.tree.Reference;
import com.xboxng.config.tree.Resolvable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ReferenceResolver {
private XNConfig config;
public ReferenceResolver(XNConfig config) {
this.config = config;
}
protected Object resolve(Object value, Set pendingReference) {
if (value instanceof Reference) {
if (pendingReference.contains(value)) {
throw new XNConfigException("cyclic references found: " + ((Reference) value).getName());
}
pendingReference.add((Reference) value);
Object v = config.getValue(((Reference) value).getName(), pendingReference);
v = resolve(v, pendingReference);
pendingReference.remove(v);
return v;
} else if (value instanceof ConfigMap)
return resolveMap((ConfigMap) value, pendingReference);
else if (value instanceof ConfigList)
return resolveList((ConfigList) value, pendingReference);
else
return value;
}
private Map resolveMap(ConfigMap map, Set pendingReference) {
Map references = map.getReferences();
Map elements = map.getElements();
for (Map.Entry entry : references.entrySet()) {
String key = entry.getKey();
if (elements.get(key) == entry.getValue()) {
elements.put(key, resolve(entry.getValue(), pendingReference));
}
}
// all references have been resolved
references.clear();
return Collections.unmodifiableMap(elements);
}
private List resolveList(ConfigList list, Set pendingReference) {
Map references = list.getReferences();
List