1 /*
   2  * Copyright (c) 2014, 2016, 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 
  24 package dom.ls;
  25 
  26 import static org.w3c.dom.ls.DOMImplementationLS.MODE_SYNCHRONOUS;
  27 
  28 import java.io.IOException;
  29 import java.io.OutputStream;
  30 import java.io.StringReader;
  31 import java.io.Writer;
  32 
  33 import javax.xml.parsers.DocumentBuilder;
  34 import javax.xml.parsers.DocumentBuilderFactory;
  35 import javax.xml.parsers.ParserConfigurationException;
  36 
  37 import org.testng.Assert;
  38 import org.testng.annotations.Listeners;
  39 import org.testng.annotations.Test;
  40 import org.w3c.dom.DOMError;
  41 import org.w3c.dom.DOMErrorHandler;
  42 import org.w3c.dom.DOMImplementation;
  43 import org.w3c.dom.Document;
  44 import org.w3c.dom.ls.DOMImplementationLS;
  45 import org.w3c.dom.ls.LSException;
  46 import org.w3c.dom.ls.LSInput;
  47 import org.w3c.dom.ls.LSOutput;
  48 import org.w3c.dom.ls.LSParser;
  49 import org.w3c.dom.ls.LSSerializer;
  50 import org.xml.sax.InputSource;
  51 import org.xml.sax.SAXException;
  52 
  53 /*
  54  * @test
  55  * @bug 8080906 8114834
  56  * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
  57  * @run testng/othervm -DrunSecMngr=true dom.ls.LSSerializerTest
  58  * @run testng/othervm dom.ls.LSSerializerTest
  59  * @summary Test LSSerializer.
  60  */
  61 @Listeners({jaxp.library.BasePolicy.class})
  62 public class LSSerializerTest {
  63 
  64     class DOMErrorHandlerImpl implements DOMErrorHandler {
  65 
  66         boolean NoOutputSpecifiedErrorReceived = false;
  67 
  68         public boolean handleError(final DOMError error) {
  69             // consume "no-output-specified" errors
  70             if ("no-output-specified".equalsIgnoreCase(error.getType())) {
  71                 NoOutputSpecifiedErrorReceived = true;
  72                 return true;
  73             }
  74 
  75             // unexpected error
  76             Assert.fail("Unexpected Error Type: " + error.getType() + " @ (" + error.getLocation().getLineNumber() + ", "
  77                     + error.getLocation().getColumnNumber() + ")" + ", " + error.getMessage());
  78 
  79             return false;
  80         }
  81     }
  82 
  83     class Output implements LSOutput {
  84         public OutputStream getByteStream() {
  85             return null;
  86         }
  87 
  88         public void setByteStream(final OutputStream byteStream) {
  89         }
  90 
  91         public Writer getCharacterStream() {
  92             return null;
  93         }
  94 
  95         public void setCharacterStream(final Writer characterStream) {
  96         }
  97 
  98         public String getSystemId() {
  99             return null;
 100         }
 101 
 102         public void setSystemId(final String systemId) {
 103         }
 104 
 105         public String getEncoding() {
 106             return "UTF8";
 107         }
 108 
 109         public void setEncoding(final String encoding) {
 110         }
 111     }
 112 
 113     /*
 114      * @bug 8080906
 115      */
 116     @Test
 117     public void testDefaultLSSerializer() throws Exception {
 118         DOMImplementationLS domImpl = (DOMImplementationLS) DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
 119         LSSerializer lsSerializer = domImpl.createLSSerializer();
 120         Assert.assertTrue(lsSerializer.getClass().getName().endsWith("dom3.LSSerializerImpl"));
 121     }
 122 
 123     @Test
 124     public void testDOMErrorHandler() {
 125 
 126         final String XML_DOCUMENT = "<?xml version=\"1.0\"?>" + "<hello>" + "world" + "</hello>";
 127 
 128         StringReader stringReader = new StringReader(XML_DOCUMENT);
 129         InputSource inputSource = new InputSource(stringReader);
 130         Document doc = null;
 131         try {
 132             DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
 133             // LSSerializer defaults to Namespace processing
 134             // so parsing must also
 135             documentBuilderFactory.setNamespaceAware(true);
 136             DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
 137             doc = parser.parse(inputSource);
 138 
 139         } catch (Throwable e) {
 140             e.printStackTrace();
 141             Assert.fail(e.toString());
 142         }
 143 
 144         DOMImplementation impl = doc.getImplementation();
 145         DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
 146         LSSerializer writer = implLS.createLSSerializer();
 147 
 148         System.out.println("Serializer is: " + implLS.getClass().getName() + " " + implLS);
 149 
 150         DOMErrorHandlerImpl eh = new DOMErrorHandlerImpl();
 151         writer.getDomConfig().setParameter("error-handler", eh);
 152 
 153         boolean serialized = false;
 154         try {
 155             serialized = writer.write(doc, new Output());
 156 
 157             // unexpected success
 158             Assert.fail("Serialized without raising an LSException due to " + "'no-output-specified'.");
 159         } catch (LSException lsException) {
 160             // expected exception
 161             System.out.println("Expected LSException: " + lsException.toString());
 162             // continue processing
 163         }
 164 
 165         Assert.assertFalse(serialized, "Expected writer.write(doc, new Output()) == false");
 166 
 167         Assert.assertTrue(eh.NoOutputSpecifiedErrorReceived, "'no-output-specified' error was expected");
 168     }
 169 
 170     @Test
 171     public void testXML11() {
 172 
 173         /**
 174          * XML 1.1 document to parse.
 175          */
 176         final String XML11_DOCUMENT = "<?xml version=\"1.1\" encoding=\"UTF-16\"?>\n" + "<hello>" + "world" + "<child><children/><children/></child>"
 177                 + "</hello>";
 178 
 179         /**JDK-8035467
 180          * no newline in default output
 181          */
 182         final String XML11_DOCUMENT_OUTPUT =
 183                 "<?xml version=\"1.1\" encoding=\"UTF-16\"?>"
 184                 + "<hello>"
 185                 + "world"
 186                 + "<child><children/><children/></child>"
 187                 + "</hello>";
 188 
 189         // it all begins with a Document
 190         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
 191         DocumentBuilder documentBuilder = null;
 192         try {
 193             documentBuilder = documentBuilderFactory.newDocumentBuilder();
 194         } catch (ParserConfigurationException parserConfigurationException) {
 195             parserConfigurationException.printStackTrace();
 196             Assert.fail(parserConfigurationException.toString());
 197         }
 198         Document document = null;
 199 
 200         StringReader stringReader = new StringReader(XML11_DOCUMENT);
 201         InputSource inputSource = new InputSource(stringReader);
 202         try {
 203             document = documentBuilder.parse(inputSource);
 204         } catch (SAXException saxException) {
 205             saxException.printStackTrace();
 206             Assert.fail(saxException.toString());
 207         } catch (IOException ioException) {
 208             ioException.printStackTrace();
 209             Assert.fail(ioException.toString());
 210         }
 211 
 212         // query DOM Interfaces to get to a LSSerializer
 213         DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
 214         DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;
 215         LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
 216 
 217         System.out.println("Serializer is: " + lsSerializer.getClass().getName() + " " + lsSerializer);
 218 
 219         // get default serialization
 220         String defaultSerialization = lsSerializer.writeToString(document);
 221 
 222         System.out.println("XML 1.1 serialization = \"" + defaultSerialization + "\"");
 223 
 224         // output should == input
 225         Assert.assertEquals(XML11_DOCUMENT_OUTPUT, defaultSerialization, "Invalid serialization of XML 1.1 document: ");
 226     }
 227 
 228     /*
 229      * @bug 8114834 test entity reference, nested entity reference when entities
 230      * is true and false
 231      */
 232     @Test
 233     public void testEntityReference() throws Exception {
 234         final String XML_DOCUMENT = "<?xml version=\"1.1\" encoding=\"UTF-16\"?>\n" +
 235                 "<!DOCTYPE author [\n" +
 236                 " <!ENTITY name \"Jo Smith\">" +
 237                 " <!ENTITY name1 \"&name;\">" +
 238                 " <!ENTITY name2 \"&name1;\">" +
 239                 "<!ENTITY ele \"<aa><bb>text</bb></aa>\">" +
 240                 " <!ENTITY ele1 \"&ele;\">" +
 241                 " <!ENTITY ele2 \"&ele1;\">" +
 242                 " ]>" +
 243                 " <author><a>&name1;</a>" +
 244                 "<b>b &name2; &name1; b</b>" +
 245                 "<c> &name; </c>" +
 246                 "<d>&ele1;d</d>" +
 247                 "<e> &ele2;eee </e>" +
 248                 "<f>&lt;att&gt;</f>" +
 249                 "<g> &ele; g</g>" +
 250                 "<h>&ele2;</h></author>" ;
 251 
 252 
 253         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
 254         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
 255 
 256         DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
 257         DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;
 258 
 259         LSParser domParser = domImplementationLS.createLSParser(MODE_SYNCHRONOUS, null);
 260         domParser.getDomConfig().setParameter("entities", Boolean.TRUE);
 261 
 262         LSInput src = domImplementationLS.createLSInput();
 263         src.setStringData(XML_DOCUMENT);
 264         Document document = domParser.parse(src);
 265 
 266         LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
 267 
 268         lsSerializer.getDomConfig().setParameter("format-pretty-print", true);
 269         System.out.println("test with default entities is " + lsSerializer.getDomConfig().getParameter("entities"));
 270         Assert.assertEquals(lsSerializer.writeToString(document),
 271                 "<?xml version=\"1.1\" encoding=\"UTF-16\"?><!DOCTYPE author [ \n" +
 272                 "<!ENTITY name 'Jo Smith'>\n" +
 273                 "<!ENTITY name1 '&name;'>\n" +
 274                 "<!ENTITY name2 '&name1;'>\n" +
 275                 "<!ENTITY ele '<aa><bb>text</bb></aa>'>\n" +
 276                 "<!ENTITY ele1 '&ele;'>\n" +
 277                 "<!ENTITY ele2 '&ele1;'>\n" +
 278                 "]>\n" +
 279                 "<author>\n" +
 280                 "    <a>&name1;Jo Smith</a>\n" +
 281                 "    <b>b &name2;Jo Smith &name1;Jo Smith b</b>\n" +
 282                 "    <c> &name;Jo Smith </c>\n" +
 283                 "    <d>&ele1;d</d>\n" +
 284                 "    <e> &ele2;eee </e>\n" +
 285                 "    <f>&lt;att&gt;</f>\n" +
 286                 "    <g> &ele; g</g>\n" +
 287                 "    <h>&ele2;</h>\n" +
 288                 "</author>\n");
 289 
 290         lsSerializer.getDomConfig().setParameter("entities", Boolean.FALSE);
 291         System.out.println("test with entities is false");
 292         Assert.assertEquals(lsSerializer.writeToString(document),
 293                 "<?xml version=\"1.1\" encoding=\"UTF-16\"?><!DOCTYPE author [ \n" +
 294                 "<!ENTITY name 'Jo Smith'>\n" +
 295                 "<!ENTITY name1 '&name;'>\n" +
 296                 "<!ENTITY name2 '&name1;'>\n" +
 297                 "<!ENTITY ele '<aa><bb>text</bb></aa>'>\n" +
 298                 "<!ENTITY ele1 '&ele;'>\n" +
 299                 "<!ENTITY ele2 '&ele1;'>\n" +
 300                 "]>\n" +
 301                 "<author>\n" +
 302                 "    <a>&name;Jo Smith</a>\n" +
 303                 "    <b>b &name;Jo Smith &name;Jo Smith b</b>\n" +
 304                 "    <c> &name;Jo Smith </c>\n" +
 305                 "    <d>\n" +
 306                 "        <aa>\n" +
 307                 "            <bb>text</bb>\n" +
 308                 "        </aa>\n" +
 309                 "        d\n" +
 310                 "    </d>\n" +
 311                 "    <e>\n" +
 312                 "        <aa>\n" +
 313                 "            <bb>text</bb>\n" +
 314                 "        </aa>\n" +
 315                 "        eee \n" +
 316                 "    </e>\n" +
 317                 "    <f>&lt;att&gt;</f>\n" +
 318                 "    <g>\n" +
 319                 "        <aa>\n" +
 320                 "            <bb>text</bb>\n" +
 321                 "        </aa>\n" +
 322                 "         g\n" +
 323                 "    </g>\n" +
 324                 "    <h>\n" +
 325                 "        <aa>\n" +
 326                 "            <bb>text</bb>\n" +
 327                 "        </aa>\n" +
 328                 "    </h>\n" +
 329                 "</author>\n");
 330 
 331     }
 332 }