1 9 package org.nanocontainer.script.xml; 10 11 import org.picocontainer.ComponentAdapter; 12 import org.picocontainer.Parameter; 13 import org.picocontainer.PicoContainer; 14 import org.picocontainer.defaults.BeanPropertyComponentAdapter; 15 import org.picocontainer.defaults.ComponentAdapterFactory; 16 import org.picocontainer.defaults.DefaultComponentAdapterFactory; 17 import org.w3c.dom.Element ; 18 import org.w3c.dom.Node ; 19 import org.w3c.dom.NodeList ; 20 21 import java.net.MalformedURLException ; 22 import java.util.Properties ; 23 24 32 public class BeanComponentInstanceFactory implements XMLComponentInstanceFactory { 33 34 private static final String NAME_ATTRIBUTE = "name"; 35 36 public Object makeInstance(PicoContainer pico, Element element, ClassLoader classLoader) throws ClassNotFoundException , MalformedURLException { 37 String className = element.getNodeName(); 38 Object instance = null; 39 40 if (element.getChildNodes().getLength() == 1) { 41 instance = BeanPropertyComponentAdapter.convert(className, element.getFirstChild().getNodeValue(), classLoader); 42 } else { 43 BeanPropertyComponentAdapter propertyComponentAdapter = 44 new BeanPropertyComponentAdapter(createComponentAdapter(className, classLoader)); 45 Properties properties = createProperties(element.getChildNodes()); 46 propertyComponentAdapter.setProperties(properties); 47 instance = propertyComponentAdapter.getComponentInstance(pico); 48 } 49 return instance; 50 } 51 52 private ComponentAdapter createComponentAdapter(String className, ClassLoader classLoader) throws ClassNotFoundException { 53 Class implementation = classLoader.loadClass(className); 54 ComponentAdapterFactory factory = new DefaultComponentAdapterFactory(); 55 return factory.createComponentAdapter(className, implementation, new Parameter[]{}); 56 } 57 58 private Properties createProperties(NodeList nodes) { 59 Properties properties = new Properties (); 60 for (int i = 0; i < nodes.getLength(); i++) { 61 Node n = nodes.item(i); 62 if (n.getNodeType() == Node.ELEMENT_NODE) { 63 String name = n.getNodeName(); 64 65 if (n.hasAttributes()) { 67 String mappedName = n.getAttributes().getNamedItem(NAME_ATTRIBUTE).getNodeValue(); 68 if (mappedName != null) { 69 name = mappedName; 70 } 71 } 72 73 String value = n.getFirstChild().getNodeValue(); 74 properties.setProperty(name, value); 75 } 76 } 77 return properties; 78 } 79 } 80 | Popular Tags |