1 package org.ejen; 22 23 import java.util.Properties ; 24 import javax.xml.transform.dom.DOMSource ; 25 import javax.xml.transform.dom.DOMResult ; 26 import org.w3c.dom.Document ; 27 import org.w3c.dom.Node ; 28 import org.w3c.dom.NodeList ; 29 import org.apache.xpath.XPathAPI; 30 import org.apache.xalan.transformer.TransformerImpl; 31 32 71 public class EjenFilterNode extends EjenStylesheetNode { 72 protected String _foreach = null; 73 74 78 public String nodeName() { 79 return "filter"; 80 } 81 82 86 public Properties getAttributes() { 87 Properties attrs = super.getAttributes(); 88 89 if (_foreach != null) { 90 attrs.setProperty("foreach", _foreach); 91 } 92 return attrs; 93 } 94 95 143 public void setForeach(String foreach) { 144 _foreach = foreach; 145 } 146 147 151 public void process() { 152 super.process(); 153 TransformerImpl ti = null; 154 DOMSource src = null; 155 156 try { 157 ti = (TransformerImpl) (getFromContext(CTX_TRANSFORMER_IMPL)); 158 src = (DOMSource ) (getFromGlobalContext(CTX_DOM_SOURCE)); 159 } catch (Exception e) { 160 throw new EjenException(this, null, e); 161 } 162 if (ti == null) { 163 throw new EjenException(this, 164 "no '" + CTX_TRANSFORMER_IMPL + "' in context"); 165 } 166 if (src == null) { 167 throw new EjenException(this, 168 "no '" + CTX_DOM_SOURCE + "' in global context"); 169 } 170 if (_foreach != null) { 171 NodeList nl = null; 172 173 try { 174 ti.setParameter("root", src.getNode()); 175 nl = XPathAPI.selectNodeList(src.getNode(), 176 evaluateAVT(ti, _foreach)); 177 } catch (Exception e) { 178 throw new EjenException(this, 179 "invalid 'foreach' attribute: " + _foreach, e); 180 } 181 try { 182 Document doc = (Document ) (src.getNode()); 183 184 for (int i = 0; i < nl.getLength(); i++) { 185 Node parent = nl.item(i).getParentNode(); 186 187 if (parent == null) { 188 throw new EjenException(this, 189 "Invalid 'foreach' attribute:" + _foreach 190 + " (node " + i + " has no parent)"); 191 } 192 DOMResult res = new DOMResult (); 193 194 ti.transform(new DOMSource (nl.item(i)), res); 195 Node root = doc.importNode(((Document ) (res.getNode())).getDocumentElement(), 196 true); 197 198 parent.replaceChild(root, nl.item(i)); 199 } 200 } catch (EjenException e) { 201 throw e; 202 } catch (Exception e) { 203 throw new EjenException(this, null, e); 204 } 205 } else { 206 DOMResult res = new DOMResult (); 207 208 try { 209 ti.transform(src, res); 210 putInGlobalContext(CTX_DOM_SOURCE, new DOMSource (res.getNode())); 211 } catch (Exception e) { 212 throw new EjenException(this, null, e); 213 } 214 } 215 } 216 } 217 | Popular Tags |