1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package org.xml.sax.ptests;
  24 
  25 import java.io.BufferedWriter;
  26 import java.io.File;
  27 import java.io.FileWriter;
  28 import java.io.IOException;
  29 import javax.xml.parsers.ParserConfigurationException;
  30 import javax.xml.parsers.SAXParser;
  31 import javax.xml.parsers.SAXParserFactory;
  32 import jaxp.library.JAXPFileBaseTest;
  33 import static jaxp.library.JAXPTestUtilities.compareWithGold;
  34 import static org.testng.Assert.assertTrue;
  35 import org.testng.annotations.Test;
  36 import org.xml.sax.Attributes;
  37 import org.xml.sax.Locator;
  38 import org.xml.sax.SAXException;
  39 import org.xml.sax.SAXParseException;
  40 import org.xml.sax.helpers.DefaultHandler;
  41 import static org.xml.sax.ptests.SAXTestConst.CLASS_DIR;
  42 import static org.xml.sax.ptests.SAXTestConst.GOLDEN_DIR;
  43 import static org.xml.sax.ptests.SAXTestConst.XML_DIR;
  44 
  45 /**
  46  * XMLReader parse XML with default handler that transverses XML and
  47  * print all visited node. Test verifies output is same as the golden file.
  48  */
  49 public class DefaultHandlerTest extends JAXPFileBaseTest {
  50     /**
  51      * Test default handler that transverses XML and  print all visited node.
  52      * 
  53      * @throws SAXException If any parse errors occur.
  54      * @throws IOException if the file exists but is a directory rather than
  55      *         a regular file, does not exist but cannot be created, or cannot 
  56      *         be opened for any other reason.
  57      * @throws ParserConfigurationException if a DocumentBuilder cannot be 
  58      *         created which satisfies the configuration requested.
  59      */
  60     @Test
  61     public void testDefaultHandler() throws ParserConfigurationException,
  62             SAXException, IOException {
  63         String outputFile = CLASS_DIR + "DefaultHandler.out";
  64         String goldFile = GOLDEN_DIR + "DefaultHandlerGF.out";
  65         String xmlFile = XML_DIR + "namespace1.xml";
  66 
  67         SAXParserFactory spf = SAXParserFactory.newInstance();
  68         spf.setNamespaceAware(true);
  69         SAXParser saxparser = spf.newSAXParser();
  70 
  71         MyDefaultHandler handler = new MyDefaultHandler(outputFile);
  72         File file = new File(xmlFile);
  73         String Absolutepath = file.getAbsolutePath();
  74         String newAbsolutePath = Absolutepath;
  75         if (File.separatorChar == '\\')
  76                 newAbsolutePath = Absolutepath.replace('\\', '/');
  77         saxparser.parse("file:///" + newAbsolutePath, handler);
  78 
  79         assertTrue(compareWithGold(goldFile, outputFile));
  80 
  81     }
  82 }
  83 
  84 class MyDefaultHandler extends DefaultHandler {
  85     /**
  86      * Prefix to every exception.
  87      */
  88     private final static String WRITE_ERROR = "bWrite error";
  89 
  90     /**
  91      * FileWriter to write string to output file.
  92      */
  93     private final BufferedWriter bWriter;
  94 
  95     /**
  96      * Initiate FileWriter when construct a MyContentHandler.
  97      * @param outputFileName output file name.
  98      * @throws SAXException creation of FileWriter failed.
  99      */
 100     MyDefaultHandler(String outputFileName) throws SAXException {
 101         try {
 102             bWriter = new BufferedWriter(new FileWriter(outputFileName));
 103         } catch (IOException ex) {
 104             throw new SAXException(ex);
 105         }
 106     }
 107 
 108     /**
 109      * Write characters tag along with content of characters when meet
 110      * characters event.
 111      * @throws IOException error happen when writing file.
 112      */
 113     @Override
 114     public void characters(char[] ch, int start, int length) throws SAXException {
 115         println("characters...\n" + new String(ch, start, length));
 116     }
 117 
 118     /**
 119      * Write endDocument tag then flush the content and close the file when meet
 120      * endDocument event.
 121      * @throws IOException error happen when writing file or closing file.
 122      */
 123     @Override
 124     public void endDocument() throws SAXException {
 125         try {
 126             println("endDocument...");
 127             bWriter.flush();
 128             bWriter.close();
 129         } catch (IOException ex) {
 130             throw new SAXException(WRITE_ERROR, ex);
 131         }
 132     }
 133 
 134     /**
 135      * Write endElement tag with namespaceURI, localName, qName to the file when
 136      * meet endElement event.
 137      * @throws IOException error happen when writing file.
 138      */
 139     @Override
 140     public void endElement(String namespaceURI,String localName,String qName) throws SAXException{
 141         println("endElement...\n" + "namespaceURI: " + namespaceURI +
 142                 " localName: "+ localName + " qName: " + qName);
 143     }
 144 
 145     /**
 146      * Write endPrefixMapping tag along with prefix to the file when meet
 147      * endPrefixMapping event.
 148      * @throws IOException error happen when writing file.
 149      */
 150     @Override
 151     public void endPrefixMapping(String prefix) throws SAXException {
 152         println("endPrefixmapping .." + prefix);
 153     }
 154 
 155     /**
 156      * Write error tag along with exception to the file when meet recoverable
 157      * error event.
 158      * @throws IOException error happen when writing file.
 159      */
 160     @Override
 161     public void error(SAXParseException e) throws SAXException {
 162         println("error: " + e.getMessage());
 163     }
 164 
 165     /**
 166      * Write fatalError tag along with exception to the file when meet
 167      * unrecoverable error event.
 168      * @throws IOException error happen when writing file.
 169      */
 170     @Override
 171     public void fatalError(SAXParseException e) throws SAXException {
 172         println("fatal error: ");
 173     }
 174 
 175     /**
 176      * Write warning tag along with exception to the file when meet warning event.
 177      * @throws IOException error happen when writing file.
 178      */
 179     @Override
 180     public void warning(SAXParseException e) throws SAXException {
 181         println("warning : ");
 182     }
 183 
 184     /**
 185      * Write ignorableWhitespace tag along with white spaces when meet
 186      * ignorableWhitespace event.
 187      * @throws IOException error happen when writing file.
 188      */
 189     @Override
 190     public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
 191         String s = new String(ch, start, length);
 192         println("ignorableWhitespace...\n" + s +
 193                 " ignorable white space string length: " + s.length());
 194     }
 195 
 196     /**
 197      * Write processingInstruction tag along with target name and target data
 198      * when meet processingInstruction event.
 199      * @throws IOException error happen when writing file.
 200      */
 201     @Override
 202     public void processingInstruction(String target, String data) throws SAXException {
 203         println("processingInstruction...target:" + target +
 204                         " data: " + data);
 205     }
 206 
 207     @Override
 208     public void setDocumentLocator(Locator locator) {
 209         try {
 210             println("setDocumentLocator...");
 211         } catch (SAXException ex) {
 212             System.err.println(WRITE_ERROR + ex);
 213         }
 214     }
 215 
 216     /**
 217      * Write skippedEntity tag along with entity name when meet skippedEntity
 218      * event.
 219      * @throws IOException error happen when writing file.
 220      */
 221     @Override
 222     public void skippedEntity(String name) throws SAXException {
 223         println("skippedEntity...\n" + "name: " + name);
 224     }
 225 
 226     /**
 227      * Write startDocument tag when meet startDocument event.
 228      * @throws IOException error happen when writing file.
 229      */
 230     @Override
 231     public void startDocument() throws SAXException {
 232         println("startDocument...");
 233     }
 234 
 235     /**
 236      * Write startElement tag along with namespaceURI, localName, qName, number
 237      * of attributes and line number when meet startElement event.
 238      * @throws IOException error happen when writing file.
 239      */
 240     @Override
 241     public void startElement(String namespaceURI, String localName,
 242                                         String qName, Attributes atts) throws SAXException {
 243         println("startElement...\n" + "namespaceURI: " +  namespaceURI +
 244                         " localName: " + localName +  " qName: " + qName +
 245                         " Number of Attributes: " + atts.getLength());
 246     }
 247 
 248     /**
 249      * Write startPrefixMapping tag along with prefix and uri when meet
 250      * startPrefixMapping event.
 251      * @throws IOException error happen when writing file.
 252      */
 253     @Override
 254     public void startPrefixMapping(String prefix, String uri) throws SAXException {
 255         println("startPrefixMapping...\n" + "prefix: " + prefix + " uri: " + uri);
 256     }
 257 
 258     /**
 259      * Write outString to file.
 260      * @param outString String to be written to File
 261      * @throws SAXException if write file failed
 262      */
 263     private void println(String outString) throws SAXException {
 264         try {
 265             bWriter.write( outString, 0, outString.length());
 266             bWriter.newLine();
 267         } catch (IOException ex) {
 268             throw new SAXException(WRITE_ERROR, ex);
 269         }
 270     }
 271 }