ContentHandlerTest.java revision 687:e7736286abe1
150477Speter/*
240269Srnordier * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
340326Srnordier * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
440326Srnordier *
540326Srnordier * This code is free software; you can redistribute it and/or modify it
640326Srnordier * under the terms of the GNU General Public License version 2 only, as
740326Srnordier * published by the Free Software Foundation.
840326Srnordier *
980751Sjhb * This code is distributed in the hope that it will be useful, but WITHOUT
1040404Srnordier * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1140326Srnordier * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
1280751Sjhb * version 2 for more details (a copy is included in the LICENSE file that
1380751Sjhb * accompanied this code).
1448919Srnordier *
1562138Sjhb * You should have received a copy of the GNU General Public License version
1648919Srnordier * 2 along with this work; if not, write to the Free Software Foundation,
1742480Srnordier * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1842480Srnordier *
1940541Srnordier * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2040541Srnordier * or visit www.oracle.com if you need additional information or have any
2140269Srnordier * questions.
2240269Srnordier */
2340269Srnordierpackage org.xml.sax.ptests;
2440269Srnordier
2540269Srnordierimport java.io.BufferedWriter;
2640269Srnordierimport java.io.FileInputStream;
2740269Srnordierimport java.io.FileWriter;
2840269Srnordierimport java.io.IOException;
2940269Srnordierimport javax.xml.parsers.SAXParserFactory;
3096327Sjhbimport jaxp.library.JAXPFileBaseTest;
3196306Sobrienimport static jaxp.library.JAXPTestUtilities.USER_DIR;
3296327Sjhbimport static jaxp.library.JAXPTestUtilities.compareWithGold;
3396306Sobrienimport static org.testng.Assert.assertTrue;
3440269Srnordierimport org.testng.annotations.Test;
3540269Srnordierimport org.xml.sax.Attributes;
3640269Srnordierimport org.xml.sax.InputSource;
3740269Srnordierimport org.xml.sax.Locator;
3840269Srnordierimport org.xml.sax.SAXException;
3940269Srnordierimport org.xml.sax.XMLReader;
4040269Srnordierimport org.xml.sax.helpers.XMLFilterImpl;
4140269Srnordierimport static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR;
4240269Srnordierimport static org.xml.sax.ptests.SAXTestConst.XML_DIR;
4340308Srnordier
4440269Srnordier/**
4540269Srnordier * Class registers a content event handler to XMLReader. Content event handler
4640269Srnordier * transverses XML and print all visited node  when XMLreader parses XML. Test
4740269Srnordier * verifies output is same as the golden file.
4860821Sjhb */
4960821Sjhbpublic class ContentHandlerTest extends JAXPFileBaseTest {
5040269Srnordier    /**
5196424Speter     * Content event handler visit all nodes to print to output file.
5296424Speter     *
5396424Speter     * @throws Exception If any errors occur.
5496424Speter     */
5596424Speter    @Test
5696424Speter    public void testcase01() throws Exception {
5780751Sjhb        String outputFile = USER_DIR + "Content.out";
5880751Sjhb        String goldFile = GOLDEN_DIR + "ContentGF.out";
5980751Sjhb        String xmlFile = XML_DIR + "namespace1.xml";
6080751Sjhb
6180751Sjhb        try(FileInputStream instream = new FileInputStream(xmlFile);
6259150Sjhb                MyContentHandler cHandler = new MyContentHandler(outputFile)) {
6340269Srnordier            SAXParserFactory spf = SAXParserFactory.newInstance();
6440314Srnordier            spf.setNamespaceAware(true);
6540314Srnordier            XMLReader xmlReader = spf.newSAXParser().getXMLReader();
6640314Srnordier            xmlReader.setContentHandler(cHandler);
6740314Srnordier            xmlReader.parse(new InputSource(instream));
6840269Srnordier        }
6940269Srnordier        assertTrue(compareWithGold(goldFile, outputFile));
7040269Srnordier    }
7140269Srnordier}
7240269Srnordier
7340308Srnordier/**
7440269Srnordier * A content write out handler.
7540404Srnordier */
7640269Srnordierclass MyContentHandler extends XMLFilterImpl implements AutoCloseable {
7740404Srnordier    /**
7840269Srnordier     * Prefix to every exception.
7980751Sjhb     */
8080751Sjhb    private final static String WRITE_ERROR = "bWriter error";
8140404Srnordier
8260821Sjhb    /**
8360821Sjhb     * FileWriter to write string to output file.
8460821Sjhb     */
8560821Sjhb    private final BufferedWriter bWriter;
8640404Srnordier
8740326Srnordier    /**
8840326Srnordier     * Default document locator.
8940326Srnordier     */
9040326Srnordier    private Locator locator;
9140326Srnordier
9240326Srnordier    /**
9340326Srnordier     * Initiate FileWriter when construct a MyContentHandler.
94     * @param outputFileName output file name.
95     * @throws SAXException creation of FileWriter failed.
96     */
97    public MyContentHandler(String outputFileName) throws SAXException {
98        try {
99            bWriter = new BufferedWriter(new FileWriter(outputFileName));
100        } catch (IOException ex) {
101            throw new SAXException(ex);
102        }
103    }
104
105    /**
106     * Write characters tag along with content of characters when meet
107     * characters event.
108     * @throws IOException error happen when writing file.
109     */
110    @Override
111    public void characters(char[] ch, int start, int length) throws SAXException {
112        String s = new String(ch, start, length);
113        println("characters...\n" + s);
114    }
115
116    /**
117     * Write endDocument tag then flush the content and close the file when meet
118     * endDocument event.
119     * @throws IOException error happen when writing file or closing file.
120     */
121    @Override
122    public void endDocument() throws SAXException {
123        try {
124            println("endDocument...");
125            bWriter.flush();
126            bWriter.close();
127        } catch (IOException ex) {
128            throw new SAXException(WRITE_ERROR, ex);
129        }
130    }
131
132    /**
133     * Write endElement tag with namespaceURI, localName, qName to the file when
134     * meet endElement event.
135     * @throws IOException error happen when writing file.
136     */
137    @Override
138    public void endElement(String namespaceURI,String localName,String qName) throws SAXException{
139        println("endElement...\n" + "namespaceURI: " + namespaceURI +
140                " localName: "+ localName + " qName: " + qName);
141    }
142
143    /**
144     * Write endPrefixMapping tag along with prefix to the file when meet
145     * endPrefixMapping event.
146     * @throws IOException error happen when writing file.
147     */
148    @Override
149    public void endPrefixMapping(String prefix) throws SAXException {
150        println("endPrefixMapping...\n" + "prefix: " + prefix);
151    }
152
153    /**
154     * Write ignorableWhitespace tag along with white spaces when meet
155     * ignorableWhitespace event.
156     * @throws IOException error happen when writing file.
157     */
158    @Override
159    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
160        String s = new String(ch, start, length);
161        println("ignorableWhitespace...\n" + s +
162                " ignorable white space string length: " + s.length());
163    }
164
165    /**
166     * Write processingInstruction tag along with target name and target data
167     * when meet processingInstruction event.
168     * @throws IOException error happen when writing file.
169     */
170    @Override
171    public void processingInstruction(String target, String data) throws SAXException {
172        println("processingInstruction...target:" + target +
173                " data: " + data);
174    }
175
176    /**
177     * Write setDocumentLocator tag when meet setDocumentLocator event.
178     */
179    @Override
180    public void setDocumentLocator(Locator locator) {
181        try {
182            this.locator = locator;
183            println("setDocumentLocator...");
184        } catch (SAXException ex) {
185            System.err.println(WRITE_ERROR + ex);
186        }
187    }
188
189    /**
190     * Write skippedEntity tag along with entity name when meet skippedEntity
191     * event.
192     * @throws IOException error happen when writing file.
193     */
194    @Override
195    public void skippedEntity(String name) throws SAXException {
196        println("skippedEntity...\n" + "name: " + name);
197    }
198
199    /**
200     * Write startDocument tag when meet startDocument event.
201     * @throws IOException error happen when writing file.
202     */
203    @Override
204    public void startDocument() throws SAXException {
205        println("startDocument...");
206    }
207
208    /**
209     * Write startElement tag along with namespaceURI, localName, qName, number
210     * of attributes and line number when meet startElement event.
211     * @throws IOException error happen when writing file.
212     */
213    @Override
214    public void startElement(String namespaceURI, String localName,
215                        String qName, Attributes atts) throws SAXException {
216        println("startElement...\n" + "namespaceURI: " +  namespaceURI +
217                " localName: " + localName +  " qName: " + qName +
218                " Number of Attributes: " + atts.getLength() +
219                " Line# " + locator.getLineNumber());
220    }
221
222    /**
223     * Write startPrefixMapping tag along with prefix and uri when meet
224     * startPrefixMapping event.
225     * @throws IOException error happen when writing file.
226     */
227    @Override
228    public void startPrefixMapping(String prefix, String uri) throws SAXException {
229        println("startPrefixMapping...\n" + "prefix: " + prefix +
230                " uri: " + uri);
231    }
232
233    /**
234     * Write outString to file.
235     * @param outString String to be written to File
236     * @throws SAXException if write file failed
237     */
238    private void println(String outString) throws SAXException {
239        try {
240            bWriter.write( outString, 0, outString.length());
241            bWriter.newLine();
242        } catch (IOException ex) {
243            throw new SAXException(WRITE_ERROR, ex);
244        }
245    }
246
247    /**
248     * Close the writer if it's initiated.
249     * @throws IOException if any IO error when close buffered writer.
250     */
251    @Override
252    public void close() throws IOException {
253        if (bWriter != null)
254            bWriter.close();
255    }
256}
257