KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freemarker > ext > dom > ElementModel


1 /*
2  * Copyright (c) 2003 The Visigoth Software Society. All rights
3  * reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in
14  * the documentation and/or other materials provided with the
15  * distribution.
16  *
17  * 3. The end-user documentation included with the redistribution, if
18  * any, must include the following acknowledgement:
19  * "This product includes software developed by the
20  * Visigoth Software Society (http://www.visigoths.org/)."
21  * Alternately, this acknowledgement may appear in the software itself,
22  * if and wherever such third-party acknowledgements normally appear.
23  *
24  * 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
25  * project contributors may be used to endorse or promote products derived
26  * from this software without prior written permission. For written
27  * permission, please contact visigoths@visigoths.org.
28  *
29  * 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
30  * nor may "FreeMarker" or "Visigoth" appear in their names
31  * without prior written permission of the Visigoth Software Society.
32  *
33  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
34  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
36  * DISCLAIMED. IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR
37  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
38  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
39  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
40  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
41  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
42  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
43  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44  * SUCH DAMAGE.
45  * ====================================================================
46  *
47  * This software consists of voluntary contributions made by many
48  * individuals on behalf of the Visigoth Software Society. For more
49  * information on the Visigoth Software Society, please see
50  * http://www.visigoths.org/
51  */

52  
53 package freemarker.ext.dom;
54
55 import org.w3c.dom.*;
56 import freemarker.template.*;
57 import freemarker.template.utility.StringUtil;
58 import freemarker.core.Environment;
59
60 class ElementModel extends NodeModel implements TemplateScalarModel {
61     
62     public ElementModel(Element element) {
63         super(element);
64     }
65     
66     public boolean isEmpty() {
67         return false;
68     }
69     
70     /**
71      * An Element node supports various hash keys.
72      * Any key that corresponds to the tag name of any child elements
73      * returns a sequence of those elements. The special key "*" returns
74      * all the element's direct children.
75      * The "**" key return all the element's descendants in the order they
76      * occur in the document.
77      * Any key starting with '@' is taken to be the name of an element attribute.
78      * The special key "@@" returns a hash of all the element's attributes.
79      * The special key "/" returns the root document node associated with this element.
80      */

81     public TemplateModel get(String JavaDoc key) throws TemplateModelException {
82         if (key.equals("*")) {
83             NodeListModel ns = new NodeListModel(this);
84             TemplateSequenceModel children = getChildNodes();
85             for (int i=0;i < children.size();i++) {
86                 NodeModel child = (NodeModel) children.get(i);
87                 if (child.node.getNodeType() == Node.ELEMENT_NODE) {
88                     ns.add(child);
89                 }
90             }
91             return ns;
92         }
93         if (key.equals("**")) {
94             Element elem = (Element) node;
95             return new NodeListModel(elem.getElementsByTagName("*"), this);
96         }
97         if (key.startsWith("@")) {
98             if (key.equals("@@") || key.equals("@*")) {
99                 return new NodeListModel(node.getAttributes(), this);
100             }
101             if (key.equals("@@start_tag")) {
102                 NodeOutputter nodeOutputter = new NodeOutputter(node);
103                 return new SimpleScalar(nodeOutputter.getOpeningTag((Element) node));
104             }
105             if (key.equals("@@end_tag")) {
106                 NodeOutputter nodeOutputter = new NodeOutputter(node);
107                 return new SimpleScalar(nodeOutputter.getClosingTag((Element) node));
108             }
109             if (key.equals("@@attributes_markup")) {
110                 StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
111                 NodeOutputter nu = new NodeOutputter(node);
112                 nu.outputContent(node.getAttributes(), buf);
113                 return new SimpleScalar(buf.toString().trim());
114             }
115             if (StringUtil.isXMLID(key.substring(1))) {
116                 Attr att = getAttribute(key.substring(1), Environment.getCurrentEnvironment());
117                 if (att == null) {
118                     return new NodeListModel(this);
119                 }
120                 return wrap(att);
121             }
122         }
123         if (StringUtil.isXMLID(key)) {
124             NodeListModel result = ((NodeListModel) getChildNodes()).filterByName(key);
125             if (result.size() == 1) {
126                 return result.get(0);
127             }
128             return result;
129         }
130         return super.get(key);
131     }
132
133     public String JavaDoc getAsString() throws TemplateModelException {
134         NodeList nl = node.getChildNodes();
135         String JavaDoc result = "";
136         for (int i = 0; i<nl.getLength(); i++) {
137             Node child = nl.item(i);
138             int nodeType = child.getNodeType();
139             if (nodeType == Node.ELEMENT_NODE) {
140                 String JavaDoc msg = "Only elements with no child elements can be processed as text."
141                              + "\nThis element with name \""
142                              + node.getNodeName()
143                              + "\" has a child element named: " + child.getNodeName();
144                 throw new TemplateModelException(msg);
145             }
146             else if (nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) {
147                 result += child.getNodeValue();
148             }
149         }
150         return result;
151     }
152     
153     public String JavaDoc getNodeName() {
154         String JavaDoc result = node.getLocalName();
155         if (result == null || result.equals("")) {
156             result = node.getNodeName();
157         }
158         return result;
159     }
160     
161     String JavaDoc getQualifiedName() {
162         String JavaDoc nodeName = getNodeName();
163         String JavaDoc nsURI = getNodeNamespace();
164         if (nsURI == null || nsURI.length() == 0) {
165             return nodeName;
166         }
167         Environment env = Environment.getCurrentEnvironment();
168         String JavaDoc defaultNS = env.getDefaultNS();
169         String JavaDoc prefix;
170         if (defaultNS != null && defaultNS.equals(nsURI)) {
171             prefix = Template.DEFAULT_NAMESPACE_PREFIX;
172         } else {
173             prefix = env.getPrefixForNamespace(nsURI);
174             
175         }
176         if (prefix == null) {
177             return null; // We have no qualified name, because there is no prefix mapping
178
}
179         if (prefix.length() >0) {
180             prefix += ":";
181         }
182         return prefix + nodeName;
183     }
184     
185     private Attr getAttribute(String JavaDoc qname, Environment env) {
186         Element element = (Element) node;
187         Attr result = element.getAttributeNode(qname);
188         if (result != null)
189             return result;
190         int colonIndex = qname.indexOf(':');
191         if (colonIndex >0) {
192             String JavaDoc prefix = qname.substring(0, colonIndex);
193             String JavaDoc uri;
194             if (prefix.equals(Template.DEFAULT_NAMESPACE_PREFIX)) {
195                 uri = Environment.getCurrentEnvironment().getDefaultNS();
196             } else {
197                 uri = Environment.getCurrentEnvironment().getNamespaceForPrefix(prefix);
198             }
199             String JavaDoc localName = qname.substring(1+colonIndex);
200             if (uri != null) {
201                 result = element.getAttributeNodeNS(uri, localName);
202             }
203         }
204         return result;
205     }
206     
207     boolean matchesName(String JavaDoc name, Environment env) {
208         return StringUtil.matchesName(name, getNodeName(), getNodeNamespace(), env);
209     }
210 }
Popular Tags