1 22 package org.jboss.test.stax; 23 24 import org.jboss.test.JBossTestCase; 25 26 import java.io.ByteArrayOutputStream ; 27 import java.io.FileInputStream ; 28 import java.net.URL ; 29 30 import javax.xml.stream.XMLEventFactory; 31 import javax.xml.stream.XMLEventReader; 32 import javax.xml.stream.XMLEventWriter; 33 import javax.xml.stream.XMLInputFactory; 34 import javax.xml.stream.XMLOutputFactory; 35 import javax.xml.stream.XMLStreamReader; 36 import javax.xml.stream.XMLStreamWriter; 37 import javax.xml.stream.events.Characters; 38 import javax.xml.stream.events.StartDocument; 39 import javax.xml.stream.events.XMLEvent; 40 import javax.xml.stream.util.XMLEventAllocator; 41 42 43 48 public class StaxTestCase extends JBossTestCase 49 { 50 53 public StaxTestCase(String name) 54 { 55 super(name); 56 } 57 58 private static String getXmlUrl(String name) 59 { 60 return getTCLResource(name).getFile(); 61 } 62 63 private static URL getTCLResource(String name) 64 { 65 URL xmlUrl = Thread.currentThread().getContextClassLoader().getResource(name); 66 if(xmlUrl == null) 67 { 68 throw new IllegalStateException (name + " not found"); 69 } 70 return xmlUrl; 71 } 72 73 public void testStreamReader() throws Exception 74 { 75 FileInputStream stream = new FileInputStream (getXmlUrl("stax/test.xml")); 76 XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream); 77 reader.next(); 78 } 79 80 public void testEventReader() throws Exception 81 { 82 FileInputStream stream = new FileInputStream (getXmlUrl("stax/test.xml")); 83 XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(stream); 84 XMLEvent event = reader.nextEvent(); 85 assertTrue("Expected document start, got:" + event.getClass(), event instanceof StartDocument); 86 event = reader.nextEvent(); 87 assertTrue("Expected characters, got:" + event.getClass(), event instanceof Characters); 88 } 89 90 public void testStreamWriter() throws Exception 91 { 92 ByteArrayOutputStream stream = new ByteArrayOutputStream (); 93 XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(stream); 94 writer.writeStartDocument(); 95 writer.writeComment("hello"); 96 writer.close(); 97 assertEquals("<?xml version='1.0' encoding='utf-8'?><!--hello-->", stream.toString()); 98 } 99 100 public void testEventWriter() throws Exception 101 { 102 ByteArrayOutputStream stream = new ByteArrayOutputStream (); 103 XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(stream); 104 XMLEventFactory factory = XMLEventFactory.newInstance(); 105 writer.add(factory.createStartDocument()); 106 writer.add(factory.createComment("hello")); 107 writer.close(); 108 assertEquals("<?xml version='1.0' encoding='UTF-8'?><!--hello-->", stream.toString()); 109 } 110 } 111 | Popular Tags |