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