~ubuntu-branches/ubuntu/precise/xom/precise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/* Copyright 2002-2004 Elliotte Rusty Harold
   
   This library is free software; you can redistribute it and/or modify
   it under the terms of version 2.1 of the GNU Lesser General Public 
   License as published by the Free Software Foundation.
   
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
   GNU Lesser General Public License for more details.
   
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the 
   Free Software Foundation, Inc., 59 Temple Place, Suite 330, 
   Boston, MA 02111-1307  USA
   
   You can contact Elliotte Rusty Harold by sending e-mail to
   elharo@metalab.unc.edu. Please include the word "XOM" in the
   subject line. The XOM home page is located at http://www.xom.nu/
*/

package nu.xom;

/**
 * <p>
 * The <code>Document</code> class represents
 * a complete XML document including its root element,
 * prolog, and epilog.
 * </p>
 * 
 * @author Elliotte Rusty Harold
 * @version 1.1b5
 * 
 */
public class Document extends ParentNode {

    /**
     * <p>
     * Creates a new <code>Document</code> object with the
     * specified root element.
     * </p>
     * 
     * @param root the root element of this document
     * 
     * @throws NullPointerException if <code>root</code> is null
     * @throws MultipleParentException if <code>root</code> already 
     *     has a parent
     */
    public Document(Element root) {
        _insertChild(root, 0);
    }

    
    /**
     * <p>
     * Creates a copy of this document.
     * </p>
     * 
     * @param doc the document to copy
     * 
     * @throws NullPointerException if <code>doc</code> is null
     */
    public Document(Document doc) {

      insertChild(doc.getRootElement().copy(), 0);
      int count = doc.getChildCount();
      for (int i = 0; i < count; i++) {
          Node child = doc.getChild(i);
          if (!(child.isElement())) {
              this.insertChild(child.copy(), i);
          }
      }
      this.actualBaseURI = doc.actualBaseURI;

    }


    final void insertionAllowed(Node child, int position) {
        
        if (child == null) {
            throw new NullPointerException(
             "Tried to insert a null child in the document");
        }
        else if (child.getParent() != null) {
            throw new MultipleParentException("Child already has a parent.");
        }
        else if (child.isComment() || child.isProcessingInstruction()) {
            return;
        }
        else if (child.isDocType()) {
            if (position <= getRootPosition()) {
                DocType oldDocType = getDocType(); 
                if (oldDocType != null) {
                    throw new IllegalAddException(
                      "Tried to insert a second DOCTYPE"
                    );   
                }
                return;
            }
            else {
                throw new IllegalAddException(
                  "Cannot add a document type declaration "
                  + "after the root element"
                );               
            }
        }
        else if (child.isElement()) {
            if (getChildCount() == 0) return;
            else {
                throw new IllegalAddException(
                  "Cannot add a second root element to a Document."
                );
            }
        }
        else {
            throw new IllegalAddException("Cannot add a "
             + child.getClass().getName() + " to a Document.");
        }

    }
    

    private int getRootPosition() {
        
        // This looks like an infinite loop but it isn't
        // because all documents have root elements
        for (int i = 0; ; i++) {
             Node child = getChild(i);
             if (child.isElement()) {
                return i;
             }
         }
        
    }
    
    
    /**
     * <p>
     * Returns this document's document type declaration, 
     * or null if it doesn't have one.
     * </p>
     * 
     * @return the document type declaration
     * 
     * @see #setDocType
     *
     */
    public final DocType getDocType() {
        
        for (int i = 0; i < getChildCount(); i++) {
             Node child = getChild(i);
             if (child.isDocType()) {
                return (DocType) child;
             }
         }
         return null;
         
    }

    
    /**
     * <p>
     * Sets this document's document type declaration.
     * If this document already has a document type declaration,
     * then it's inserted at that position. Otherwise, it's inserted
     * at the beginning of the document.
     * </p>
     * 
     * @param doctype the document type declaration
     * 
     * @throws MultipleParentException if <code>doctype</code> belongs 
     *      to another document
     * @throws NullPointerException if <code>doctype</code> is null
     * 
     */
    public void setDocType(DocType doctype) {
        
        DocType oldDocType = getDocType();
        if (doctype == null) {
            throw new NullPointerException("Null DocType");
        }
        else if (doctype == oldDocType) return; 
        else if (doctype.getParent() != null) {
            throw new MultipleParentException("DocType belongs to another document");
        }
        
        if (oldDocType == null) insertChild(doctype, 0);
        else {
            int position = indexOf(oldDocType);
            super.removeChild(position);
            fastInsertChild(doctype, position);
            oldDocType.setParent(null);
            doctype.setParent(this);
        }
        
    }


    /**
     * <p>
     * Returns this document's root element.
     * This is guaranteed to be non-null.
     * </p>
     * 
     * @return the root element
     */
    public final Element getRootElement() {
        
        // This looks like an infinite loop but it isn't because
        // all documents have root elements.
        for (int i = 0; ; i++) {
             Node child = getChild(i);
             if (child.isElement()) {
                return (Element) child;
             }
         }
        
    }

    
    /**
     * <p>
     * Replaces the current root element with a different root element.
     * </p>
     * 
     * @param root the new root element
     * 
     * @throws MultipleParentException if root has a parent
     * @throws NullPointerException if root is null
     */
    public void setRootElement(Element root) {
        
        Element oldRoot = this.getRootElement(); 
        if (root == oldRoot) return;
        else if (root == null) {
            throw new NullPointerException("Root element cannot be null");
        }
        else if (root.getParent() != null) {
            throw new MultipleParentException(root.getQualifiedName()
              + " already has a parent");
        }
        
        fillInBaseURI(oldRoot);
        int index = indexOf(oldRoot);
        
        oldRoot.setParent(null);
        children[index] = root;
        root.setParent(this);
        
    }
    
    
    /**
     * <p>
     * Sets the URI from which this document was loaded, and
     * against which relative URLs in this document will be resolved.
     * Setting the base URI to null or the empty string removes any
     * existing base URI.
     * </p>
     * 
     * @param URI the base URI of this document 
     * 
     * @throws MalformedURIException if <code>URI</code> is 
     *     not a legal absolute URI
     */
    public void setBaseURI(String URI) { 
        setActualBaseURI(URI);       
    }
    
    
    /**
     * <p>
     *   Returns the absolute URI from which this document was loaded.
     *   This method returns the empty string if the base URI is not 
     *   known; for instance if the document was created in memory with
     *   a constructor rather than by parsing an existing document.
     * </p>
     * 
     * @return the base URI of this document 
     */
    public final String getBaseURI() {       
        return getActualBaseURI();
    }

    
    /**
     * <p>
     * Removes the child of this document at the specified position.
     * Indexes begin at 0 and count up to one less than the number
     * of children of this document. The root element cannot be 
     * removed. Instead, use <code>setRootElement</code> to replace
     * the existing root element with a different element.
     * </p>
     * 
     * @param position index of the node to remove
     * 
     * @return the node which was removed
     * 
     * @throws IndexOutOfBoundsException if the index is negative or 
     *    greater than the number of children of this document - 1
     * @throws WellformednessException if the index points 
     *     to the root element
     */
    public Node removeChild(int position) {
        
        if (position == getRootPosition()) {
            throw new WellformednessException(
              "Cannot remove the root element"
            );
        }
        return super.removeChild(position);
        
    }

    
    /**
     * <p>
     * Removes the specified child from this document.
     * The root element cannot be removed.
     * Instead, use <code>setRootElement</code> to replace the
     * existing root element with a different element.
     * </p>
     * 
     * @param child node to remove
     * 
     * @return the node which was removed
     * 
     * @throws NoSuchChildException if the node is not a
     *   child of this node
     * @throws WellformednessException if child is the root element
     */
    public Node removeChild(Node child) {
        
        if (child == getRootElement()) {
            throw new WellformednessException(
              "Cannot remove the root element");
        }
        return super.removeChild(child);
        
    }

    
    /**
     * <p>
     * Replaces an existing child with a new child node.
     * If <code>oldChild</code> is not a child of this node, 
     * then a <code>NoSuchChildException</code> is thrown. 
     * The root element can only be replaced by another element.
     * </p>
     * 
     * @param oldChild the node removed from the tree
     * @param newChild the node inserted into the tree
     * 
     * @throws MultipleParentException if <code>newChild</code> already
     *     has a parent
     * @throws NoSuchChildException if <code>oldChild</code> 
     *     is not a child of this node
     * @throws NullPointerException if either argument is null
     * @throws IllegalAddException if <code>newChild</code> is an
     *     attribute or a text node
     * @throws WellformednessException if <code>newChild</code> 
     *     <code>oldChild</code> is an element and 
     *     <code>newChild</code> is not
     */
    public void replaceChild(Node oldChild, Node newChild) {
          
        if (oldChild == getRootElement() 
          && newChild != null && newChild.isElement()) {
            setRootElement((Element) newChild);
        } 
        else if (oldChild == getDocType() 
          && newChild != null && newChild.isDocType()) {
            setDocType((DocType) newChild);
        }
        else {
            super.replaceChild(oldChild, newChild);
        }
        
    }


    /**
     * <p>
     * Returns the value of the document as defined by XPath 1.0.
     * This is the same as the value of the root element, which 
     * is the complete PCDATA content of the root element, without 
     * any tags, comments, or processing instructions after all 
     * entity and character references have been resolved.
     * </p>
     * 
     * @return  value of the root element of this document
     * 
     */
    public final String getValue() {
        return getRootElement().getValue();
    }

    
    /**
     * <p>
     * Returns the actual complete, well-formed XML document as a 
     * <code>String</code>. Significant white space is preserved. 
     * Insignificant white space in tags, the prolog, the epilog, 
     * and the internal DTD subset is not preserved.
     * Entity and character references are not preserved. 
     * The entire document is contained in this one string.
     * </p>
     * 
     * @return a string containing this entire XML document
     */
    public final String toXML() {
    
        StringBuffer result = new StringBuffer();

        // XML declaration
        result.append("<?xml version=\"1.0\"?>\n");
        
        // children
        for (int i = 0; i < getChildCount(); i++) {
            result.append(getChild(i).toXML());
            result.append("\n");  
        }
        
        return result.toString();
        
    }

    
    /**
     * <p>
     * Returns a complete copy of this document.
     * </p>
     * 
     * @return a deep copy of this <code>Document</code> object
     */
    public Node copy() {
        return new Document(this);
    }

    
    boolean isDocument() {
        return true;   
    }

    
    /**
     * <p>
     * Returns a string representation of this document suitable 
     * for debugging and diagnosis. This is <em>not</em>
     * the XML representation of this document.
     * </p>
     * 
     * @return a non-XML string representation of this document
     */
    public final String toString() {
        return "[" + getClass().getName() + ": " 
          + getRootElement().getQualifiedName() + "]"; 
    }

    
}