001
014
015 package com.liferay.portal.bean;
016
017 import com.liferay.portal.kernel.bean.BeanLocator;
018 import com.liferay.portal.kernel.bean.BeanLocatorException;
019 import com.liferay.portal.kernel.log.Log;
020 import com.liferay.portal.kernel.log.LogFactoryUtil;
021 import com.liferay.portal.kernel.util.ProxyUtil;
022
023 import java.util.ArrayList;
024 import java.util.List;
025 import java.util.Map;
026 import java.util.concurrent.ConcurrentHashMap;
027
028 import org.springframework.context.ApplicationContext;
029
030
033 public class BeanLocatorImpl implements BeanLocator {
034
035 public static final String VELOCITY_SUFFIX = ".velocity";
036
037 public BeanLocatorImpl(
038 ClassLoader classLoader, ApplicationContext applicationContext) {
039
040 _classLoader = classLoader;
041 _applicationContext = applicationContext;
042 }
043
044 public ApplicationContext getApplicationContext() {
045 return _applicationContext;
046 }
047
048 public ClassLoader getClassLoader() {
049 return _classLoader;
050 }
051
052 public String[] getNames() {
053 return _applicationContext.getBeanDefinitionNames();
054 }
055
056 public Class<?> getType(String name) {
057 try {
058 return _applicationContext.getType(name);
059 }
060 catch (Exception e) {
061 throw new BeanLocatorException(e);
062 }
063 }
064
065 public Object locate(String name) throws BeanLocatorException {
066 try {
067 return doLocate(name);
068 }
069 catch (Exception e) {
070 throw new BeanLocatorException(e);
071 }
072 }
073
074 protected Object doLocate(String name) throws Exception {
075 if (_log.isDebugEnabled()) {
076 _log.debug("Locating " + name);
077 }
078
079 if (name.endsWith(VELOCITY_SUFFIX)) {
080 Object bean = _velocityBeans.get(name);
081
082 if (bean == null) {
083 String originalName = name.substring(
084 0, name.length() - VELOCITY_SUFFIX.length());
085
086 bean = _applicationContext.getBean(originalName);
087
088 Class<?> beanClass = bean.getClass();
089
090 Class<?>[] interfaces = beanClass.getInterfaces();
091
092 List<Class<?>> interfacesList = new ArrayList<Class<?>>();
093
094 for (Class<?> clazz : interfaces) {
095 try {
096 interfacesList.add(
097 _classLoader.loadClass(clazz.getName()));
098 }
099 catch (ClassNotFoundException cnfe) {
100 }
101 }
102
103 bean = ProxyUtil.newProxyInstance(
104 _classLoader,
105 interfacesList.toArray(new Class<?>[interfacesList.size()]),
106 new VelocityBeanHandler(bean, _classLoader));
107
108 _velocityBeans.put(name, bean);
109 }
110
111 return bean;
112 }
113 else {
114 return _applicationContext.getBean(name);
115 }
116 }
117
118 private static Log _log = LogFactoryUtil.getLog(BeanLocatorImpl.class);
119
120 private ApplicationContext _applicationContext;
121 private ClassLoader _classLoader;
122 private Map<String, Object> _velocityBeans =
123 new ConcurrentHashMap<String, Object>();
124
125 }