Java Code Examples for javax.xml.parsers.DocumentBuilderFactory.setValidating()

The following are Jave code examples for showing how to use setValidating() of the javax.xml.parsers.DocumentBuilderFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: L2J-Global   File: DocumentBase.java   View Source Code Vote up 6 votes
public Document parse()
{
	Document doc = null;
	try
	{
		final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		factory.setIgnoringComments(true);
		doc = factory.newDocumentBuilder().parse(_file);
		parseDocument(doc);
	}
	catch (Exception e)
	{
		_log.log(Level.SEVERE, "Error loading file " + _file, e);
	}
	return doc;
}
 
Example 2
Project: openjdk-jdk10   File: AuctionController.java   View Source Code Vote up 6 votes
/**
 * Check grammar caching with imported schemas.
 *
 * @throws Exception If any errors occur.
 * @see <a href="content/coins.xsd">coins.xsd</a>
 * @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
 */
@Test
public void testGetOwnerItemList() throws Exception {
    String xsdFile = XML_DIR + "coins.xsd";
    String xmlFile = XML_DIR + "coins.xml";

    try(FileInputStream fis = new FileInputStream(xmlFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
        dbf.setValidating(false);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File(((xsdFile))));

        MyErrorHandler eh = new MyErrorHandler();
        Validator validator = schema.newValidator();
        validator.setErrorHandler(eh);

        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document document = docBuilder.parse(fis);
        validator.validate(new DOMSource(document), new DOMResult());
        assertFalse(eh.isAnyError());
    }
}
 
Example 3
Project: openjdk-jdk10   File: XPathImplUtil.java   View Source Code Vote up 6 votes
/**
 * Parse the input source and return a Document.
 * @param source The {@code InputSource} of the document
 * @return a DOM Document
 * @throws XPathExpressionException if there is an error parsing the source.
 */
Document getDocument(InputSource source)
    throws XPathExpressionException {
    requireNonNull(source, "Source");
    try {
        // we'd really like to cache those DocumentBuilders, but we can't because:
        // 1. thread safety. parsers are not thread-safe, so at least
        //    we need one instance per a thread.
        // 2. parsers are non-reentrant, so now we are looking at having a
        // pool of parsers.
        // 3. then the class loading issue. The look-up procedure of
        //    DocumentBuilderFactory.newInstance() depends on context class loader
        //    and system properties, which may change during the execution of JVM.
        //
        // so we really have to create a fresh DocumentBuilder every time we need one
        // - KK
        DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(useServiceMechanism);
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        return dbf.newDocumentBuilder().parse(source);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new XPathExpressionException (e);
    }
}
 
Example 4
Project: openjdk-jdk10   File: Bug4966138.java   View Source Code Vote up 6 votes
@Test
public void test1() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
    dbf.setAttribute(SCHEMA_SOURCE, Bug4966138.class.getResource("test.xsd").toExternalForm());

    Document document = dbf.newDocumentBuilder().parse(Bug4966138.class.getResource("test.xml").toExternalForm());

    TypeInfo type = document.getDocumentElement().getSchemaTypeInfo();

    String typeName = type.getTypeName();
    System.out.println(typeName);
    Assert.assertNotNull(typeName);
    Assert.assertTrue(typeName.length() != 0, "returned typeName shouldn't be empty");

    String typeNs = type.getTypeNamespace();
    System.out.println(typeNs);
    Assert.assertNotNull(typeNs);
    Assert.assertTrue(typeNs.length() != 0, "returned typeNamespace shouldn't be empty");
}
 
Example 5
Project: vexillo   File: FlagParser.java   View Source Code Vote up 6 votes
public static Flag parse(String name, InputStream in) throws IOException {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(true); // make sure the XML is valid
		factory.setExpandEntityReferences(false); // don't allow custom entities
		DocumentBuilder builder = factory.newDocumentBuilder();
		builder.setEntityResolver(new KVXXEntityResolver());
		builder.setErrorHandler(new KVXXErrorHandler(name));
		Document document = builder.parse(new InputSource(in));
		return parseDocument(document);
	} catch (ParserConfigurationException pce) {
		throw new IOException(pce);
	} catch (SAXException saxe) {
		throw new IOException(saxe);
	}
}
 
Example 6
Project: L2J-Global   File: MerchantPriceConfigTable.java   View Source Code Vote up 5 votes
public void loadXML() throws SAXException, IOException, ParserConfigurationException
{
	final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setValidating(false);
	factory.setIgnoringComments(true);
	final File file = new File(Config.DATAPACK_ROOT + "/data/" + MPCS_FILE);
	if (file.exists())
	{
		int defaultPriceConfigId;
		final Document doc = factory.newDocumentBuilder().parse(file);
		
		Node n = doc.getDocumentElement();
		final Node dpcNode = n.getAttributes().getNamedItem("defaultPriceConfig");
		if (dpcNode == null)
		{
			throw new IllegalStateException("merchantPriceConfig must define an 'defaultPriceConfig'");
		}
		defaultPriceConfigId = Integer.parseInt(dpcNode.getNodeValue());
		
		MerchantPriceConfig mpc;
		for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
		{
			mpc = parseMerchantPriceConfig(n);
			if (mpc != null)
			{
				_mpcs.put(mpc.getId(), mpc);
			}
		}
		
		final MerchantPriceConfig defaultMpc = this.getMerchantPriceConfig(defaultPriceConfigId);
		if (defaultMpc == null)
		{
			throw new IllegalStateException("'defaultPriceConfig' points to an non-loaded priceConfig");
		}
		_defaultMpc = defaultMpc;
	}
}
 
Example 7
Project: joai-project   File: XMLDocReader.java   View Source Code Vote up 5 votes
/**
 *  Gets a org.w3c.dom.Document for this record. This method is optimized to create only one DOM when
 *  accessed multiple times for the same XMLDocReader.
 *
 * @return    A org.w3c.dom.Document, or null if unable to read.
 */
public org.w3c.dom.Document getW3CXmlDoc() {
	if (w3cXmlDoc != null)
		return w3cXmlDoc;

	DocumentBuilderFactory docfactory
		 = DocumentBuilderFactory.newInstance();
	docfactory.setCoalescing(true);
	docfactory.setExpandEntityReferences(true);
	docfactory.setIgnoringComments(true);

	docfactory.setNamespaceAware(true);

	// We must set validation false since jdk1.4 parser
	// doesn't know about schemas.
	docfactory.setValidating(false);

	// Ignore whitespace doesn't work unless setValidating(true),
	// according to javadocs.
	docfactory.setIgnoringElementContentWhitespace(false);
	try {
		DocumentBuilder docbuilder = docfactory.newDocumentBuilder();
		w3cXmlDoc = docbuilder.parse(getXml());
	} catch (Throwable e) {
		return null;
	}
	return w3cXmlDoc;
}
 
Example 8
Project: ciguan   File: AsXmlTool.java   View Source Code Vote up 5 votes
/**
 * Load XML resource.
 *
 * @param pResource the resource
 * @return the document
 * @throws Exception in case a problem occurred
 */
public static Document loadXmlResource(String pResource) throws Exception {

    String tResource = (pResource.startsWith("/") ? pResource.substring(1) : pResource);
    InputStream tStream = null;

    /**
     * Try own class loader first, then the system class loader
     */
    tStream = AsXmlTool.class.getClassLoader().getResourceAsStream(tResource);
    if (tStream == null) {
        tStream = ClassLoader.getSystemResourceAsStream(tResource);
    }
    if (tStream == null) {
        tStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(tResource);
    }        
    if (tStream == null) {
        throw new RuntimeException("Failed to locate module '" + pResource + "'");
    }
    
    DocumentBuilderFactory tFactory = DocumentBuilderFactory.newInstance();
    tFactory.setIgnoringComments(true);
    tFactory.setNamespaceAware(false); // No namespaces: this is default
    tFactory.setValidating(false); // Don't validate DTD: also default
    
    DocumentBuilder tParser = tFactory.newDocumentBuilder();
    
    return tParser.parse(tStream);
}
 
Example 9
Project: lams   File: DefaultDocumentLoader.java   View Source Code Vote up 5 votes
/**
 * Create the {@link DocumentBuilderFactory} instance.
 * @param validationMode the type of validation: {@link XmlValidationModeDetector#VALIDATION_DTD DTD}
 * or {@link XmlValidationModeDetector#VALIDATION_XSD XSD})
 * @param namespaceAware whether the returned factory is to provide support for XML namespaces
 * @return the JAXP DocumentBuilderFactory
 * @throws ParserConfigurationException if we failed to build a proper DocumentBuilderFactory
 */
protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
		throws ParserConfigurationException {

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(namespaceAware);

	if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
		factory.setValidating(true);
		if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
			// Enforce namespace aware for XSD...
			factory.setNamespaceAware(true);
			try {
				factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
			}
			catch (IllegalArgumentException ex) {
				ParserConfigurationException pcex = new ParserConfigurationException(
						"Unable to validate using XSD: Your JAXP provider [" + factory +
						"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
						"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
				pcex.initCause(ex);
				throw pcex;
			}
		}
	}

	return factory;
}
 
Example 10
Project: OpenJSharp   File: SAX2DOMEx.java   View Source Code Vote up 5 votes
/**
 * Creates a fresh empty DOM document and adds nodes under this document.
 * @deprecated
 */
public SAX2DOMEx() throws ParserConfigurationException {
    DocumentBuilderFactory factory = XmlFactory.createDocumentBuilderFactory(false);
    factory.setValidating(false);

    document = factory.newDocumentBuilder().newDocument();
    node = document;
    nodeStack.push(document);
}
 
Example 11
Project: openjdk-jdk10   File: PrettyPrintTest.java   View Source Code Vote up 5 votes
private Document toXmlDocument(String xmlString) throws Exception {
    InputSource xmlInputSource = new InputSource(new StringReader(xmlString));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    DocumentBuilder xmlDocumentBuilder = dbf.newDocumentBuilder();
    Document node = xmlDocumentBuilder.parse(xmlInputSource);
    return node;
}
 
Example 12
Project: DeskChan   File: PhrasesList.java   View Source Code Vote up 5 votes
public void load(){
	try {
		phrases.clear();
		DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
		f.setValidating(false);

		DocumentBuilder builder = f.newDocumentBuilder();
		InputStream inputStream = Files.newInputStream(packFile);
		Document doc = builder.parse(inputStream);
		inputStream.close();
		Node mainNode = doc.getChildNodes().item(0);
		NodeList list = mainNode.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			if (!list.item(i).getNodeName().equals("phrase")) continue;
			try {
				add(Phrase.create(list.item(i)));
			} catch (Exception e2) {
				Main.log(e2);
			}
		}
	} catch (Exception e) {
		Main.log("Error while parsing phrases file " + packName + ": " + e.getMessage());
		loaded = false;
		return;
	}
	loaded = true;
}
 
Example 13
Project: trashjam2017   File: InkscapeLoader.java   View Source Code Vote up 4 votes
/**
 * Load a SVG document into a diagram
 * 
 * @param in
 *            The input stream from which to read the SVG
 * @param offset
 *            Offset the diagram for the height of the document
 * @return The diagram loaded
 * @throws SlickException
 *             Indicates a failure to process the document
 */
private Diagram loadDiagram(InputStream in, boolean offset)
		throws SlickException {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory
				.newInstance();
		factory.setValidating(false);
		factory.setNamespaceAware(true);

		DocumentBuilder builder = factory.newDocumentBuilder();
		builder.setEntityResolver(new EntityResolver() {
			public InputSource resolveEntity(String publicId,
					String systemId) throws SAXException, IOException {
				return new InputSource(
						new ByteArrayInputStream(new byte[0]));
			}
		});

		Document doc = builder.parse(in);
		Element root = doc.getDocumentElement();

		String widthString = root.getAttribute("width");
		while (Character.isLetter(widthString
				.charAt(widthString.length() - 1))) {
			widthString = widthString.substring(0, widthString.length() - 1);
		}

		String heightString = root.getAttribute("height");
		while (Character.isLetter(heightString
				.charAt(heightString.length() - 1))) {
			heightString = heightString.substring(0,heightString.length() - 1);
		}

		float docWidth = Float.parseFloat(widthString);
		float docHeight = Float.parseFloat(heightString);

		diagram = new Diagram(docWidth, docHeight);
		if (!offset) {
			docHeight = 0;
		}
		loadChildren(root, Transform
				.createTranslateTransform(0, -docHeight));

		return diagram;
	} catch (Exception e) {
		throw new SlickException("Failed to load inkscape document", e);
	}
}
 
Example 14
Project: incubator-netbeans   File: ArchQuestionsTest.java   View Source Code Vote up 4 votes
public void testGenerateArchFileWhenEmptyWithDefaultAnswerForNbDepsQuestion() throws Exception {
    java.io.File answers = extractString ("");
    answers.delete ();
    assertFalse ("Really deleted", answers.exists ());

    java.io.File f = extractString (
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<project name=\"Test Arch\" basedir=\".\" default=\"all\" >" +
        "  <taskdef name=\"arch\" classname=\"org.netbeans.nbbuild.Arch\" classpath=\"${nbantext.jar}\"/>" +
        "  <arch answers=\"" + answers + "\" output=\"x.html\" />" +
        "<target name=\"all\" >" +
        "  " +
        "</target>" +
        "</project>"

    );
    execute (f, new String[] { });

    assertTrue ("File is generated", answers.exists ());
    
    String res = readFile(answers);
    DocumentBuilderFactory fack = DocumentBuilderFactory.newInstance();
    fack.setValidating(false);
    DocumentBuilder build = fack.newDocumentBuilder();
    build.setEntityResolver(this);
    org.w3c.dom.Document dom;
    try {
        dom = build.parse(answers);
    } catch (IOException ex) {
        throw new IOException(ex.getMessage() + "\n" + msg.toString(), ex);
    }

    org.w3c.dom.NodeList list = dom.getElementsByTagName("defaultanswer");
    assertTrue("There is at least one defaultanswer: " + res, list.getLength() > 0);
    BIGLOOP: for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node n = list.item(i);
        while (n != null) {
            n = n.getParentNode();
            assertNotNull ("No parent node answer found: " + res, n);
            
            if (n.getNodeName().equals ("answer")) {
                String id = n.getAttributes().getNamedItem("id").getNodeValue();
                if (id.equals ("dep-nb")) {
                    // ok, we were searching for answer to dep-nb question
                    return;
                }
                continue BIGLOOP;
            }
        }
    }
    
    fail ("dep-nb question should have a defaultanswer: " + res);
}
 
Example 15
Project: openjdk-jdk10   File: UserController.java   View Source Code Vote up 4 votes
/**
 * Checking conflicting namespaces and use renameNode and normalizeDocument.
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testAddUser() throws Exception {
    String resultFile = USER_DIR + "accountRole.out";
    String xmlFile = XML_DIR + "accountInfo.xml";

    // Copy schema for outputfile
    Files.copy(Paths.get(XML_DIR, "accountInfo.xsd"),
            Paths.get(USER_DIR, "accountInfo.xsd"),
            StandardCopyOption.REPLACE_EXISTING);
    MyErrorHandler eh = new MyErrorHandler();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(xmlFile);
    Element sell = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Sell").item(0);
    Element role = (Element) sell.getParentNode();

    Element buy = (Element) document.renameNode(sell, PORTAL_ACCOUNT_NS, "acc:Buy");
    role.appendChild(buy);

    DOMImplementationLS impl
            = (DOMImplementationLS) DOMImplementationRegistry
                    .newInstance().getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();


    try(FileOutputStream output = new FileOutputStream(resultFile)) {
        MyDOMOutput mydomoutput = new MyDOMOutput();
        mydomoutput.setByteStream(output);
        writer.write(document, mydomoutput);
    }

    docBuilder.parse(resultFile);
    assertFalse(eh.isAnyError());
}
 
Example 16
Project: jdk8u-jdk   File: Canonicalizer.java   View Source Code Vote up 4 votes
/**
 * This method tries to canonicalize the given bytes. It's possible to even
 * canonicalize non-wellformed sequences if they are well-formed after being
 * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
 *
 * @param inputBytes
 * @return the result of the canonicalization.
 * @throws CanonicalizationException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 */
public byte[] canonicalize(byte[] inputBytes)
    throws javax.xml.parsers.ParserConfigurationException,
    java.io.IOException, org.xml.sax.SAXException, CanonicalizationException {
    InputStream bais = new ByteArrayInputStream(inputBytes);
    InputSource in = new InputSource(bais);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

    dfactory.setNamespaceAware(true);

    // needs to validate for ID attribute normalization
    dfactory.setValidating(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    /*
     * for some of the test vectors from the specification,
     * there has to be a validating parser for ID attributes, default
     * attribute values, NMTOKENS, etc.
     * Unfortunately, the test vectors do use different DTDs or
     * even no DTD. So Xerces 1.3.1 fires many warnings about using
     * ErrorHandlers.
     *
     * Text from the spec:
     *
     * The input octet stream MUST contain a well-formed XML document,
     * but the input need not be validated. However, the attribute
     * value normalization and entity reference resolution MUST be
     * performed in accordance with the behaviors of a validating
     * XML processor. As well, nodes for default attributes (declared
     * in the ATTLIST with an AttValue but not specified) are created
     * in each element. Thus, the declarations in the document type
     * declaration are used to help create the canonical form, even
     * though the document type declaration is not retained in the
     * canonical form.
     */
    db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

    Document document = db.parse(in);
    return this.canonicalizeSubtree(document);
}
 
Example 17
Project: joai-project   File: XMLDoc.java   View Source Code Vote up 4 votes
/**
 *  Reads and parses the XML from the given source.
 */		
private final void doParseDoc(
	InputSource xmlSource,
	boolean validating,			// does parser validate
	boolean namespaceAware,		// is parser namespace aware
	boolean expandEntities)		// expand Entity refs
throws XMLException
{
	this.doc = null;

	if (bugs >= 1)
		prtln("getXmlDoc: systemid: \"" + systemid + "\"");
	DocumentBuilderFactory factory = null;
	try {
		factory = DocumentBuilderFactory.newInstance();
	} catch (FactoryConfigurationError fce) {
		mkerror("factory config error: " + fce);
	}

	factory.setValidating(validating);
	factory.setNamespaceAware(namespaceAware);
	factory.setExpandEntityReferences(expandEntities); // expand Entity rfs

	factory.setCoalescing(true);	// convert CDATA nodes to Text nodes
	factory.setIgnoringElementContentWhitespace(true);

	DocumentBuilder bldr = null;
	try {
		bldr = factory.newDocumentBuilder();
	} catch (ParserConfigurationException pce) {
		mkerror("parser config exc: " + pce);
	}

	SimpleErrorHandler simpleErrorHandler
		= new SimpleErrorHandler(errors, warnings);
	bldr.setErrorHandler(simpleErrorHandler);

	try {
		doc = bldr.parse(xmlSource);
	} catch (IOException ioe) {
		mkerror("Could not read xml doc file \"" + systemid
			 + "\"  exc: " + ioe.getMessage());
	} catch (SAXException sxe) {
		mkerror("Could not parse xml doc file \"" + systemid
			 + "\"  exc: " + sxe.getMessage());
	}
	hasErrors = simpleErrorHandler.hasErrors();
	hasWarnings = simpleErrorHandler.hasWarnings();
	///try{
	///	xmlSource.getByteStream().close();
	///}catch(Throwable e){}
	///xmlSource = null;
}
 
Example 18
Project: openjdk-jdk10   File: UserController.java   View Source Code Vote up 4 votes
/**
 * This will check if adoptNode works will adoptNode from
 * @see <a href="content/userInfo.xml">userInfo.xml</a>
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>. This is
 * adopting a node from the XML file which is validated by a DTD and
 * into an XML file which is validated by the schema This covers Row 5
 * for the table
 * http://javaweb.sfbay/~jsuttor/JSR206/jsr-206-html/ch03s05.html. Filed
 * bug 4893745 because there was a difference in behavior.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateUserAccount() throws Exception {
    String userXmlFile = XML_DIR + "userInfo.xml";
    String accountXmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(userXmlFile);
    Element user = (Element) document.getElementsByTagName("FirstName").item(0);
    // Set schema after parsing userInfo.xml. Otherwise it will conflict
    // with DTD validation.
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    DocumentBuilder docBuilder1 = dbf.newDocumentBuilder();
    docBuilder1.setErrorHandler(eh);
    Document accDocument = docBuilder1.parse(accountXmlFile);

    Element firstName = (Element) accDocument
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0);
    Element adoptedAccount = (Element) accDocument.adoptNode(user);

    Element parent = (Element) firstName.getParentNode();
    parent.replaceChild(adoptedAccount, firstName);

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();

    MyDOMOutput mydomoutput = new MyDOMOutput();
    mydomoutput.setByteStream(System.out);

    writer.write(document, mydomoutput);
    writer.write(accDocument, mydomoutput);

    assertFalse(eh.isAnyError());
}
 
Example 19
Project: openjdk-jdk10   File: DOMConfigurationTest.java   View Source Code Vote up 4 votes
/**
 * Equivalence class partitioning with state and input values orientation
 * for public void setParameter(String name, Object value) throws
 * DOMException, <br>
 * <b>pre-conditions</b>: The root element is not declared in the schema
 * specified by setting the 'schema-location' and the 'schema-type'
 * parameters., <br>
 * <b>name</b>: validate-if-schema <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: No error is reported
 */
@Test
public void testValidateIfSchema002() {
    DOMImplementation domImpl = null;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        domImpl = dbf.newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("test", "ns:undeclared_root", null);

    Element root = doc.getDocumentElement();
    root.appendChild(doc.createTextNode("xxx"));

    DOMConfiguration config = doc.getDomConfig();

    if (!config.canSetParameter("schema-location", test1_xsd_url) || !config.canSetParameter("schema-type", XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
        System.out.println("cannot set the parameters 'schema-location' and 'schema-type'" + " to 'DOMConfigurationTest.xsd' and '"
                + XMLConstants.W3C_XML_SCHEMA_NS_URI + "' respectively");
        return;
    }
    config.setParameter("schema-type", XMLConstants.W3C_XML_SCHEMA_NS_URI);
    config.setParameter("schema-location", test1_xsd_url);

    if (!config.canSetParameter("validate-if-schema", Boolean.TRUE)) {
        System.out.println("OK, setting the parameter 'validate-if-schema'" + " to true is not supported");
        return;
    }

    config.setParameter("validate-if-schema", Boolean.TRUE);
    TestHandler testHandler = new TestHandler();
    config.setParameter("error-handler", testHandler);
    doc.normalizeDocument();
    if (testHandler.getError() != null || null != testHandler.getFatalError()) {
        Assert.fail("unexpected error: " + testHandler.getFatalError() + "; " + testHandler.getError());
    }
    return; // Status.passed("OK");

}
 
Example 20
Project: wisp   File: ConfigParser.java   View Source Code Vote up 4 votes
/**
 * parse data
 *
 * @param xmlPath
 *
 * @return
 *
 * @throws Exception
 */
public static InitDbConfig parse(InputStream xmlPath) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");

    Document document = null;
    DocumentBuilder docBuilder = null;
    docBuilder = factory.newDocumentBuilder();
    DefaultHandler handler = new DefaultHandler();
    docBuilder.setEntityResolver(handler);
    docBuilder.setErrorHandler(handler);

    document = docBuilder.parse(xmlPath);

    List<String> schemaList = new ArrayList<>();
    List<String> dataList = new ArrayList<>();

    Element rootEl = document.getDocumentElement();
    NodeList children = rootEl.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node instanceof Element) {
            Element element = (Element) node;

            if (elementNameMatch(element, "initialize-database")) {

                schemaList = parseSchemaList(element);

            } else if (elementNameMatch(element, "initialize-data")) {

                dataList = parseDataList(element);
            }

        }
    }

    InitDbConfig initDbConfig = new InitDbConfig();
    initDbConfig.setDataFileList(dataList);
    initDbConfig.setSchemaFileList(schemaList);

    return initDbConfig;
}