KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > slide > util > XMLValue


1 /*
2  * $Header: /home/cvs/jakarta-slide/src/share/org/apache/slide/util/XMLValue.java,v 1.6.2.1 2004/09/01 15:40:28 pnever Exp $
3  * $Revision: 1.6.2.1 $
4  * $Date: 2004/09/01 15:40:28 $
5  *
6  * ====================================================================
7  *
8  * Copyright 1999-2002 The Apache Software Foundation
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  *
22  */

23 package org.apache.slide.util;
24 import org.jdom.*;
25
26 import java.io.IOException JavaDoc;
27 import java.io.StringReader JavaDoc;
28 import java.io.StringWriter JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.List JavaDoc;
32 import org.apache.slide.content.NodeProperty;
33 import org.apache.slide.content.NodeRevisionDescriptor;
34 import org.apache.slide.structure.SubjectNode;
35 import org.jdom.input.SAXBuilder;
36 import org.jdom.output.XMLOutputter;
37 import org.xml.sax.Attributes JavaDoc;
38 import org.xml.sax.SAXException JavaDoc;
39 import org.xml.sax.helpers.XMLFilterImpl JavaDoc;
40
41 /**
42  * This class is a container for a list of JDOM Elements.
43  * The {@link #toString toString()} method provides a XML document fragment
44  * describing the Elements of this XMLValue.
45  *
46  * @version $Revision: 1.6.2.1 $
47  *
48  **/

49 public class XMLValue implements Cloneable JavaDoc, Comparable JavaDoc {
50     
51     /**
52      * Constant for the message of the IllegalArgumentException that may be
53      * thrown in method {@link #add add()}.
54      */

55     
56     public static final String JavaDoc ELEMENT_MUST_NOT_BE_NULL = "'null' Element is not allowed";
57     
58     /**
59      * Constant for the message of the IllegalArgumentException that may be
60      * thrown in constructor {@link #XMLValue(List) XMLValue(List)}.
61      */

62     public static final String JavaDoc TYPE_MISMATCH = "Only objects of type Element are allowed";
63     
64     /**
65      * The start tag used to create a valid document out of the XML Element list
66      * string in constructor {@link #XMLValue(String) XMLValue(String)}.
67      */

68     protected static final String JavaDoc START_TAG = "<root>";
69     
70     /**
71      * The end tag used to create a valid document out of the XML Element list
72      * string in constructor {@link #XMLValue(String) XMLValue(String)}.
73      */

74     protected static final String JavaDoc END_TAG = "</root>";
75     
76     protected static final String JavaDoc E_HREF = "href";
77     
78     
79     /**
80      * The list of JDOM Elements.
81      */

82     protected ArrayList JavaDoc elementList = null;
83     
84     
85     /**
86      * Creates a XMLValue.
87      */

88     public XMLValue() {
89         this((List JavaDoc)null);
90     }
91     
92     /**
93      * Creates a XMLValue from the given <code>element</code>.
94      *
95      * @param element the JDOM Element to add to the list.
96      *
97      * @throws IllegalArgumentException if the given <code>element</code>
98      * is <code>null</code>.
99      */

100     public XMLValue(Element element) throws IllegalArgumentException JavaDoc {
101         this((List JavaDoc)null);
102         add(element);
103     }
104     
105     /**
106      * Creates a XMLValue from the given <code>list</code> of JDOM Elements.
107      * the given List may be <code>null</code>.
108      *
109      * @param elementList the list of JDOM Elements to add.
110      *
111      * @throws IllegalArgumentException if one of the list items
112      * is <code>null</code> or not a
113      * <code>Element</code>.
114      */

115     public XMLValue(List JavaDoc elementList) throws IllegalArgumentException JavaDoc{
116         this.elementList = new ArrayList JavaDoc();
117         add(elementList);
118     }
119     
120     /**
121      * Creates a XMLValue from the given String representation of a
122      * list of XML Elements.
123      *
124      * @param xmlString a String representation of a list of XML Elements.
125      *
126      * @throws JDOMException if parsing the <code>xmlString</code> fails.
127      */

128     public XMLValue(String JavaDoc xmlString) throws JDOMException {
129         this(xmlString, null);
130     }
131     
132     /**
133      * Creates a XMLValue from the given String representation of a
134      * list of XML Elements. If the given <code>defaultNamespace</code> is not
135      * <code>null</code>, all nodes that does not have any namespace will be
136      * created with that Namespace.
137      *
138      * @param xmlString a String representation of a list of XML Elements.
139      * @param defaultNamespace the Namespace to use to create nodes that
140      * does not have any namespace.
141      * May be <code>null</code>.
142      *
143      * @throws JDOMException if parsing the <code>xmlString</code> fails.
144      */

145     public XMLValue(String JavaDoc xmlString, Namespace defaultNamespace) throws JDOMException {
146         this((List JavaDoc)null);
147         add(xmlString, defaultNamespace);
148     }
149     
150     
151     /**
152      * Adds a JDOM Element.
153      *
154      * @param element the JDOM Element to add.
155      *
156      * @throws IllegalArgumentException if the given <code>element</code>
157      * is <code>null</code>.
158      */

159     public void add(Element element) throws IllegalArgumentException JavaDoc {
160         if (element == null) {
161             throw new IllegalArgumentException JavaDoc(ELEMENT_MUST_NOT_BE_NULL);
162         }
163         elementList.add(element);
164     }
165     
166     /**
167      * Adds a JDOM Text.
168      *
169      * @param text the JDOM Text to add.
170      *
171      * @throws IllegalArgumentException if the given <code>text</code>
172      * is <code>null</code>.
173      */

174     public void add(Text text) throws IllegalArgumentException JavaDoc {
175         if (text == null) {
176             throw new IllegalArgumentException JavaDoc(ELEMENT_MUST_NOT_BE_NULL);
177         }
178         elementList.add(text);
179     }
180     
181     /**
182      * Adds a JDOM Comment.
183      *
184      * @param comment the JDOM Comment to add.
185      *
186      * @throws IllegalArgumentException if the given <code>comment</code>
187      * is <code>null</code>.
188      */

189     public void add(Comment comment) throws IllegalArgumentException JavaDoc {
190         if (comment == null) {
191             throw new IllegalArgumentException JavaDoc(ELEMENT_MUST_NOT_BE_NULL);
192         }
193         elementList.add(comment);
194     }
195     
196     /**
197      * Adds a JDOM ProcessingInstruction.
198      *
199      * @param pi the JDOM ProcessingInstruction to add.
200      *
201      * @throws IllegalArgumentException if the given <code>pi</code>
202      * is <code>null</code>.
203      */

204     public void add(ProcessingInstruction pi) throws IllegalArgumentException JavaDoc {
205         if (pi == null) {
206             throw new IllegalArgumentException JavaDoc(ELEMENT_MUST_NOT_BE_NULL);
207         }
208         elementList.add(pi);
209     }
210     
211     /**
212      * Adds a JDOM CDATA.
213      *
214      * @param cdata the JDOM CDATA to add.
215      *
216      * @throws IllegalArgumentException if the given <code>CDATA</code>
217      * is <code>null</code>.
218      */

219     public void add(CDATA cdata) throws IllegalArgumentException JavaDoc {
220         if (cdata == null) {
221             throw new IllegalArgumentException JavaDoc(ELEMENT_MUST_NOT_BE_NULL);
222         }
223         elementList.add(cdata);
224     }
225     
226     /**
227      * Adds a JDOM EntityRef.
228      *
229      * @param eref the JDOM EntityRef to add.
230      *
231      * @throws IllegalArgumentException if the given <code>entity ref</code>
232      * is <code>null</code>.
233      */

234     public void add(EntityRef eref) throws IllegalArgumentException JavaDoc {
235         if (eref == null) {
236             throw new IllegalArgumentException JavaDoc(ELEMENT_MUST_NOT_BE_NULL);
237         }
238         elementList.add(eref);
239     }
240     
241     /**
242      * Adds a List of JDOM items.
243      *
244      * @param content the list of JDOM items to add.
245      *
246      * @throws IllegalArgumentException if one of the list items
247      * is <code>null</code> or not a
248      * <code>Element</code>.
249      */

250     public void add(List JavaDoc content) throws IllegalArgumentException JavaDoc {
251         
252         if (content != null) {
253             Iterator iterator = content.iterator();
254             while (iterator.hasNext()) {
255                 Object JavaDoc o = iterator.next();
256                 if( o == null ) {
257                     throw new IllegalArgumentException JavaDoc(ELEMENT_MUST_NOT_BE_NULL);
258                 }
259                 else if( o instanceof Element ) {
260                     add((Element)o);
261                 }
262                 else if( o instanceof Text ) {
263                     Text t = (Text)o;
264                     t.setText( t.getTextTrim() );
265                     add(t);
266                 }
267                 else if( o instanceof Comment ) {
268                     add((Comment)o);
269                 }
270                 else if( o instanceof ProcessingInstruction ) {
271                     add((ProcessingInstruction)o);
272                 }
273                 else if( o instanceof CDATA ) {
274                     add((CDATA)o);
275                 }
276                 else if( o instanceof EntityRef ) {
277                     add((EntityRef)o);
278                 }
279                 else {
280                     throw new IllegalArgumentException JavaDoc(TYPE_MISMATCH);
281                 }
282             }
283         }
284     }
285     
286     /**
287      * Adds the Elements given by an XML string representation.
288      *
289      * @param xmlString a String representation of a list of XML Elements.
290      *
291      * @throws JDOMException if parsing the <code>xmlString</code> fails.
292      */

293     public void add(String JavaDoc xmlString) throws JDOMException {
294         add(xmlString, null);
295     }
296     
297     /**
298      * Adds the Elements given by an XML string representation. If the given
299      * <code>namespace</code> is not <code>null</code>, all nodes that does not
300      * have any namespace will be created with that Namespace.
301      *
302      * @param xmlString a String representation of a list of XML Elements.
303      * @param defaultNamespace the Namespace to use to create nodes that
304      * does not have any namespace.
305      * May be <code>null</code>.
306      *
307      * @throws JDOMException if parsing the <code>xmlString</code> fails.
308      */

309     public void add(String JavaDoc xmlString, Namespace defaultNamespace) throws JDOMException {
310         
311         if (xmlString != null && xmlString.length() > 0) {
312             if (NodeRevisionDescriptor.COLLECTION_TYPE.equals(xmlString)) {
313                 // avoid trivial parsing
314
add(new Element("collection", defaultNamespace));
315             }
316             else {
317                 StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(START_TAG.length() +
318                                                            xmlString.length() +
319                                                            END_TAG.length());
320                 buffer.append(START_TAG);
321                 buffer.append(xmlString);
322                 buffer.append(END_TAG);
323                 SAXBuilder builder = new SAXBuilder();
324                 if (defaultNamespace != null) {
325                     builder.setXMLFilter(new DefaultNamespaceXMLFilter(defaultNamespace));
326                 }
327                 try {
328                     Document document = builder.build(new StringReader JavaDoc(buffer.toString()));
329                     List JavaDoc content = document.getRootElement().getContent();
330                     add( content );
331                     // detach elements from parent
332
content.clear();
333                 }
334                 catch (Exception JavaDoc e) {
335                     // should not happen since the StringReader does not
336
// perform any "real" I/O
337
throw new JDOMException(e.getMessage());
338                 }
339             }
340         }
341     }
342     
343     public void addHref(String JavaDoc path) {
344         Element href = new Element(E_HREF, NodeProperty.NamespaceCache.DEFAULT_NAMESPACE);
345         href.setText(path);
346         add(href);
347     }
348     
349     /**
350      * Method getHrefs
351      *
352      * @return a List of URIs (String)
353      *
354      */

355     public List JavaDoc getHrefStrings() {
356         List JavaDoc result = new ArrayList JavaDoc();
357         Iterator i = iterator();
358         while (i.hasNext()) {
359             Object JavaDoc o = i.next();
360             if (o instanceof Element && E_HREF.equals(((Element)o).getName())) {
361                 result.add(((Element)o).getTextTrim());
362             }
363         }
364         return result;
365     }
366     
367     /**
368      * Method getHrefs
369      *
370      * @return a List of nodes (SubjectNode)
371      *
372      */

373     public List JavaDoc getHrefNodes() {
374         List JavaDoc result = new ArrayList JavaDoc();
375         Iterator i = iterator();
376         while (i.hasNext()) {
377             Object JavaDoc o = i.next();
378             if (o instanceof Element && E_HREF.equals(((Element)o).getName())) {
379                 result.add(SubjectNode.getSubjectNode(((Element)o).getTextTrim()));
380             }
381         }
382         return result;
383     }
384     
385     public void stripServletContext(String JavaDoc servletContext) {
386         Iterator i = iterator();
387         while (i.hasNext()) {
388             Object JavaDoc o = i.next();
389             if (o instanceof Element && E_HREF.equals(((Element)o).getName())) {
390                 Element hrefElm = (Element)o;
391                 String JavaDoc href = hrefElm.getTextTrim();
392                 if (href.startsWith(servletContext)) {
393                     hrefElm.setContent(java.util.Arrays.asList(
394                                            new Text[]{new Text(href.substring(servletContext.length()))}));
395                 }
396             }
397         }
398     }
399     
400     /**
401      * Returns an iterator of JDOM Elements.
402      *
403      * @return an iterator of JDOM Elements.
404      */

405     public Iterator iterator() {
406         return elementList.iterator();
407     }
408     
409     /**
410      * Returns the amount of JDOM elements.
411      *
412      * @return the amount of JDOM elements.
413      */

414     public int size() {
415         return elementList.size();
416     }
417     
418     /**
419      * Returns a clone of the List of JDOM Elements.
420      *
421      * @return a clone of the List of JDOM Elements.
422      */

423     public List JavaDoc getList() {
424         return (List JavaDoc)elementList.clone();
425     }
426     
427     /**
428      * Returns <code>true</code> if the other object is an XMLValue and
429      * both their String representations are equal.
430      *
431      * @param other the Object to test for equality.
432      *
433      * @return <code>true</code> if the other object is an XMLValue and
434      * both their String representations are equal.
435      */

436     public boolean equals(Object JavaDoc other) {
437         if ( ! (other instanceof XMLValue) ) {
438             return false;
439         }
440         return (this.toString().equals(other.toString()));
441     }
442     
443     /**
444      * Returns the hash code of this instance.
445      *
446      * @return the hash code of this instance.
447      */

448     public int hashCode() {
449         return toString().hashCode();
450     }
451     
452     /**
453      * Returns a clone of this instance.
454      *
455      * @return a clone of this instance.
456      */

457     public Object JavaDoc clone() {
458         return new XMLValue(elementList);
459     }
460     
461     /**
462      * Returns a String representation of the Elements as a XML document fragment.
463      *
464      * @return a String representation of the Elements.
465      */

466     public String JavaDoc toString() {
467         
468         XMLOutputter outputter = new XMLOutputter();
469         StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
470         Iterator iterator = elementList.iterator();
471         while (iterator.hasNext()) {
472             try {
473                 Object JavaDoc o = iterator.next();
474                 if( o instanceof Element ) {
475                     outputter.output((Element)o, stringWriter);
476                 }
477                 else if( o instanceof Text ) {
478                     outputter.output((Text)o, stringWriter);
479                 }
480                 else if( o instanceof Comment ) {
481                     outputter.output((Comment)o, stringWriter);
482                 }
483                 else if( o instanceof ProcessingInstruction ) {
484                     outputter.output((ProcessingInstruction)o, stringWriter);
485                 }
486                 else if( o instanceof CDATA ) {
487                     outputter.output((CDATA)o, stringWriter);
488                 }
489                 else if( o instanceof EntityRef ) {
490                     outputter.output((EntityRef)o, stringWriter);
491                 }
492             }
493             catch (IOException JavaDoc e) {
494                 // this should not happen since we're writing to a StringWriter
495
// which is no 'real' I/O
496
throw new RuntimeException JavaDoc("IOException occurred: " + e.getMessage());
497             }
498         }
499         return stringWriter.toString();
500     }
501     
502     /**
503      * This XMLFilter uses the given namespace as the default, means if no
504      * namespace is provided.
505      */

506     protected static class DefaultNamespaceXMLFilter extends XMLFilterImpl JavaDoc {
507         
508         /**
509          * The namespace to use as default.
510          */

511         Namespace defaultNamespace = null;
512         
513         /**
514          * Creates a DefaultNamespaceXMLFilter which uses the given
515          * <code>defaultNamespace</code> as default namespace, means if no
516          * namespace is provided.
517          *
518          * @param defaultNamespace the Namespace to use as default.
519          * Must NOT be <code>null</code>.
520          */

521         public DefaultNamespaceXMLFilter(Namespace defaultNamespace) {
522             this.defaultNamespace = defaultNamespace;
523         }
524         
525         /**
526          * Overwrite <code>startElement()</code> in order to provide the
527          * <code>defaultNamespace</code> if the current Element does not have
528          * any namespace.
529          *
530          * @param namespaceURI the URI of the Namespace.
531          * @param localName the name of the Element without any namspace
532          * prefix.
533          * @param qName the full name of the Element (with the namespace
534          * prefix if there is one).
535          * @param atts the Attributes of the element.
536          *
537          * @throws SaxException
538          */

539         public void startElement(String JavaDoc namespaceURI, String JavaDoc localName, String JavaDoc qName, Attributes JavaDoc atts) throws SAXException JavaDoc {
540             
541             if ( (namespaceURI == null) || (namespaceURI.length() == 0) ) {
542                 namespaceURI = defaultNamespace.getURI();
543                 qName = defaultNamespace.getPrefix() + ":" + qName;
544             }
545             super.startElement(namespaceURI, localName, qName, atts);
546         }
547         
548         /**
549          * Overwrite <code>endElement()</code> in order to provide the
550          * <code>defaultNamespace</code> if the current Element does not have
551          * any namespace.
552          *
553          * @param namespaceURI the URI of the Namespace.
554          * @param localName the name of the Element without any namspace
555          * prefix.
556          * @param qName the full name of the Element (with the namespace
557          * prefix if there is one).
558          *
559          * @throws SaxException
560          */

561         public void endElement(String JavaDoc namespaceURI, String JavaDoc localName, String JavaDoc qName) throws SAXException JavaDoc {
562             
563             if ( (namespaceURI == null) || (namespaceURI.length() == 0) ) {
564                 namespaceURI = defaultNamespace.getURI();
565                 qName = defaultNamespace.getPrefix() + ":" + qName;
566             }
567             super.endElement(namespaceURI, localName, qName);
568         }
569         
570     }
571     
572     /**
573      * concatenates the text() values of all Elements in elementList
574      *
575      * @return a String
576      *
577      */

578     public String JavaDoc getTextValue() {
579         Iterator it = elementList.iterator();
580         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
581         
582         while (it.hasNext()) {
583             Object JavaDoc o = it.next();
584             if (o instanceof Element) {
585                 sb.append (((Element)o).getTextTrim());
586             }
587         }
588         return sb.toString();
589     }
590     
591     /**
592      * compares the concatenated Text values of all Elements in elementList
593      *
594      * @param o an Object
595      *
596      * @return an int
597      *
598      */

599     public int compareTo (Object JavaDoc o) {
600         
601         String JavaDoc s1 = getTextValue();
602         String JavaDoc s2 = ((XMLValue)o).getTextValue();
603         return s1.compareTo (s2);
604     }
605 }
606
607
Popular Tags