/* * Copyright 2015 Jesse Morgan */ package com.p4square.grow.provider; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.HashMap; /** * In-memory CollectionProvider implementation, useful for tests. * * @author Jesse Morgan */ public class MapCollectionProvider implements CollectionProvider { private final Map> mMap; public MapCollectionProvider() { mMap = new HashMap<>(); } @Override public synchronized V get(C collection, K key) throws IOException { Map map = mMap.get(collection); if (map != null) { return map.get(key); } return null; } @Override public synchronized Map query(C collection) throws IOException { Map map = mMap.get(collection); if (map == null) { map = new HashMap(); } return map; } @Override public synchronized Map query(C collection, int limit) throws IOException { Map map = query(collection); if (map.size() > limit) { Map smallMap = new HashMap<>(); Iterator> iterator = map.entrySet().iterator(); for (int i = 0; i < limit; i++) { Map.Entry entry = iterator.next(); smallMap.put(entry.getKey(), entry.getValue()); } return smallMap; } else { return map; } } @Override public synchronized void put(C collection, K key, V obj) throws IOException { Map map = mMap.get(collection); if (map == null) { map = new HashMap(); mMap.put(collection, map); } map.put(key, obj); } }