1
14
15 package com.liferay.portal.bean;
16
17 import com.liferay.portal.kernel.bean.BeanLocator;
18 import com.liferay.portal.kernel.bean.BeanLocatorException;
19 import com.liferay.portal.kernel.log.Log;
20 import com.liferay.portal.kernel.log.LogFactoryUtil;
21 import com.liferay.portal.kernel.util.ListUtil;
22
23 import java.lang.reflect.Proxy;
24
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.concurrent.ConcurrentHashMap;
29
30 import org.springframework.context.ApplicationContext;
31
32
37 public class BeanLocatorImpl implements BeanLocator {
38
39 public static final String VELOCITY_SUFFIX = ".velocity";
40
41 public BeanLocatorImpl(
42 ClassLoader classLoader, ApplicationContext applicationContext) {
43
44 _classLoader = classLoader;
45 _applicationContext = applicationContext;
46 }
47
48 public ApplicationContext getApplicationContext() {
49 return _applicationContext;
50 }
51
52 public ClassLoader getClassLoader() {
53 return _classLoader;
54 }
55
56 public Object locate(String name) throws BeanLocatorException {
57 try {
58 return doLocate(name);
59 }
60 catch (Exception e) {
61 throw new BeanLocatorException(e);
62 }
63 }
64
65 protected Object doLocate(String name) throws Exception {
66 if (_log.isDebugEnabled()) {
67 _log.debug("Locating " + name);
68 }
69
70 if (name.endsWith(VELOCITY_SUFFIX)) {
71 Object bean = _velocityBeans.get(name);
72
73 if (bean == null) {
74 String originalName = name.substring(
75 0, name.length() - VELOCITY_SUFFIX.length());
76
77 bean = _applicationContext.getBean(originalName);
78
79 Class<?>[] interfaces = bean.getClass().getInterfaces();
80
81 List<Class<?>> interfacesList = ListUtil.fromArray(interfaces);
82
83 Iterator<Class<?>> itr = interfacesList.iterator();
84
85 while (itr.hasNext()) {
86 Class<?> classObj = itr.next();
87
88 try {
89 _classLoader.loadClass(classObj.getName());
90 }
91 catch (Exception e) {
92 itr.remove();
93 }
94 }
95
96 bean = Proxy.newProxyInstance(
97 _classLoader,
98 interfacesList.toArray(new Class<?>[interfacesList.size()]),
99 new VelocityBeanHandler(bean, _classLoader));
100
101 _velocityBeans.put(name, bean);
102 }
103
104 return bean;
105 }
106 else {
107 return _applicationContext.getBean(name);
108 }
109 }
110
111 private static Log _log = LogFactoryUtil.getLog(BeanLocatorImpl.class);
112
113 private ClassLoader _classLoader;
114 private ApplicationContext _applicationContext;
115 private Map<String, Object> _velocityBeans =
116 new ConcurrentHashMap<String, Object>();
117
118 }