1 /*
   2  * Copyright (c) 2003, 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 package test.auctionportal;
  24 
  25 import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
  26 import static jaxp.library.JAXPTestUtilities.bomStream;
  27 import static org.testng.Assert.assertEquals;
  28 import static org.testng.Assert.assertFalse;
  29 import static org.testng.Assert.assertTrue;
  30 import static test.auctionportal.HiBidConstants.JAXP_SCHEMA_LANGUAGE;
  31 import static test.auctionportal.HiBidConstants.JAXP_SCHEMA_SOURCE;
  32 import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS;
  33 import static test.auctionportal.HiBidConstants.XML_DIR;
  34 
  35 import java.io.File;
  36 import java.io.FileInputStream;
  37 import java.io.InputStream;
  38 import java.math.BigInteger;
  39 import java.nio.file.Paths;
  40 import java.util.GregorianCalendar;
  41 
  42 import javax.xml.datatype.DatatypeConstants;
  43 import javax.xml.datatype.DatatypeFactory;
  44 import javax.xml.datatype.Duration;
  45 import javax.xml.parsers.DocumentBuilder;
  46 import javax.xml.parsers.DocumentBuilderFactory;
  47 import javax.xml.parsers.SAXParser;
  48 import javax.xml.parsers.SAXParserFactory;
  49 import javax.xml.transform.dom.DOMResult;
  50 import javax.xml.transform.dom.DOMSource;
  51 import javax.xml.validation.Schema;
  52 import javax.xml.validation.SchemaFactory;
  53 import javax.xml.validation.Validator;
  54 
  55 import org.testng.annotations.Listeners;
  56 import org.testng.annotations.Test;
  57 import org.w3c.dom.Attr;
  58 import org.w3c.dom.DOMConfiguration;
  59 import org.w3c.dom.Document;
  60 import org.w3c.dom.Element;
  61 import org.w3c.dom.NodeList;
  62 import org.w3c.dom.TypeInfo;
  63 import org.w3c.dom.bootstrap.DOMImplementationRegistry;
  64 import org.w3c.dom.ls.DOMImplementationLS;
  65 import org.w3c.dom.ls.LSSerializer;
  66 
  67 /**
  68  * This is the user controller  class for the Auction portal HiBid.com.
  69  */
  70 /*
  71  * @test
  72  * @library /javax/xml/jaxp/libs
  73  * @run testng/othervm -DrunSecMngr=true test.auctionportal.AuctionController
  74  * @run testng/othervm test.auctionportal.AuctionController
  75  */
  76 @Listeners({jaxp.library.FilePolicy.class})
  77 public class AuctionController {
  78     /**
  79      * Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927
  80      * DOMConfiguration.setParameter("well-formed",true) throws an exception.
  81      *
  82      * @throws Exception If any errors occur.
  83      */
  84     @Test
  85     public void testCreateNewItem2Sell() throws Exception {
  86         String xmlFile = XML_DIR + "novelsInvalid.xml";
  87 
  88         Document document = DocumentBuilderFactory.newInstance()
  89                 .newDocumentBuilder().parse(xmlFile);
  90 
  91         document.getDomConfig().setParameter("well-formed", true);
  92 
  93         DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
  94         DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
  95         MyDOMOutput domOutput = new MyDOMOutput();
  96         domOutput.setByteStream(System.out);
  97         LSSerializer writer = impl.createLSSerializer();
  98         writer.write(document, domOutput);
  99     }
 100 
 101     /**
 102      * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
 103      * test throws DOM Level 1 node error.
 104      *
 105      * @throws Exception If any errors occur.
 106      */
 107     @Test
 108     public void testCreateNewItem2SellRetry() throws Exception  {
 109         String xmlFile = XML_DIR + "accountInfo.xml";
 110 
 111         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 112         dbf.setNamespaceAware(true);
 113         Document document = dbf.newDocumentBuilder().parse(xmlFile);
 114 
 115         DOMConfiguration domConfig = document.getDomConfig();
 116         MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
 117         domConfig.setParameter("error-handler", errHandler);
 118 
 119         DOMImplementationLS impl =
 120              (DOMImplementationLS) DOMImplementationRegistry.newInstance()
 121                      .getDOMImplementation("LS");
 122         LSSerializer writer = impl.createLSSerializer();
 123         MyDOMOutput domoutput = new MyDOMOutput();
 124 
 125         domoutput.setByteStream(System.out);
 126         writer.write(document, domoutput);
 127 
 128         document.normalizeDocument();
 129         writer.write(document, domoutput);
 130         assertFalse(errHandler.isError());
 131     }
 132 
 133     /**
 134      * Check if setting the attribute to be of type ID works. This will affect
 135      * the Attr.isID method according to the spec.
 136      *
 137      * @throws Exception If any errors occur.
 138      */
 139     @Test
 140     public void testCreateID() throws Exception {
 141         String xmlFile = XML_DIR + "accountInfo.xml";
 142 
 143         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 144         dbf.setNamespaceAware(true);
 145 
 146         Document document = dbf.newDocumentBuilder().parse(xmlFile);
 147         Element account = (Element)document
 148             .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
 149 
 150         account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true);
 151         Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID");
 152         assertTrue(aID.isId());
 153     }
 154 
 155     /**
 156      * Check the user data on the node.
 157      *
 158      * @throws Exception If any errors occur.
 159      */
 160     @Test
 161     public void testCheckingUserData() throws Exception {
 162         String xmlFile = XML_DIR + "accountInfo.xml";
 163 
 164         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 165         dbf.setNamespaceAware(true);
 166 
 167         DocumentBuilder docBuilder = dbf.newDocumentBuilder();
 168         Document document = docBuilder.parse(xmlFile);
 169 
 170         Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
 171         assertEquals(account.getNodeName(), "acc:Account");
 172         Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0);
 173         assertEquals(firstName.getNodeName(), "FirstName");
 174 
 175         Document doc1 = docBuilder.newDocument();
 176         Element someName = doc1.createElement("newelem");
 177 
 178         someName.setUserData("mykey", "dd",
 179             (operation, key,  data, src,  dst) ->  {
 180                 System.err.println("In UserDataHandler" + key);
 181                 System.out.println("In UserDataHandler");
 182             });
 183         Element impAccount = (Element)document.importNode(someName, true);
 184         assertEquals(impAccount.getNodeName(), "newelem");
 185         document.normalizeDocument();
 186         String data = (someName.getUserData("mykey")).toString();
 187         assertEquals(data, "dd");
 188     }
 189 
 190 
 191     /**
 192      * Check the UTF-16 XMLEncoding xml file.
 193      *
 194      * @throws Exception If any errors occur.
 195      * @see <a href="content/movies.xml">movies.xml</a>
 196      */
 197     @Test
 198     public void testCheckingEncoding() throws Exception {
 199         // Note since movies.xml is UTF-16 encoding. We're not using stanard XML
 200         // file suffix.
 201         String xmlFile = XML_DIR + "movies.xml.data";
 202 
 203         try (InputStream source = bomStream("UTF-16", xmlFile)) {
 204             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 205             dbf.setNamespaceAware(true);
 206             Document document = dbf.newDocumentBuilder().parse(source);
 207             assertEquals(document.getXmlEncoding(), "UTF-16");
 208             assertEquals(document.getXmlStandalone(), true);
 209         }
 210     }
 211 
 212     /**
 213      * Check validation API features. A schema which is including in Bug 4909119
 214      * used to be testing for the functionalities.
 215      *
 216      * @throws Exception If any errors occur.
 217      * @see <a href="content/userDetails.xsd">userDetails.xsd</a>
 218      */
 219     @Test
 220     public void testGetOwnerInfo() throws Exception {
 221         String schemaFile = XML_DIR + "userDetails.xsd";
 222         String xmlFile = XML_DIR + "userDetails.xml";
 223 
 224         try(FileInputStream fis = new FileInputStream(xmlFile)) {
 225             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 226             dbf.setNamespaceAware(true);
 227             dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
 228 
 229             SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
 230             Schema schema = schemaFactory.newSchema(Paths.get(schemaFile).toFile());
 231 
 232             Validator validator = schema.newValidator();
 233             MyErrorHandler eh = new MyErrorHandler();
 234             validator.setErrorHandler(eh);
 235 
 236             DocumentBuilder docBuilder = dbf.newDocumentBuilder();
 237             docBuilder.setErrorHandler(eh);
 238 
 239             Document document = docBuilder.parse(fis);
 240             DOMResult dResult = new DOMResult();
 241             DOMSource domSource = new DOMSource(document);
 242             validator.validate(domSource, dResult);
 243             assertFalse(eh.isAnyError());
 244         }
 245     }
 246 
 247     /**
 248      * Check grammar caching with imported schemas.
 249      *
 250      * @throws Exception If any errors occur.
 251      * @see <a href="content/coins.xsd">coins.xsd</a>
 252      * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
 253      */
 254     @Test
 255     public void testGetOwnerItemList() throws Exception {
 256         String xsdFile = XML_DIR + "coins.xsd";
 257         String xmlFile = XML_DIR + "coins.xml";
 258 
 259         try(FileInputStream fis = new FileInputStream(xmlFile)) {
 260             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 261             dbf.setNamespaceAware(true);
 262             dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
 263             dbf.setValidating(false);
 264 
 265             SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
 266             Schema schema = schemaFactory.newSchema(new File(((xsdFile))));
 267 
 268             MyErrorHandler eh = new MyErrorHandler();
 269             Validator validator = schema.newValidator();
 270             validator.setErrorHandler(eh);
 271 
 272             DocumentBuilder docBuilder = dbf.newDocumentBuilder();
 273             Document document = docBuilder.parse(fis);
 274             validator.validate(new DOMSource(document), new DOMResult());
 275             assertFalse(eh.isAnyError());
 276         }
 277     }
 278 
 279 
 280     /**
 281      * Check for the same imported schemas but will use SAXParserFactory and try
 282      * parsing using the SAXParser. SCHEMA_SOURCE attribute is using for this
 283      * test.
 284      *
 285      * @throws Exception If any errors occur.
 286      * @see <a href="content/coins.xsd">coins.xsd</a>
 287      * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
 288      */
 289 
 290     @Test
 291     public void testGetOwnerItemList1() throws Exception {
 292         String xsdFile = XML_DIR + "coins.xsd";
 293         String xmlFile = XML_DIR + "coins.xml";
 294         SAXParserFactory spf = SAXParserFactory.newInstance();
 295         spf.setNamespaceAware(true);
 296         spf.setValidating(true);
 297 
 298         SAXParser sp = spf.newSAXParser();
 299         sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
 300         sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile);
 301 
 302         MyErrorHandler eh = new MyErrorHandler();
 303         sp.parse(new File(xmlFile), eh);
 304         assertFalse(eh.isAnyError());
 305     }
 306 
 307     /**
 308      * Check usage of javax.xml.datatype.Duration class.
 309      *
 310      * @throws Exception If any errors occur.
 311      */
 312     @Test
 313     public void testGetItemDuration() throws Exception {
 314         String xmlFile = XML_DIR + "itemsDuration.xml";
 315 
 316         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 317         dbf.setNamespaceAware(true);
 318         Document document = dbf.newDocumentBuilder().parse(xmlFile);
 319 
 320         Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0);
 321 
 322         NodeList childList = durationElement.getChildNodes();
 323 
 324         for (int i = 0; i < childList.getLength(); i++) {
 325             System.out.println("child " + i + childList.item(i));
 326         }
 327 
 328         Duration duration = DatatypeFactory.newInstance().newDuration("P365D");
 329         Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue());
 330         assertFalse(sellDuration.isShorterThan(duration));
 331         assertFalse(sellDuration.isLongerThan(duration));
 332         assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365));
 333         assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration);
 334 
 335         Duration myDuration = sellDuration.add(duration);
 336         assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)),
 337                 DatatypeFactory.newInstance().newDuration("P730D"));
 338     }
 339 
 340     /**
 341      * Check usage of TypeInfo interface introduced in DOM L3.
 342      *
 343      * @throws Exception If any errors occur.
 344      */
 345     @Test
 346     public void testGetTypeInfo() throws Exception {
 347         String xmlFile = XML_DIR + "accountInfo.xml";
 348 
 349         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 350         dbf.setNamespaceAware(true);
 351         dbf.setValidating(true);
 352         dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
 353 
 354         DocumentBuilder docBuilder = dbf.newDocumentBuilder();
 355         docBuilder.setErrorHandler(new MyErrorHandler());
 356 
 357         Document document = docBuilder.parse(xmlFile);
 358         Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0);
 359         TypeInfo typeInfo = userId.getSchemaTypeInfo();
 360         assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger"));
 361         assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI));
 362 
 363         Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0);
 364         TypeInfo roletypeInfo = role.getSchemaTypeInfo();
 365         assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell"));
 366         assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS));
 367     }
 368 }
 369 
 370