Cache implements Indexer<T> { @Override public void addIndexers(Map<String, Function<T, List<String>>> indexersNew) { if (!items.isEmpty()) { throw new IllegalStateException("Cannot add indexers to a Cache which is not empty"); } Set<String> intersection = new HashSet<>(indexers.keySet()); intersection.retainAll(indexersNew.keySet()); if (!intersection.isEmpty()) { throw new IllegalArgumentException("Indexer conflict: " + intersection); } for (Map.Entry<String, Function<T, List<String>>> indexEntry : indexersNew.entrySet()) { addIndexFunc(indexEntry.getKey(), indexEntry.getValue()); } } Cache();  Cache(String indexName, Function<T, List<String>> indexFunc, Function<T, String> keyFunc); @Override synchronized void add(T obj); @Override Map<String, Function<T, List<String>>> getIndexers(); @Override void addIndexers(Map<String, Function<T, List<String>>> indexersNew); @Override synchronized void update(T obj); @Override synchronized void delete(T obj); @Override synchronized void replace(List<T> list, String resourceVersion); @Override void resync(); @Override synchronized List<String> listKeys(); @Override synchronized T get(T obj); @Override synchronized List<T> list(); @Override synchronized T getByKey(String key); @Override synchronized List<T> index(String indexName, Object obj); @Override synchronized List<String> indexKeys(String indexName, String indexKey); @Override synchronized List<T> byIndex(String indexName, String indexKey); @Override void isPopulated(boolean isPopulated); void updateIndices(T oldObj, T newObj, String key); void addIndexFunc(String indexName, Function<T, List<String>> indexFunc); static String deletionHandlingMetaNamespaceKeyFunc(T object); static String metaNamespaceKeyFunc(Object obj); static List<String> metaNamespaceIndexFunc(Object obj); static final String NAMESPACE_INDEX; }
@Test void testAddIndexers() { Cache<Pod> podCache = new Cache<>(); String nodeIndex = "node-index"; String clusterIndex = "cluster-index"; Map<String, Function<Pod, List<String>>> indexers = new HashMap<>(); indexers.put(nodeIndex, (Pod pod) -> Arrays.asList(pod.getSpec().getNodeName())); indexers.put(clusterIndex, (Pod pod) -> Arrays.asList(pod.getMetadata().getClusterName())); podCache.addIndexers(indexers); Pod testPod = new PodBuilder() .withNewMetadata().withNamespace("test").withName("test-pod").withClusterName("test-cluster").endMetadata() .withNewSpec().withNodeName("test-node").endSpec() .build(); podCache.add(testPod); List<Pod> namespaceIndexedPods = podCache.byIndex(Cache.NAMESPACE_INDEX, "test"); assertEquals(1, namespaceIndexedPods.size()); List<Pod> nodeNameIndexedPods = podCache.byIndex(nodeIndex, "test-node"); assertEquals(1, nodeNameIndexedPods.size()); List<Pod> clusterNameIndexedPods = podCache.byIndex(clusterIndex, "test-cluster"); assertEquals(1, clusterNameIndexedPods.size()); }