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