File: JDOMWriterTest.java

package info (click to toggle)
libjibx-java 1.0.1-2
  • links: PTS
  • area: contrib
  • in suites: lenny
  • size: 15,748 kB
  • ctags: 10,069
  • sloc: java: 29,151; xml: 7,963; makefile: 14
file content (399 lines) | stat: -rw-r--r-- 15,853 bytes parent folder | download | duplicates (10)
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
/*
Copyright (c) 2004, Dennis M. Sosnoski
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of JiBX nor the names of its contributors may be used
   to endorse or promote products derived from this software without specific
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package extras;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

import junit.framework.TestCase;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

import org.jibx.extras.JDOMWriter;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.JiBXException;

/** 
 * JUnit <code>TestCase</code> against <code>JDOMWriter</code>.
 * 
 * Most tests marshal a JDOMContact object to a JDOM <code>Document</code> and
 * compare it to a <code>Document</code> based on a static XML file.
 * 
 * As JDOMs equals() methods are based on identity comparison is done using
 * <code>XMLOutputter</code> and comparing the resulting <code>String</code>s.
 * 
 * @author Andreas Brenk
 * @version 1.0
 */
public class JDOMWriterTest extends TestCase {

    private static final String FIRSTNAME = "Tom";
    private static final String LASTNAME = "Sawyer";
    private static final String PHONE = "1-800-555-1212";
    private static final String INFO1 = "Additional Info First Line";
    private static final String INFO2 = "Additional Info Second Line";
    private static final String EMPTY_NAMESPACE = "";
    private static final String XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
    private static final String[] STD_NAMESPACES = new String[] { EMPTY_NAMESPACE, XML_NAMESPACE };
       
    public JDOMWriterTest(String name) {
        super(name);
    }

    /**
     * Test a simple binding.
     */
    public void testSimpleBinding() throws Exception {
        final JDOMContact0 contact = new JDOMContact0(FIRSTNAME, LASTNAME, PHONE);
        
        final Document actualDocument = marshalActualDocument(contact);
        final Document expectedDocument = readExpectedOutput("test/extras/jdomcontact0.xml");
                
        final String actualOutput = formatDocument(actualDocument);
        final String expectedOutput = formatDocument(expectedDocument);
        
        saveActualOutput(actualOutput);
        
        assertEquals(expectedOutput, actualOutput);
    }
    
    /**
     * Test a binding with namespaces.
     */
    public void testNamespaceBinding() throws Exception {
        JDOMContact1 contact = new JDOMContact1(FIRSTNAME, LASTNAME, PHONE, new JDOMContactInformation1(INFO1, INFO2));
        
        final Document actualDocument = marshalActualDocument(contact);
        final Document expectedDocument = readExpectedOutput("test/extras/jdomcontact1.xml");
        
        final String actualOutput = formatDocument(actualDocument);
        final String expectedOutput = formatDocument(expectedDocument);

        saveActualOutput(actualOutput);
        
        assertEquals(expectedOutput, actualOutput);
    }
    
    /**
     * Test marshalling an object into an existing empty Document.
     */
    public void testExistingDocumentWithoutRootNode() throws Exception {
        final JDOMContact0 contact = new JDOMContact0(FIRSTNAME, LASTNAME, PHONE);
        final Document existingDocument = new Document();
        
        final Document returnedDocument = marshalActualDocument(contact, existingDocument);
        final Document expectedDocument = readExpectedOutput("test/extras/jdomcontact0.xml");
                
        final String actualOutput = formatDocument(existingDocument);
        final String expectedOutput = formatDocument(expectedDocument);
        
        saveActualOutput(actualOutput);
        
        assertSame(existingDocument, returnedDocument);
        assertEquals(expectedOutput, actualOutput);
    }

    /**
     * Test marshalling an object into an existing Document with root Element.
     */
    public void testExistingDocumentWithRootNode() throws Exception {
        final JDOMContact0 contact = new JDOMContact0(FIRSTNAME, LASTNAME, PHONE);
        final Element rootElement = new Element("root"); 
        final Document existingDocument = new Document(rootElement);
        
        final Document returnedDocument = marshalActualDocument(contact, existingDocument);
        final Document expectedDocument = readExpectedOutput("test/extras/jdomDocumentContact0.xml");
        
        final String actualOutput = formatDocument(existingDocument);
        final String expectedOutput = formatDocument(expectedDocument);
        
        saveActualOutput(actualOutput);
        
        assertSame(existingDocument, returnedDocument);
        assertEquals(expectedOutput, actualOutput);
    }
    
    /**
     * Test marshalling an object into an existing Document with root and content Elements.
     */
    public void testExistingDocumentAndCurrentElement() throws Exception {
        final JDOMContact0 contact = new JDOMContact0(FIRSTNAME, LASTNAME, PHONE);
        final Element rootElement = new Element("root");
        final Element currentElement = new Element("current");
        rootElement.addContent(new Element("pre").setText("before current"));
        rootElement.addContent(currentElement);
        rootElement.addContent(new Element("post").setText("after current"));
        final Document existingDocument = new Document(rootElement);
        
        final Document returnedDocument = marshalActualDocument(contact, currentElement);
        final Document expectedDocument = readExpectedOutput("test/extras/jdomElementContact0.xml");
                
        final String actualOutput = formatDocument(existingDocument);
        final String expectedOutput = formatDocument(expectedDocument);
        
        saveActualOutput(actualOutput);
        
        assertSame(existingDocument, returnedDocument);
        assertEquals(expectedOutput, actualOutput);
    }
    
    /**
     * Test valid constructor usages.
     */
    public void testValidContructorUsage() throws Exception {
        Element element;
        Document document;
        JDOMWriter jdomWriter = null;
        
        // valid
        jdomWriter = new JDOMWriter(STD_NAMESPACES);
        jdomWriter = new JDOMWriter(new String[] { EMPTY_NAMESPACE, XML_NAMESPACE, "urn:myNs1", "urn:myNs2" });
        
        document = new Document();
        
        // valid
        jdomWriter = new JDOMWriter(STD_NAMESPACES, document);
        
        element = new Element("element");
        document = new Document(element);
        
        // valid
        jdomWriter = new JDOMWriter(STD_NAMESPACES, document);
        jdomWriter = new JDOMWriter(STD_NAMESPACES, element);
        
        assertNotNull(jdomWriter);
    }
    
    /**
     * Test invalid constructor usages.
     */
    public void testInvalidConstructorUsage() throws Exception {
        JDOMWriter jdomWriter = null;
       
        // invalid: empty and xml namespace have to be defined
        try {
            jdomWriter = new JDOMWriter(new String[0]);
            fail("expected ArrayIndexOutOfBoundsException");
        } catch(ArrayIndexOutOfBoundsException e) {}
        try {
            jdomWriter = new JDOMWriter(new String[1]);
            fail("expected ArrayIndexOutOfBoundsException");
        } catch(ArrayIndexOutOfBoundsException e) {}
        
        // invalid: Document is null
        try {
            jdomWriter = new JDOMWriter(STD_NAMESPACES, (Document) null);
            fail("expected NullPointerException");
        } catch(NullPointerException e) {}
        
        // invalid: Element is null
        try {
            jdomWriter = new JDOMWriter(STD_NAMESPACES, (Element) null);
            fail("expected NullPointerException");
        } catch(NullPointerException e) {}
        
        // invalid: Element has no parent Document
        try {
            jdomWriter = new JDOMWriter(STD_NAMESPACES, new Element("element"));
            fail("expected NullPointerException");
        } catch(NullPointerException e) {}
        
        assertNull(jdomWriter);
    }
    
    /**
     * Test adding and removing extension namespaces.
     */
    public void testExtensionNamespaces() throws Exception {
        final JDOMWriter jdomWriter = new JDOMWriter(STD_NAMESPACES);
        String[][] ns;

        ns = jdomWriter.getExtensionNamespaces();
        assertNull(ns);
        
        jdomWriter.pushExtensionNamespaces(new String[] { "urn:myNs1", "urn:myNs2" });
        
        ns = jdomWriter.getExtensionNamespaces();
        assertEquals(1, ns.length);
        assertEquals("urn:myNs1", ns[0][0]);
        assertEquals("urn:myNs2", ns[0][1]);
        
        jdomWriter.pushExtensionNamespaces(new String[] { "urn:myNs3" });
        
        ns = jdomWriter.getExtensionNamespaces();
        assertEquals(2, ns.length);
        assertEquals(2, ns[0].length);
        assertEquals(1, ns[1].length);
        assertEquals("urn:myNs1", ns[0][0]);
        assertEquals("urn:myNs2", ns[0][1]);
        assertEquals("urn:myNs3", ns[1][0]);
        
        jdomWriter.popExtensionNamespaces();
        
        ns = jdomWriter.getExtensionNamespaces();
        assertEquals(1, ns.length);
        assertEquals(2, ns[0].length);
        assertEquals("urn:myNs1", ns[0][0]);
        assertEquals("urn:myNs2", ns[0][1]);
        
        jdomWriter.popExtensionNamespaces();
        
        ns = jdomWriter.getExtensionNamespaces();
        assertNull(ns);
    }
    
    /**
     * Test changing namespace prefixes.
     */
    public void testNamespacePrefixes() throws Exception {
        JDOMWriter jdomWriter = new JDOMWriter(new String[] { EMPTY_NAMESPACE, XML_NAMESPACE, "urn:myNs1", "urn:myNs2" });
        
        assertEquals("", jdomWriter.getNamespaceUri(0));
        assertEquals("http://www.w3.org/XML/1998/namespace", jdomWriter.getNamespaceUri(1));
        assertEquals("urn:myNs1", jdomWriter.getNamespaceUri(2));
        assertEquals("urn:myNs2", jdomWriter.getNamespaceUri(3));
        
        assertEquals("", jdomWriter.getNamespacePrefix(0));
        assertEquals("xml", jdomWriter.getNamespacePrefix(1));
        assertNull("unexpected prefix defined", jdomWriter.getNamespacePrefix(2));
        assertNull("unexpected prefix defined", jdomWriter.getNamespacePrefix(3));
        
        jdomWriter.startTagNamespaces(0, "element1", new int[] {2, 3}, new String[] {"myns1", "myns2"});
        jdomWriter.closeStartTag();

        assertEquals("myns1", jdomWriter.getNamespacePrefix(2));
        assertEquals("myns2", jdomWriter.getNamespacePrefix(3));
        
        jdomWriter.startTagNamespaces(0, "element2", new int[] {2}, new String[] {"prefix"});
        
        assertEquals("prefix", jdomWriter.getNamespacePrefix(2));
        assertEquals("myns2", jdomWriter.getNamespacePrefix(3));
        
        jdomWriter.closeEmptyTag();
        
        assertEquals("myns1", jdomWriter.getNamespacePrefix(2));
        assertEquals("myns2", jdomWriter.getNamespacePrefix(3));
        
        jdomWriter.endTag(0, "element1");
        
        assertNull("unexpected prefix defined", jdomWriter.getNamespacePrefix(2));
        assertNull("unexpected prefix defined", jdomWriter.getNamespacePrefix(3));
    }
    
    /**
     * Helper method to read a file to a <code>Document</code>.
     * 
     * @param filename the name of a XML file to read
     * @return a Document based on the given file 
     */
    private static Document readExpectedOutput(String filename) throws IOException, JDOMException {
        final SAXBuilder builder = new SAXBuilder();
        final InputStream input = new FileInputStream(filename);
        
        return builder.build(input);
    }
    
    /**
     * Helper method to format a <code>Document</code> to String.
     * 
     * @param document the Document to format
     * @return a String containing XML
     */
    private static String formatDocument(Document document) throws IOException {        
        final XMLOutputter outputter = new XMLOutputter();
        final StringWriter writer = new StringWriter();
        
        outputter.output(document, writer);
        
        return writer.getBuffer().toString();
    }
    
    /**
     * Helper method to marshal an Object to a Document.
     * 
     * @param root the Object to marshal
     * @return the Document representation
     */
    private static Document marshalActualDocument(Object root) throws JiBXException {
        final IBindingFactory bfact = BindingDirectory.getFactory(root.getClass());
        final IMarshallingContext mctx = bfact.createMarshallingContext();
        
        final JDOMWriter jdomWriter = new JDOMWriter(bfact.getNamespaces());
        
        return marshalDocument(root, mctx, jdomWriter);
    }
    
    private static Document marshalActualDocument(Object root, Document document) throws JiBXException {
        final IBindingFactory bfact = BindingDirectory.getFactory(root.getClass());
        final IMarshallingContext mctx = bfact.createMarshallingContext();
        
        final JDOMWriter jdomWriter = new JDOMWriter(bfact.getNamespaces(), document);
        
        return marshalDocument(root, mctx, jdomWriter);
    }
    
    private static Document marshalActualDocument(Object root, Element element) throws JiBXException {
        final IBindingFactory bfact = BindingDirectory.getFactory(root.getClass());
        final IMarshallingContext mctx = bfact.createMarshallingContext();
        
        final JDOMWriter jdomWriter = new JDOMWriter(bfact.getNamespaces(), element);
        
        return marshalDocument(root, mctx, jdomWriter);
    }
    
    private static Document marshalDocument(Object root, IMarshallingContext mctx, JDOMWriter jdomWriter) throws JiBXException {
        mctx.setXmlWriter(jdomWriter);
        mctx.marshalDocument(root);
        
        return jdomWriter.getDocument();
    }
    
    /**
     * Helper method to save the actual output to temp.xml
     * 
     * @param actualOutput the output generated by marshalling
     */
    private static void saveActualOutput(String actualOutput) throws IOException {
        File fout = new File("temp.xml");
        fout.delete();
        FileOutputStream fos = new FileOutputStream(fout);
        fos.write(actualOutput.getBytes());
        fos.close();
    }
}