1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.core.impl.cache;
17
18 import org.apache.log4j.Logger;
19 import org.kuali.rice.core.api.cache.CacheManagerRegistry;
20 import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
21 import org.springframework.beans.factory.NamedBean;
22 import org.springframework.cache.CacheManager;
23
24 import java.lang.reflect.InvocationTargetException;
25 import java.lang.reflect.Method;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.CopyOnWriteArrayList;
31
32
33
34
35 public final class CacheManagerRegistryImpl implements CacheManagerRegistry {
36 private static final String GET_NAME = "getName";
37 private static final Logger LOG = Logger.getLogger(CacheManagerRegistryImpl.class);
38 private static final String GET_NAME_MSG = "unable to get the getName method on the cache manager";
39
40 private static final List<CacheManager> CACHE_MANAGERS = new CopyOnWriteArrayList<CacheManager>();
41 private static final Map<String, CacheManager> CACHE_MANAGER_MAP = new ConcurrentHashMap<String, CacheManager> ();
42
43 public void setCacheManager(CacheManager c) {
44 if (c == null) {
45 throw new IllegalArgumentException("c is null");
46 }
47
48 CACHE_MANAGERS.add(c);
49
50
51 for (String cacheName : c.getCacheNames()) {
52 CACHE_MANAGER_MAP.put(cacheName, c);
53 }
54 }
55
56 @Override
57 public List<CacheManager> getCacheManagers() {
58 return Collections.unmodifiableList(CACHE_MANAGERS);
59 }
60
61 @Override
62 public CacheManager getCacheManager(String name) {
63 for (CacheManager cm : getCacheManagers()) {
64 if (name.equals(getCacheManagerName(cm))) {
65 return cm;
66 }
67 }
68 return null;
69 }
70
71 @Override
72 public String getCacheManagerName(CacheManager cm) {
73 if (cm instanceof NamedBean) {
74 return ((NamedBean) cm).getBeanName();
75 }
76
77 String v = "Unnamed CacheManager " + cm.hashCode();
78 try {
79 final Method nameMethod = cm.getClass().getMethod(GET_NAME, new Class[] {});
80 if (nameMethod != null && nameMethod.getReturnType() == String.class) {
81 v = (String) nameMethod.invoke(cm, new Object[] {});
82 }
83 } catch (NoSuchMethodException e) {
84 LOG.warn(GET_NAME_MSG, e);
85 } catch (InvocationTargetException e) {
86 LOG.warn(GET_NAME_MSG, e);
87 } catch (IllegalAccessException e) {
88 LOG.warn(GET_NAME_MSG, e);
89 }
90
91 return v;
92 }
93
94 @Override
95 public CacheManager getCacheManagerByCacheName(String cacheName) {
96 CacheManager cm = CACHE_MANAGER_MAP.get(cacheName);
97 if (cm != null) {
98 return cm;
99 }
100 throw new RiceIllegalArgumentException("Cache not found : " + cacheName);
101 }
102 }