
com.hubspot.jinjava.util.ScopeMap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jinjava Show documentation
Show all versions of jinjava Show documentation
Jinja templating engine implemented in Java
package com.hubspot.jinjava.util;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ScopeMap implements Map {
private final Map scope;
private final ScopeMap parent;
public ScopeMap() {
this(null);
}
public ScopeMap(ScopeMap parent) {
this.scope = new HashMap();
this.parent = parent;
}
public ScopeMap(ScopeMap parent, Map scope) {
this(parent);
this.scope.putAll(scope);
}
public ScopeMap getParent() {
return parent;
}
public Map getScope() {
return scope;
}
@Override
public int size() {
return keySet().size();
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsKey(Object key) {
return get(key) != null;
}
@Override
public boolean containsValue(Object value) {
if (scope.containsValue(value)) {
return true;
}
if (parent != null) {
return parent.containsValue(value);
}
return false;
}
public V get(Object key, V defVal) {
V val = get(key);
if (val != null) {
return val;
}
return defVal;
}
@Override
public V get(Object key) {
V val = scope.get(key);
if (val != null) {
return val;
}
if (parent != null) {
return parent.get(key);
}
return null;
}
@Override
public V put(K key, V value) {
return scope.put(key, value);
}
@Override
public V remove(Object key) {
return scope.remove(key);
}
@Override
public void putAll(Map extends K, ? extends V> m) {
scope.putAll(m);
}
@Override
public void clear() {
scope.clear();
}
@Override
public Set keySet() {
Set keys = new HashSet<>();
if (parent != null) {
keys.addAll(parent.keySet());
}
keys.addAll(scope.keySet());
return keys;
}
@Override
public Collection values() {
Set> entrySet = entrySet();
Collection values = new ArrayList<>(entrySet.size());
for (Map.Entry entry : entrySet) {
values.add(entry.getValue());
}
return values;
}
@Override
@SuppressFBWarnings(
justification = "using overridden get() to do scoped retrieve with parent fallback",
value = "WMI_WRONG_MAP_ITERATOR"
)
public Set> entrySet() {
Set> entries = new HashSet<>();
for (K key : keySet()) {
entries.add(new ScopeMapEntry(key, get(key), this));
}
return entries;
}
public static class ScopeMapEntry implements Map.Entry {
private final Map map;
private final K key;
private V value;
public ScopeMapEntry(K key, V value, Map map) {
this.key = key;
this.value = value;
this.map = map;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V old = value;
this.value = value;
map.put(key, value);
return old;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy