]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.core/src/main/java/org/argeo/slc/ant/spring/AbstractSpringArg.java
Simplify TreeSPath
[gpl/argeo-slc.git] / org.argeo.slc.core / src / main / java / org / argeo / slc / ant / spring / AbstractSpringArg.java
1 package org.argeo.slc.ant.spring;
2
3 import java.util.List;
4 import java.util.Vector;
5
6 import org.springframework.beans.BeanWrapper;
7 import org.springframework.beans.BeanWrapperImpl;
8 import org.springframework.beans.factory.InitializingBean;
9 import org.springframework.context.ApplicationContext;
10
11 import org.apache.commons.logging.LogFactory;
12 import org.apache.tools.ant.types.DataType;
13
14 import org.argeo.slc.ant.SlcAntException;
15 import org.argeo.slc.ant.SlcProjectHelper;
16 import org.argeo.slc.core.SlcException;
17
18 /** Abstract Ant type wrapping a Spring bean. */
19 public abstract class AbstractSpringArg extends DataType {
20 private List<OverrideArg> overrides = new Vector<OverrideArg>();
21
22 private String bean;
23
24 // cache bean instance to avoid reading it twice if it is a prototype
25 private Object beanInstance = null;
26
27 /** The <u>name</u> of the underlying bean, as set throught the attribute. */
28 public String getBean() {
29 return bean;
30 }
31
32 /** Setter for the bean name. */
33 public void setBean(String bean) {
34 this.bean = bean;
35 }
36
37 /**
38 * Retrieve the instance of the bean, and sets the overriden properties.
39 * <b>The value is cached.</b>
40 */
41 public Object getBeanInstance() {
42 if (beanInstance == null) {
43 beanInstance = getContext().getBean(bean);
44
45 setOverridenProperties(beanInstance);
46
47 if (beanInstance instanceof InitializingBean) {
48 try {
49 ((InitializingBean) beanInstance).afterPropertiesSet();
50 } catch (Exception e) {
51 throw new SlcException("Could not initialize bean", e);
52 }
53 }
54 }
55 return beanInstance;
56 }
57
58 protected void setOverridenProperties(Object obj){
59 BeanWrapper wrapper = new BeanWrapperImpl(obj);
60 for (OverrideArg override : overrides) {
61 if (override.getName() == null) {
62 throw new SlcAntException(
63 "The name of the property to override has to be set.");
64 }
65
66 // LogFactory.getLog(getClass()).debug(
67 // "Prop " + override.getName());
68 wrapper.setPropertyValue(override.getName(), override
69 .getObject());
70 }
71
72 }
73
74 /** Creates an override subtag. */
75 public OverrideArg createOverride() {
76 OverrideArg propertyArg = new OverrideArg();
77 overrides.add(propertyArg);
78 return propertyArg;
79 }
80
81 /** The related Spring application context. */
82 protected ApplicationContext getContext() {
83 return (ApplicationContext) getProject().getReference(
84 SlcProjectHelper.REF_ROOT_CONTEXT);
85 }
86
87 }