01: /*
02: * Created on Nov 23, 2005
03: */
04: package uk.org.ponder.springutil;
05:
06: import java.io.IOException;
07: import java.io.InputStream;
08:
09: import org.springframework.beans.BeansException;
10: import org.springframework.beans.factory.FactoryBean;
11: import org.springframework.context.ApplicationContext;
12: import org.springframework.context.ApplicationContextAware;
13: import org.springframework.core.io.Resource;
14:
15: import uk.org.ponder.reflect.ReflectiveCache;
16: import uk.org.ponder.saxalizer.XMLProvider;
17: import uk.org.ponder.util.Logger;
18: import uk.org.ponder.util.UniversalRuntimeException;
19:
20: /**
21: * A very useful base class for any bean constructed out of an XML
22: * representation. Will provide a default-constructed object of the required
23: * type if the location field is blank or refers to a nonexistent file.
24: *
25: * @author Antranig Basman (antranig@caret.cam.ac.uk)
26: */
27:
28: public class XMLFactoryBean implements FactoryBean,
29: ApplicationContextAware {
30: String location;
31: private ApplicationContext applicationcontext;
32: private XMLProvider xmlprovider;
33: private Class objecttype;
34: protected ReflectiveCache reflectivecache;
35:
36: public void setLocation(String location) {
37: this .location = location;
38: }
39:
40: public void setXMLProvider(XMLProvider xmlprovider) {
41: this .xmlprovider = xmlprovider;
42: }
43:
44: public void setReflectiveCache(ReflectiveCache reflectivecache) {
45: this .reflectivecache = reflectivecache;
46: }
47:
48: public void setObjectType(Class objecttype) {
49: this .objecttype = objecttype;
50: }
51:
52: public Class getObjectType() {
53: return objecttype;
54: }
55:
56: public Object getObject() throws Exception {
57: Object togo = null;
58: if (location != null) {
59: Resource res = applicationcontext.getResource(location);
60: try {
61: InputStream is = res.getInputStream();
62: togo = xmlprovider.readXML(objecttype, is);
63: } catch (Exception e) {
64: UniversalRuntimeException tothrow = UniversalRuntimeException
65: .accumulate(e,
66: "Error loading object from path " + res
67: + ": ");
68: if (tothrow.getTargetException() instanceof IOException) {
69: Logger.log.warn(tothrow.getTargetException()
70: .getClass().getName()
71: + ": " + tothrow.getMessage());
72: togo = reflectivecache.construct(objecttype);
73: } else {
74: throw tothrow;
75: }
76: }
77: } else {
78: togo = reflectivecache.construct(objecttype);
79: }
80: return togo;
81: }
82:
83: public boolean isSingleton() {
84: return true;
85: }
86:
87: public void setApplicationContext(
88: ApplicationContext applicationcontext)
89: throws BeansException {
90: this.applicationcontext = applicationcontext;
91: }
92:
93: }
|