Skip to content

Instantly share code, notes, and snippets.

@vshank77
Created August 28, 2014 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vshank77/fbe6706f5b9865cfd632 to your computer and use it in GitHub Desktop.
Save vshank77/fbe6706f5b9865cfd632 to your computer and use it in GitHub Desktop.
Map Objects
package igloo.viper.api;
import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import java.util.Collections;
import java.util.Map;
@RequiredArgsConstructor
public final class MapContext {
private final Map<String, String> internalContext;
public static final MapContext EMPTY = new MapContext(Collections.<String, String>emptyMap());
public static final MapContext from(String key, String value) {
return new MapContext(ImmutableMap.<String, String>builder().put(key, value).build());
}
public String get(String key) {
return internalContext.get(key);
}
}
package igloo.viper.api;
import lombok.RequiredArgsConstructor;
import snowflake.cuttlefish.util.ReflectUtil;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.google.common.base.Preconditions.checkState;
@RequiredArgsConstructor
public final class MappedObject<T> {
private final Class<T> tClass;
private final ConcurrentMap<String, T> sourceMap = new ConcurrentHashMap<>();
public T getStrict(String key) {
checkState(sourceMap.containsKey(key), "unable to find key " + key);
return sourceMap.get(key);
}
public T getSafe(String key, T defValue) {
return sourceMap.containsKey(key) ? sourceMap.get(key) : defValue;
}
@SuppressWarnings("unchecked")
public T getOrCreate(String key) {
if (!sourceMap.containsKey(key))
sourceMap.putIfAbsent(key, (T) ReflectUtil.create(tClass));
return sourceMap.get(key);
}
public int size() {
return sourceMap.size();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment