1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.jcs3.jcache.extras.loader;
20
21 import javax.cache.configuration.Factory;
22 import javax.cache.integration.CacheLoader;
23 import javax.cache.integration.CacheLoaderException;
24
25 import org.apache.commons.jcs3.jcache.extras.closeable.Closeables;
26
27 import java.io.Closeable;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashMap;
32 import java.util.Map;
33
34 public class CompositeCacheLoader<K, V> implements CacheLoader<K, V>, Closeable, Factory<CacheLoader<K, V>>
35 {
36 private final CacheLoader<K, V>[] delegates;
37
38 public CompositeCacheLoader(final CacheLoader<K, V>... delegates)
39 {
40 this.delegates = delegates;
41 }
42
43 @Override
44 public V load(final K key) throws CacheLoaderException
45 {
46 for (final CacheLoader<K, V> delegate : delegates)
47 {
48 final V v = delegate.load(key);
49 if (v != null)
50 {
51 return v;
52 }
53 }
54 return null;
55 }
56
57 @Override
58 public Map<K, V> loadAll(final Iterable<? extends K> keys) throws CacheLoaderException
59 {
60 final Collection<K> list = new ArrayList<>();
61 for (final K k : keys)
62 {
63 list.add(k);
64 }
65
66 final Map<K, V> result = new HashMap<>();
67 for (final CacheLoader<K, V> delegate : delegates)
68 {
69 final Map<K, V> v = delegate.loadAll(list);
70 if (v != null)
71 {
72 result.putAll(v);
73 list.removeAll(v.keySet());
74 if (list.isEmpty())
75 {
76 return v;
77 }
78 }
79 }
80
81 return result;
82 }
83
84 @Override
85 public void close() throws IOException
86 {
87 Closeables.close(delegates);
88 }
89
90 @Override
91 public CacheLoader<K, V> create()
92 {
93 return this;
94 }
95 }