1 16 package org.apache.cocoon.generation; 17 18 import org.apache.avalon.framework.parameters.Parameters; 19 import org.apache.cocoon.ProcessingException; 20 import org.apache.cocoon.environment.ObjectModelHelper; 21 import org.apache.cocoon.environment.Request; 22 import org.apache.cocoon.environment.Session; 23 import org.apache.cocoon.environment.SourceResolver; 24 import org.apache.cocoon.xml.XMLUtils; 25 import org.apache.cocoon.xml.IncludeXMLConsumer; 26 import org.apache.excalibur.xml.sax.XMLizable; 27 import org.w3c.dom.Node ; 28 import org.xml.sax.SAXException ; 29 30 import java.io.IOException ; 31 import java.util.Map ; 32 33 77 public class SessionAttributeGenerator extends AbstractGenerator { 78 79 public static final String ATTR_NAME = "attr-name"; 80 public static final String ELEMENT_NAME = "root-element"; 81 82 83 private Object attrObject; 84 85 86 private String elementName; 87 88 91 public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) 92 throws ProcessingException, SAXException , IOException { 93 94 super.setup(resolver, objectModel, src, par); 95 96 this.elementName = par.getParameter(ELEMENT_NAME, null); 98 99 String attrName = par.getParameter(ATTR_NAME, src); 101 if (attrName == null) { 102 String msg = "SessionAttributeGenerator needs an attribute name !"; 103 getLogger().error(msg); 104 throw new ProcessingException(msg); 105 } 106 107 Request request = ObjectModelHelper.getRequest(objectModel); 109 Session session = request.getSession(false); 110 if (session != null) { 111 this.attrObject = session.getAttribute(attrName); 112 } 113 114 if (this.attrObject == null) { 116 if (this.elementName == null) { 117 String msg = "Session attribute '" + attrName + "' doesn't exist"; 119 getLogger().error(msg); 120 throw new ProcessingException(msg); 121 } else { 122 if (getLogger().isDebugEnabled()) { 123 getLogger().debug("Session attribute '" + attrName + 124 "' doesn't exist : will generate a single '" + this.elementName + 125 "' element."); 126 } 127 } 128 } else { 129 if (this.elementName == null && 131 ! (this.attrObject instanceof XMLizable) && 132 ! (this.attrObject instanceof Node )) { 133 134 String msg = "Session attribute '" + attrName + "' needs an enclosing element : class is " + 135 this.attrObject.getClass().getName(); 136 137 getLogger().warn(msg); 138 throw new ProcessingException(msg); 139 } 140 } 141 } 142 143 146 public void generate() 147 throws IOException , SAXException , ProcessingException { 148 xmlConsumer.startDocument(); 149 150 if (this.elementName != null) { 151 xmlConsumer.startElement("", this.elementName, this.elementName, XMLUtils.EMPTY_ATTRIBUTES); 152 XMLUtils.valueOf(new IncludeXMLConsumer(xmlConsumer), this.attrObject); 153 xmlConsumer.endElement("", this.elementName, this.elementName); 154 } else { 155 XMLUtils.valueOf(new IncludeXMLConsumer(xmlConsumer), this.attrObject); 156 } 157 158 xmlConsumer.endDocument(); 159 } 160 } 161 | Popular Tags |