001
014
015 package com.liferay.portal.spring.util;
016
017 import com.liferay.portal.kernel.bean.BeanPropertiesUtil;
018 import com.liferay.portal.kernel.security.pacl.DoPrivileged;
019 import com.liferay.portal.kernel.spring.util.FactoryBean;
020 import com.liferay.portal.kernel.spring.util.SpringFactory;
021 import com.liferay.portal.kernel.spring.util.SpringFactoryException;
022 import com.liferay.portal.kernel.util.InstanceFactory;
023 import com.liferay.portal.kernel.util.SetUtil;
024 import com.liferay.portal.kernel.util.StringUtil;
025 import com.liferay.portal.util.ClassLoaderUtil;
026
027 import java.util.HashMap;
028 import java.util.Map;
029 import java.util.Set;
030
031
034 @DoPrivileged
035 public class SpringFactoryImpl implements SpringFactory {
036
037 @Override
038 public Object newBean(String className) throws SpringFactoryException {
039 return newBean(className, null);
040 }
041
042 @Override
043 public Object newBean(String className, Map<String, Object> properties)
044 throws SpringFactoryException {
045
046 try {
047 return doNewBean(className, properties);
048 }
049 catch (SpringFactoryException se) {
050 throw se;
051 }
052 catch (Exception e) {
053 throw new SpringFactoryException(e);
054 }
055 }
056
057 public void setBeanDefinitions(Map<String, String> beanDefinitions) {
058 _beanDefinitions = new HashMap<String, Set<String>>();
059
060 for (Map.Entry<String, String> entry : beanDefinitions.entrySet()) {
061 String className = entry.getKey();
062
063 Set<String> properties = SetUtil.fromArray(
064 StringUtil.split(entry.getValue()));
065
066 _beanDefinitions.put(className, properties);
067 }
068 }
069
070 protected Object doNewBean(String className, Map<String, Object> properties)
071 throws Exception {
072
073 Set<String> allowedProperties = _beanDefinitions.get(className);
074
075 if (allowedProperties == null) {
076 throw new SpringFactoryException("Undefined class " + className);
077 }
078
079 Object bean = InstanceFactory.newInstance(
080 ClassLoaderUtil.getPortalClassLoader(), className);
081
082 FactoryBean<Object> factoryBean = null;
083
084 if (bean instanceof FactoryBean) {
085 factoryBean = (FactoryBean<Object>)bean;
086
087 bean = factoryBean.create();
088 }
089
090 if (properties != null) {
091 for (Map.Entry<String, Object> entry : properties.entrySet()) {
092 String name = entry.getKey();
093
094 if (!allowedProperties.contains(name)) {
095 throw new SpringFactoryException(
096 "Undefined property " + name + " for class " +
097 className);
098 }
099
100 Object value = entry.getValue();
101
102 BeanPropertiesUtil.setProperty(bean, name, value);
103 }
104 }
105
106 if (factoryBean != null) {
107 bean = factoryBean.postProcessing(bean);
108 }
109
110 return bean;
111 }
112
113 private Map<String, Set<String>> _beanDefinitions;
114
115 }