1 16 package org.apache.commons.jelly.impl; 17 18 import java.util.HashSet ; 19 import java.util.Iterator ; 20 import java.util.Map ; 21 import java.util.Set ; 22 23 import org.apache.commons.beanutils.DynaClass; 24 import org.apache.commons.jelly.DynaBeanTagSupport; 25 import org.apache.commons.jelly.JellyTagException; 26 import org.apache.commons.jelly.MissingAttributeException; 27 import org.apache.commons.jelly.XMLOutput; 28 import org.apache.commons.jelly.expression.Expression; 29 30 38 public class DynamicDynaBeanTag extends DynaBeanTagSupport implements BeanSource { 39 40 41 private DynaClass beanClass; 42 43 47 private String variableNameAttribute; 48 49 50 private String var; 51 52 53 private Set setAttributesSet = new HashSet (); 54 55 56 private Map attributes; 57 58 public DynamicDynaBeanTag(DynaClass beanClass, Map attributes, String variableNameAttribute) { 59 this.beanClass = beanClass; 60 this.attributes = attributes; 61 this.variableNameAttribute = variableNameAttribute; 62 } 63 64 public void beforeSetAttributes() throws JellyTagException { 65 try { 67 setDynaBean( beanClass.newInstance() ); 68 } catch (IllegalAccessException e) { 69 throw new JellyTagException("Could not instantiate dynabean",e); 70 } catch (InstantiationException e) { 71 throw new JellyTagException("Could not instantiate dynabean",e); 72 } 73 74 setAttributesSet.clear(); 75 } 76 77 public void setAttribute(String name, Object value) throws JellyTagException { 78 boolean isVariableName = false; 79 if (variableNameAttribute != null ) { 80 if ( variableNameAttribute.equals( name ) ) { 81 if (value == null) { 82 var = null; 83 } 84 else { 85 var = value.toString(); 86 } 87 isVariableName = true; 88 } 89 } 90 if (! isVariableName) { 91 92 setAttributesSet.add(name); 96 97 99 super.setAttribute(name, value); 100 } 101 } 102 103 public void doTag(XMLOutput output) throws JellyTagException { 106 107 for ( Iterator iter = attributes.values().iterator(); iter.hasNext(); ) { 109 Attribute attribute = (Attribute) iter.next(); 110 String name = attribute.getName(); 111 if ( ! setAttributesSet.contains( name ) ) { 112 if ( attribute.isRequired() ) { 113 throw new MissingAttributeException(name); 114 } 115 Object value = null; 117 Expression expression = attribute.getDefaultValue(); 118 if ( expression != null ) { 119 value = expression.evaluate(context); 120 } 121 122 if ( value != null ) { 124 super.setAttribute(name, value); 125 } 126 } 127 } 128 129 invokeBody(output); 130 131 if ( var != null ) { 133 context.setVariable(var, getDynaBean()); 134 } 135 } 136 137 142 public Object getBean() { 143 return getDynaBean(); 144 } 145 } 146 | Popular Tags |