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

The following are Jave code examples for showing how to use newDocumentBuilder() 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: openjdk-jdk10   File: TransformerFactoryTest.java   View Source Code Vote up 7 votes
private static Document load(InputStream in) throws IOException {

        Document document = null;

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            document = db.parse(in);
        } catch (ParserConfigurationException parserConfigurationException) {
            parserConfigurationException.printStackTrace();
            Assert.fail(parserConfigurationException.toString());
        } catch (SAXException saxException) {
            saxException.printStackTrace();
            Assert.fail(saxException.toString());
        }

        return document;
    }
 
Example 2
Project: hadoop   File: TestHsWebServicesJobs.java   View Source Code Vote up 6 votes
@Test
public void testJobIdXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId)
        .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList job = dom.getElementsByTagName("job");
    verifyHsJobXML(job, appContext);
  }

}
 
Example 3
Project: doctemplate   File: DOCXMergeEngine.java   View Source Code Vote up 6 votes
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray()));
		XPathFactory xPathfactory = XPathFactory.newInstance();
		XPath xpath = xPathfactory.newXPath();
		XPathExpression expr = xpath.compile("Relationships/*");
		NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
		for (int i = 0; i < nodeList.getLength(); i++) {
			String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent();
			int idNum = Integer.parseInt(id.substring("rId".length()));
			this.maxRId = idNum > this.maxRId ? idNum : this.maxRId;
		}
		return this.maxRId;
	}
 
Example 4
Project: jaffa-framework   File: AbstractLoader.java   View Source Code Vote up 6 votes
/** Returns an XML Parser.
 * @return an XML Parser.
 * @throws ParserConfigurationException if any error occurs
 */
protected DocumentBuilder createParser() throws ParserConfigurationException {
    // Create a factory object for creating DOM parsers
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // Specifies that the parser produced by this factory will validate documents as they are parsed.
    factory.setValidating(false);

    // Now use the factory to create a DOM parser
    DocumentBuilder parser = factory.newDocumentBuilder();

    // Specifies the EntityResolver to resolve DTD used in XML documents
    parser.setEntityResolver(new DefaultEntityResolver());

    // Specifies the ErrorHandler to handle warning/error/fatalError conditions
    parser.setErrorHandler(new DefaultErrorHandler());

    return parser;
}
 
Example 5
Project: openjdk-jdk10   File: AuctionItemRepository.java   View Source Code Vote up 6 votes
/**
 * Use a DocumentBuilder to create a DOM object and see if Secure Processing
 * feature affects the entity expansion.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testEntityExpansionDOMPos() throws Exception  {
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(FEATURE_SECURE_PROCESSING, true);
    setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(10000));
    DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    dBuilder.setErrorHandler(eh);
    dBuilder.parse(ENTITY_XML);
    assertFalse(eh.isAnyError());
}
 
Example 6
Project: openjdk-jdk10   File: SAXTFactoryTest.java   View Source Code Vote up 6 votes
/**
 * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is
 * namespace awareness, DocumentBuilder parse xslt file as DOMSource.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase03() throws Exception {
    String outputFile = USER_DIR + "saxtf003.out";
    String goldFile = GOLDEN_DIR + "saxtf003GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document document = docBuilder.parse(new File(XSLT_FILE));
        Node node = (Node)document;
        DOMSource domSource= new DOMSource(node);

        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();
        TransformerHandler handler =
                    saxTFactory.newTransformerHandler(domSource);
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 7
Project: ascii_generate   File: GetEmoticons.java   View Source Code Vote up 5 votes
private void writeFile(String title, ArrayList<String> list) throws IOException, ParserConfigurationException, TransformerException {
    System.out.println("GetEmoticons.writeFile");
    System.out.println("title = " + title);
    System.out.println("list = " + list);
    if (title == null || list == null || list.isEmpty()) return;
    String fileName = title.replaceAll("\\W", "") + ".xml";
    File file = new File("C:\\github\\AsciiGenerator\\app\\src\\main\\assets\\emoticons\\" + fileName);
    if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    org.w3c.dom.Document document = documentBuilder.newDocument();
    org.w3c.dom.Element root = document.createElement("root");
    document.appendChild(root);

    org.w3c.dom.Element name = document.createElement("name");
    name.appendChild(document.createTextNode(title));
    root.appendChild(name);

    org.w3c.dom.Element data = document.createElement("data");

    for (String s : list) {
        org.w3c.dom.Element item = document.createElement("item");
        item.appendChild(document.createTextNode(s));
        data.appendChild(item);
    }
    root.appendChild(data);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult streamResult = new StreamResult(file);
    transformer.transform(domSource, streamResult);
}
 
Example 8
Project: Shopping-Cart-using-Web-Services   File: MyClientRest.java   View Source Code Vote up 5 votes
private void parseUserActionResponse(String xml){
	messageList = new ArrayList<String>();
	//get the factory
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	try {
		DocumentBuilder db = dbf.newDocumentBuilder();
		domARB = db.parse(new InputSource(new StringReader(xml)));
		domARB.getDocumentElement().normalize();
		NodeList nList = domARB.getElementsByTagName("messagetouser");
		messageList.clear();
		//put all message from server in a list
	    for (int temp = 0; temp < nList.getLength(); temp++) {
	        Node nNode = nList.item(temp);
	        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
	        	Element eElement = (Element) nNode; 
	        	messageList.add(eElement.getTextContent());
	        }
	    }
	    //catch total items returned from server
	    totalItem=domARB.getElementsByTagName("totalitem").item(0).getTextContent();
	    
	}catch(ParserConfigurationException pce) {			pce.printStackTrace();
	}catch(SAXException se) {							se.printStackTrace();
	}catch(IOException ioe) {							ioe.printStackTrace();
	}catch (Exception e){								e.printStackTrace();
	}
}
 
Example 9
Project: geomapapp   File: XML_Layer.java   View Source Code Vote up 5 votes
public static XML_Layer parse(InputStream in)
		throws ParserConfigurationException, SAXException, IOException {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setIgnoringComments(true);
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document dom = db.parse(in);

	Node root = getElement(dom, "Layers");
	XML_Layer layer = parseFolder(root);
	layer.name = "Basemaps";
	return layer;
}
 
Example 10
Project: OpenJSharp   File: DOMUtil.java   View Source Code Vote up 5 votes
/**
 * Creates a new DOM document.
 */
public static Document createDom() {
    synchronized (DOMUtil.class) {
        if (db == null) {
            try {
                DocumentBuilderFactory dbf = XmlUtil.newDocumentBuilderFactory();
                dbf.setNamespaceAware(true);
                db = dbf.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                throw new FactoryConfigurationError(e);
            }
        }
        return db.newDocument();
    }
}
 
Example 11
Project: openjdk-jdk10   File: DOMValidatorHelper.java   View Source Code Vote up 5 votes
/**
 * Sets up handler for <code>DOMResult</code>.
 */
private void setupDOMResultHandler(DOMSource source, DOMResult result) throws SAXException {
    // If there's no DOMResult, unset the validator handler
    if (result == null) {
        fDOMValidatorHandler = null;
        fSchemaValidator.setDocumentHandler(null);
        return;
    }
    final Node nodeResult = result.getNode();
    // If the source node and result node are the same use the DOMResultAugmentor.
    // Otherwise use the DOMResultBuilder.
    if (source.getNode() == nodeResult) {
        fDOMValidatorHandler = fDOMResultAugmentor;
        fDOMResultAugmentor.setDOMResult(result);
        fSchemaValidator.setDocumentHandler(fDOMResultAugmentor);
        return;
    }
    if (result.getNode() == null) {
        try {
            DocumentBuilderFactory factory = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ?
                                DocumentBuilderFactory.newInstance() : new DocumentBuilderFactoryImpl();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            result.setNode(builder.newDocument());
        }
        catch (ParserConfigurationException e) {
            throw new SAXException(e);
        }
    }
    fDOMValidatorHandler = fDOMResultBuilder;
    fDOMResultBuilder.setDOMResult(result);
    fSchemaValidator.setDocumentHandler(fDOMResultBuilder);
}
 
Example 12
Project: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   View Source Code Vote up 5 votes
public static void unsafeManualConfig1() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 13
Project: donut-nunit-adapter   File: NUnitAdapter.java   View Source Code Vote up 5 votes
Document extractDocument(String absolutePath) throws ParserConfigurationException, IOException, SAXException {

        //Get the DOM Builder Factory
        DocumentBuilderFactory factory =
                DocumentBuilderFactory.newInstance();

        //Get the DOM Builder
        DocumentBuilder builder = factory.newDocumentBuilder();

        //Load and Parse the XML document
        //document contains the complete XML as a Tree.
        return builder.parse(readXml(absolutePath));
    }
 
Example 14
Project: OpenJSharp   File: Canonicalizer.java   View Source Code Vote up 5 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 15
Project: openjdk-jdk10   File: TransformerTest.java   View Source Code Vote up 5 votes
/**
 * This tests set/get ErrorListener methods of Transformer.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void transformer04() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File(TEST_XSL));
    DOMSource domSource = new DOMSource(document);

    Transformer transformer = TransformerFactory.newInstance()
            .newTransformer(domSource);
    transformer.setErrorListener(new MyErrorListener());
    assertNotNull(transformer.getErrorListener());
    assertTrue(transformer.getErrorListener() instanceof MyErrorListener);
}
 
Example 16
Project: nCube-Thyme-Java   File: MqttClientRequestParser.java   View Source Code Vote up 5 votes
public static ArrayList<String> notificationParse(String xml) throws Exception {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();
	InputSource xmlSource = new InputSource();
	xmlSource.setCharacterStream(new StringReader(xml));
	Document document = builder.parse(xmlSource);
	
	String rqi = "";
	String content = "";
	String subr = "";
	
	NodeList rqiNodeList = document.getElementsByTagName("rqi");
	if (rqiNodeList.getLength() > 0 && rqiNodeList.item(0).getChildNodes().getLength() > 0) {
		Node rqiNode = rqiNodeList.item(0).getChildNodes().item(0);
		rqi = rqiNode.getNodeValue();
	}
	
	NodeList conNodeList = document.getElementsByTagName("con");
	if (conNodeList.getLength() > 0 && conNodeList.item(0).getChildNodes().getLength() > 0) {
		Node conNode = conNodeList.item(0).getChildNodes().item(0);
		content = conNode.getNodeValue();
	}
	NodeList surNodeList = document.getElementsByTagName("sur");
	if (surNodeList.getLength() > 0 && surNodeList.item(0).getChildNodes().getLength() > 0) {
		Node surNode = surNodeList.item(0).getChildNodes().item(0);
		subr = surNode.getNodeValue();
	}
	
	ArrayList<String> returnArray = new ArrayList<String>();
	returnArray.add(rqi);
	returnArray.add(content);
	returnArray.add(subr);
	
	return returnArray;
}
 
Example 17
Project: lams   File: UpdateWarTask.java   View Source Code Vote up 5 votes
/**
    * Parses the web xml into a Dom document
    * 
    * @throws org.apache.tools.ant.DeployException
    *             in case of errors
    * @return A DOM Document of the web xml
    */
   protected Document parseWebXml(final InputStream webXmlPath) throws DeployException {
try {
    //get application xml as dom doc
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(webXmlPath);
} catch (ParserConfigurationException pex) {
    throw new DeployException("Could not configure parser", pex);
} catch (SAXException saxex) {
    throw new DeployException("Error parsing web xml" + webXmlPath, saxex);
} catch (IOException ioex) {
    throw new DeployException("Error reading web xml" + webXmlPath, ioex);
}
   }
 
Example 18
Project: openjdk-jdk10   File: LSSerializerTest.java   View Source Code Vote up 4 votes
@Test
public void testDOMErrorHandler() {

    final String XML_DOCUMENT = "<?xml version=\"1.0\"?>" + "<hello>" + "world" + "</hello>";

    StringReader stringReader = new StringReader(XML_DOCUMENT);
    InputSource inputSource = new InputSource(stringReader);
    Document doc = null;
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // LSSerializer defaults to Namespace processing
        // so parsing must also
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
        doc = parser.parse(inputSource);

    } catch (Throwable e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }

    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer writer = implLS.createLSSerializer();

    System.out.println("Serializer is: " + implLS.getClass().getName() + " " + implLS);

    DOMErrorHandlerImpl eh = new DOMErrorHandlerImpl();
    writer.getDomConfig().setParameter("error-handler", eh);

    boolean serialized = false;
    try {
        serialized = writer.write(doc, new Output());

        // unexpected success
        Assert.fail("Serialized without raising an LSException due to " + "'no-output-specified'.");
    } catch (LSException lsException) {
        // expected exception
        System.out.println("Expected LSException: " + lsException.toString());
        // continue processing
    }

    Assert.assertFalse(serialized, "Expected writer.write(doc, new Output()) == false");

    Assert.assertTrue(eh.NoOutputSpecifiedErrorReceived, "'no-output-specified' error was expected");
}
 
Example 19
Project: SofaTime   File: Xml.java   View Source Code Vote up 3 votes
/**
 * Build XML document from string.
 *
 * @param xml String to build the XML document from
 * @return Built XML document
 * @throws IOException                  XML document cannot be created
 *                                      from XML string
 * @throws SAXException                 SAX error or warning
 * @throws ParserConfigurationException Serious configuration error
 */
public static Document buildDocFromString(final String xml) throws
        IOException, SAXException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xml)));
}
 
Example 20
Project: openjdk-jdk10   File: BaseParsingTest.java   View Source Code Vote up 3 votes
/**
 * @bug 8169450
 * This particular issue does not appear in DOM parsing since the spaces are
 * normalized during version detection. This test case then serves as a guard
 * against such an issue from occuring in the version detection.
 *
 * @param xml the test xml
 * @throws Exception if the parser fails to parse the xml
 */
@Test(dataProvider = "xmlDeclarations")
public void testWithDOM(String xml) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.parse(new InputSource(new StringReader(xml)));
}