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 public Object newBean(String className) throws SpringFactoryException {
038 return newBean(className, null);
039 }
040
041 public Object newBean(String className, Map<String, Object> properties)
042 throws SpringFactoryException {
043
044 try {
045 return doNewBean(className, properties);
046 }
047 catch (SpringFactoryException se) {
048 throw se;
049 }
050 catch (Exception e) {
051 throw new SpringFactoryException(e);
052 }
053 }
054
055 public void setBeanDefinitions(Map<String, String> beanDefinitions) {
056 _beanDefinitions = new HashMap<String, Set<String>>();
057
058 for (Map.Entry<String, String> entry : beanDefinitions.entrySet()) {
059 String className = entry.getKey();
060
061 Set<String> properties = SetUtil.fromArray(
062 StringUtil.split(entry.getValue()));
063
064 _beanDefinitions.put(className, properties);
065 }
066 }
067
068 protected Object doNewBean(String className, Map<String, Object> properties)
069 throws Exception {
070
071 Set<String> allowedProperties = _beanDefinitions.get(className);
072
073 if (allowedProperties == null) {
074 throw new SpringFactoryException("Undefined class " + className);
075 }
076
077 Object bean = InstanceFactory.newInstance(
078 ClassLoaderUtil.getPortalClassLoader(), className);
079
080 if (bean instanceof FactoryBean) {
081 FactoryBean<Object> factoryBean = (FactoryBean<Object>)bean;
082
083 bean = factoryBean.create();
084 }
085
086 if (properties == null) {
087 return bean;
088 }
089
090 for (Map.Entry<String, Object> entry : properties.entrySet()) {
091 String name = entry.getKey();
092
093 if (!allowedProperties.contains(name)) {
094 throw new SpringFactoryException(
095 "Undefined property " + name + " for class " +
096 className);
097 }
098
099 Object value = entry.getValue();
100
101 BeanPropertiesUtil.setProperty(bean, name, value);
102 }
103
104 return bean;
105 }
106
107 private Map<String, Set<String>> _beanDefinitions;
108
109 }