Created
August 28, 2014 10:52
-
-
Save vshank77/fbe6706f5b9865cfd632 to your computer and use it in GitHub Desktop.
Map Objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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