1 /*
   2  * Copyright (c) 2015, 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 parsers;
  24 
  25 import java.io.IOException;
  26 import java.io.InputStream;
  27 import java.util.ArrayList;
  28 import java.util.List;
  29 import javax.xml.parsers.ParserConfigurationException;
  30 import javax.xml.parsers.SAXParser;
  31 import javax.xml.parsers.SAXParserFactory;
  32 import org.testng.Assert;
  33 import org.testng.annotations.Test;
  34 import org.xml.sax.Attributes;
  35 import org.xml.sax.SAXException;
  36 import org.xml.sax.helpers.DefaultHandler;
  37 
  38 /*
  39  * @bug 8136778
  40  * @summary This test verifies the stop and resume methods of the SAX parser
  41  * @author Joe Wang
  42  */
  43 public class SaxParserStop {
  44     //yep, we're only displaying two records per page
  45     static final int RECORD_PER_PAGE = 2;
  46     SAXParser parser = null;
  47     DataCollector dataCollector = null;
  48 
  49     @Test
  50     public void test() {
  51         InputStream xmlFile = getClass().getResourceAsStream("SaxParserStop.xml");
  52 
  53         int page;
  54         //Get content for page 1; The parser will be started and stopped after
  55         //collecting the required data.
  56         page = 1;
  57         List<String> content = getPage(xmlFile, page);
  58         Assert.assertEquals(2, content.size());
  59         Assert.assertEquals("The Martian", content.get(0));
  60         Assert.assertEquals("The Doll", content.get(1));
  61 
  62         //The parser will be resumed and stopped again after collecting page 2.
  63         page = 2;
  64         content = getPage(xmlFile, page);
  65         Assert.assertEquals(2, content.size());
  66         Assert.assertEquals("Transformer X", content.get(0));
  67         Assert.assertEquals("The Spaceship", content.get(1));
  68     }
  69 
  70     /**
  71      * Parses the xml and returns a list of toys.
  72      *
  73      * @param is the input stream
  74      * @return a list of toys
  75      */
  76     private List<String> getPage(InputStream is, int page) {
  77         if (parser == null) {
  78             parser = getParser();
  79         }
  80 
  81         try {
  82             if (page == 1) {
  83                 dataCollector = new DataCollector(parser, RECORD_PER_PAGE);
  84                 parser.parse(is, dataCollector);
  85             } else {
  86                 dataCollector.reset();
  87                 parser.resume();
  88             }
  89             return dataCollector.getContent();
  90         } catch (SAXException | IOException ex) {
  91             Assert.fail("Failed to parse the inputstream", ex);
  92         }
  93 
  94         return null;
  95     }
  96 
  97     /**
  98      * Returns an instance of SAXParser.
  99      * @return a SAXParser
 100      */
 101     private SAXParser getParser() {
 102         SAXParser p = null;
 103         try {
 104             SAXParserFactory spf = SAXParserFactory.newInstance();
 105             spf.setNamespaceAware(true);
 106             spf.setValidating(false);
 107             spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
 108             p = spf.newSAXParser();
 109         } catch (ParserConfigurationException | SAXException e) {
 110             Assert.fail("Failed to create a parser", e);
 111         }
 112         return p;
 113     }
 114 
 115     /**
 116      * This class is responsible for collecting names from a toys catalog.
 117      */
 118     class DataCollector extends DefaultHandler {
 119         List<String> toys = new ArrayList<>();
 120         int numOfRecord;
 121         int recordCount;
 122         String toyId;
 123         SAXParser parser;
 124         boolean inToy = false;
 125         boolean collectName = false;
 126 
 127         /**
 128          * Constructs a DataCollector instance with a parser.
 129          *
 130          * @param parser the SAX parser
 131          * @param num the number of records to be collected
 132          */
 133         public DataCollector(SAXParser parser, int num) {
 134             this.parser = parser;
 135             numOfRecord = num;
 136         }
 137 
 138         public List<String> getContent() {
 139             return new ArrayList<>(toys);
 140         }
 141 
 142         /**
 143          * Resets the collector to get data for the next page
 144          */
 145         public void reset() {
 146             toys.clear();
 147             recordCount = 0;
 148             toyId = null;
 149             inToy = false;
 150             collectName = false;
 151         }
 152 
 153         @Override
 154         public void startElement(String namespaceURI,
 155                 String localName,
 156                 String qName,
 157                 Attributes atts)
 158                 throws SAXException {
 159             if (inToy) {
 160                 if (localName.equals("name")) {
 161                     collectName = true;
 162                 }
 163             } else if (localName.equals("toy")) {
 164                 inToy = true;
 165                 String id = atts.getValue("id");
 166                 toyId = "toy" + id;
 167             }
 168         }
 169 
 170         @Override
 171         public void characters(char ch[], int start, int length)
 172                 throws SAXException {
 173             if (collectName) {
 174                 toys.add(new String(ch, start, length));
 175                 recordCount++;
 176                 collectName = false;
 177             }
 178         }
 179 
 180         /**
 181          * Handles endElement event
 182          */
 183         @Override
 184         public void endElement(String namespaceURI, String localName, String qName)
 185                 throws SAXException {
 186             if (inToy) {
 187                 if (localName.equals("toy")) {
 188                     inToy = false;
 189                     if (recordCount == numOfRecord) {
 190                         parser.stop();
 191                     }
 192                 }
 193             }
 194         }
 195     }
 196 }