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 if (bean instanceof FactoryBean) {
083 FactoryBean<Object> factoryBean = (FactoryBean<Object>)bean;
084
085 bean = factoryBean.create();
086 }
087
088 if (properties == null) {
089 return bean;
090 }
091
092 for (Map.Entry<String, Object> entry : properties.entrySet()) {
093 String name = entry.getKey();
094
095 if (!allowedProperties.contains(name)) {
096 throw new SpringFactoryException(
097 "Undefined property " + name + " for class " +
098 className);
099 }
100
101 Object value = entry.getValue();
102
103 BeanPropertiesUtil.setProperty(bean, name, value);
104 }
105
106 return bean;
107 }
108
109 private Map<String, Set<String>> _beanDefinitions;
110
111 }