Java Code Examples for javax.xml.parsers.DocumentBuilder.parse()

The following are Jave code examples for showing how to use parse() of the javax.xml.parsers.DocumentBuilder 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: Hydrograph   File: ExternalOperationExpressionUtil.java   View Source Code Vote up 9 votes
/**
 *Converts xml-stream into its equivalent jaxb object
 * 
 * @param xmlInputStream
 * @param type
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws JAXBException
 */
public Object unmarshal(InputStream xmlInputStream, Class<?> type)
		throws ParserConfigurationException, SAXException, IOException, JAXBException {
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		builderFactory.setExpandEntityReferences(false);
		builderFactory.setNamespaceAware(true);
		builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true);
		DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
		Document document = documentBuilder.parse(xmlInputStream);
		JAXBContext jaxbContext = JAXBContext.newInstance(type);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		return jaxbUnmarshaller.unmarshal(document);
}
 
Example 2
Project: hadoop   File: TestRMWebServicesNodes.java   View Source Code Vote up 6 votes
@Test
public void testNodes2XML() throws JSONException, Exception {
  rm.start();
  WebResource r = resource();
  rm.registerNode("h1:1234", 5120);
  rm.registerNode("h2:1235", 5121);
  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("nodes").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 nodesApps = dom.getElementsByTagName("nodes");
  assertEquals("incorrect number of elements", 1, nodesApps.getLength());
  NodeList nodes = dom.getElementsByTagName("node");
  assertEquals("incorrect number of elements", 2, nodes.getLength());
  rm.stop();
}
 
Example 3
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   View Source Code Vote up 6 votes
/**
 * Test for the isIgnoringElementContentWhitespace and the
 * setIgnoringElementContentWhitespace. The xml file has all kinds of
 * whitespace,tab and newline characters, it uses the MyNSContentHandler
 * which does not invoke the characters callback when this
 * setIgnoringElementContentWhitespace is set to true.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckElementContentWhitespace() throws Exception {
    String goldFile = GOLDEN_DIR + "dbfactory02GF.out";
    String outputFile = USER_DIR + "dbfactory02.out";
    MyErrorHandler eh = MyErrorHandler.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    assertFalse(dbf.isIgnoringElementContentWhitespace());
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(eh);
    Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml"));
    assertFalse(eh.isErrorOccured());
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer transformer = tfactory.newTransformer();
    SAXResult saxResult = new SAXResult();
    try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) {
        saxResult.setHandler(handler);
        transformer.transform(domSource, saxResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 4
Project: beaker-notebook-archive   File: SVGContainer.java   View Source Code Vote up 6 votes
private static Document validateData(Object data, DocumentBuilder builder) throws SAXException, IOException {
  Document doc;
  if(data instanceof String) {
    String path = data.toString();
    if (isValidURL(path)) {
      doc = builder.parse(new URL(path).openStream());
    } else if (exists(path)) {
      doc = builder.parse(path);
    } else {
      throw new FileNotFoundException(path + " doesn't exist. ");
    }
  } else {
    doc = builder.parse(new ByteArrayInputStream((byte[])data));
  }
  return doc;
}
 
Example 5
Project: IPPR2016   File: GenerateOWLServiceImpl.java   View Source Code Vote up 6 votes
private Node getOWLSkeleton(Document doc, DocumentBuilder builder) throws IOException, SAXException {
  String skeleton = "<?xml version=\"1.0\"?>" +
          "" +
          "<rdf:RDF xmlns:abstract-pass-ont=\"http://www.imi.kit.edu/abstract-pass-ont#\" xmlns:standard-pass-ont=\"http://www.i2pm.net/standard-pass-ont#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" xmlns=\"" + ontologyUri + "\">" +
          "	<owl:Ontology rdf:about=\""+ontologyUri+"\">" +
          "       <owl:versionIRI rdf:resource=\""+ontologyUri+"\"></owl:versionIRI>" +
          "		<owl:imports rdf:resource=\"http://www.imi.kit.edu/abstract-pass-ont\"></owl:imports>" +
          "		<owl:imports rdf:resource=\"http://www.i2pm.net/standard-pass-ont\"></owl:imports>" +
          "	</owl:Ontology>" +
          "</rdf:RDF>";

  Document doc2 = builder.parse(new ByteArrayInputStream(skeleton.getBytes()));
  Node node = doc.importNode(doc2.getDocumentElement(), true);
  doc.appendChild(node);
  return node;
}
 
Example 6
Project: openjdk-jdk10   File: Bug6849942Test.java   View Source Code Vote up 6 votes
@Test
public void testWProlog() throws Exception {
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream("<?xml version=\"1.1\" encoding=\"UTF-8\"?><?xmltarget foo?><test></test>".getBytes());
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder xmlParser = factory.newDocumentBuilder();
        // DOMParser p = new DOMParser();
        Document document = xmlParser.parse(new InputSource(bais));
        String result = ((ProcessingInstruction) document.getFirstChild()).getData();
        System.out.println(result);
        if (!result.equalsIgnoreCase("foo")) {
            Assert.fail("missing PI data");
        }
    } catch (Exception e) {
    }
}
 
Example 7
Project: openjdk-jdk10   File: Bug4971605.java   View Source Code Vote up 6 votes
@Test
public void test1() throws Exception {
    String xsd = "<?xml version='1.0'?>\n" + "<schema xmlns='http://www.w3.org/2001/XMLSchema'\n" + "        xmlns:test='jaxp13_test1'\n"
            + "        targetNamespace='jaxp13_test1'\n" + "        elementFormDefault='qualified'>\n" + "    <element name='test'/>\n" + "</schema>\n";

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Node document = docBuilder.parse(new InputSource(new StringReader(xsd)));
    Assert.assertNotNull(document);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory.newSchema(new Source[] { new DOMSource(document) });
    Assert.assertNotNull(schema, "Failed: newSchema returned null.");
}
 
Example 8
Project: fc-java-sdk   File: XmlUtils.java   View Source Code Vote up 6 votes
public static Document getDocument(InputSource xml, InputStream xsd)
    throws ParserConfigurationException, SAXException, IOException {
    Document doc = null;

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        if (xsd != null) {
            dbf.setNamespaceAware(true);
        }

        DocumentBuilder builder = dbf.newDocumentBuilder();
        doc = builder.parse(xml);

        if (xsd != null) {
            validateXml(doc, xsd);
        }
    } finally {
        closeStream(xml.getByteStream());
    }

    return doc;
}
 
Example 9
Project: swallow-core   File: DocumentParserTest.java   View Source Code Vote up 5 votes
@Test
    public void parseText() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "<return_msg><![CDATA[OK]]></return_msg>\n" +
                    "<appid><![CDATA[wxa2dfabf4a3c52551]]></appid>\n" +
                    "<mch_id><![CDATA[1346733401]]></mch_id>\n" +
                    "<nonce_str><![CDATA[8q3K40bL86nhv4Vp]]></nonce_str>\n" +
                    "<sign><![CDATA[124A01D6ADF83B0D4048398F5E848A97]]></sign>\n" +
                    "<result_code><![CDATA[SUCCESS]]></result_code>\n" +
                    "<prepay_id><![CDATA[wx20170413154005a6b42d4ccd0214498848]]></prepay_id>\n" +
                    "<trade_type><![CDATA[NATIVE]]></trade_type>\n" +
                    "<code_url><![CDATA[weixin://wxpay/bizpayurl?pr=h3ZzLPU]]></code_url>\n" +
                    "</xml>";

            InputSource inputSource = new InputSource(new StringReader(data));

            Document document = builder.parse(inputSource);
            System.out.println(DocumentUtil.getText(document,"return_code"));
//            Element root = document.getDocumentElement();
//            System.out.println(root.getNodeName());
//            NodeList nodeList = root.getChildNodes();
//            for (int i = 0; i < nodeList.getLength(); i++) {
//                Node item = nodeList.item(i);
//                if (item instanceof Element) {
//                    System.out.println(item.getNodeName() + "=" + item.getTextContent());
//                }
//            }

        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
 
Example 10
Project: warrior-jenkins-plugin   File: WarriorPluginBuilder.java   View Source Code Vote up 5 votes
/**
 * Private method to get the values given in warriorframework
 * tag of warhorn config file
 *
 * @param build Build
 * @param workspace Jenkins job workspace
 * @param listener Task listener
 * @return cloneDetails Details required to clone warriorframework
 * @throws ParserConfigurationException ParserConfigurationException
 * @throws SAXException SAXException
 * @throws IOException IOException
 */
private String[] getWfCloneDetails(Run<?,?> build, FilePath workspace, TaskListener listener)
        throws ParserConfigurationException, SAXException, IOException{

    String absWarhornConfig = "";
    String[] cloneDetails = new String[4];
    if (configType.equals("configGit")){
        absWarhornConfig = workspace.getRemote() + "/configRepo/" + gitConfigFile;
    } else {
        absWarhornConfig = workspace.getRemote() + "/warhorn_config.xml";
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File(absWarhornConfig));
    NodeList wfNodeList = document.getElementsByTagName("warriorframework");
    String url = "";
    String branch = "";
    if(wfNodeList.getLength() > 0){
        Element element = (Element) wfNodeList.item(0);
        url = element.getAttribute("url");
        branch = element.getAttribute("label");
    }
    if (url.isEmpty()){
        url = "https://github.com/warriorframework/warriorframework.git";
    }
    if (branch.isEmpty()){
        branch = "origin/develop";
    }

    // Temp_fix: Using the username & password given for cloning warhorn config file.
    // These will be empty/default if not provided for warhorn config file
    cloneDetails[0] = this.gitConfigUname;
    cloneDetails[1] = this.gitConfigPwd;
    cloneDetails[2] = url;
    cloneDetails[3] = branch;

    return cloneDetails;
}
 
Example 11
Project: hadoop   File: TestRMWebServices.java   View Source Code Vote up 5 votes
public void verifySchedulerFifoXML(String xml) throws JSONException,
    Exception {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  Document dom = db.parse(is);
  NodeList nodesSched = dom.getElementsByTagName("scheduler");
  assertEquals("incorrect number of elements", 1, nodesSched.getLength());
  NodeList nodes = dom.getElementsByTagName("schedulerInfo");
  assertEquals("incorrect number of elements", 1, nodes.getLength());

  for (int i = 0; i < nodes.getLength(); i++) {
    Element element = (Element) nodes.item(i);

    verifyClusterSchedulerFifoGeneric(
        WebServicesTestUtils.getXmlAttrString(element, "xsi:type"),
        WebServicesTestUtils.getXmlString(element, "qstate"),
        WebServicesTestUtils.getXmlFloat(element, "capacity"),
        WebServicesTestUtils.getXmlFloat(element, "usedCapacity"),
        WebServicesTestUtils.getXmlInt(element, "minQueueMemoryCapacity"),
        WebServicesTestUtils.getXmlInt(element, "maxQueueMemoryCapacity"),
        WebServicesTestUtils.getXmlInt(element, "numNodes"),
        WebServicesTestUtils.getXmlInt(element, "usedNodeCapacity"),
        WebServicesTestUtils.getXmlInt(element, "availNodeCapacity"),
        WebServicesTestUtils.getXmlInt(element, "totalNodeCapacity"),
        WebServicesTestUtils.getXmlInt(element, "numContainers"));
  }
}
 
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: ats-framework   File: XmlUtilities.java   View Source Code Vote up 5 votes
/**
 *
 * @param xmlString xml string
 * @return xml Document object
 * @throws XmlUtilitiesException
 */
public static Document stringToXmlDocumentObj( String xmlString ) throws XmlUtilitiesException {

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(new ByteArrayInputStream(xmlString.getBytes()));
    } catch (Exception e) {
        throw new XmlUtilitiesException("Error transforming String to XML document", e);
    }
}
 
Example 14
Project: vind   File: SolrSchemaChecker.java   View Source Code Vote up 5 votes
public static void checkSchema(Path solrSchemaPath, SchemaResponse response) throws IOException, SchemaValidationException {
    // read the local schema.xml
    final Document local;
    try (InputStream xml = Files.newInputStream(solrSchemaPath, StandardOpenOption.READ)) {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        final DocumentBuilder builder = factory.newDocumentBuilder();

        local = builder.parse(xml);
    } catch (ParserConfigurationException | SAXException e) {
        log.error("Error checking schema.xml: {}", e.getMessage(), e);
        throw new IOException(e);
    }

    final SchemaRepresentation remote = response.getSchemaRepresentation();
    final Element schema = local.getDocumentElement();
    // check the field-types
    final NodeList fieldTypes = schema.getElementsByTagName("fieldType");
    final Set<String> fieldTypeNames = remote.getFieldTypes().stream()
            .map(FieldTypeDefinition::getAttributes)
            .map(m -> m.get("name"))
            .filter(Objects::nonNull)
            .map(String::valueOf)
            .collect(Collectors.toSet());
    for (int i = 0; i < fieldTypes.getLength(); i++) {
        final Node fieldType = fieldTypes.item(i);
        final String fieldTypeName = fieldType.getAttributes().getNamedItem("name").getNodeValue();
        if (! fieldTypeNames.contains(fieldTypeName)) {
            throw new SchemaValidationException(String.format("Missing <fieldType name='%s' />", fieldTypeName));
        }
    }

    // TODO: check local -> remote.

}
 
Example 15
Project: aws-sdk-java-v2   File: XpathUtils.java   View Source Code Vote up 5 votes
/**
 * This method closes the given input stream upon completion.
 */
public static Document documentFrom(InputStream is)
        throws SAXException, IOException, ParserConfigurationException {
    is = new NamespaceRemovingInputStream(is);
    // DocumentBuilderFactory is not thread safe
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // ensure that parser writes error/warning messages to the logger
    // rather than stderr
    builder.setErrorHandler(ERROR_HANDLER);
    Document doc = builder.parse(is);
    is.close();
    return doc;
}
 
Example 16
Project: Cognizant-Intelligent-Test-Scripter   File: XMLOperation.java   View Source Code Vote up 5 votes
public static Document initTreeOp(String xmlPath) {
    try {
        if (new File(xmlPath).exists()) {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            return docBuilder.parse(xmlPath);
        }
    } catch (ParserConfigurationException | SAXException | IOException ex) {
        Logger.getLogger(XMLOperation.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
 
Example 17
Project: r2-streamer-java   File: EpubParser.java   View Source Code Vote up 5 votes
private String containerXmlParser(String containerData) throws EpubParserException {           //parsing container.xml
    try {
        String xml = containerData.replaceAll("[^\\x20-\\x7e]", "").trim();         //in case encoding problem

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xml)));
        document.getDocumentElement().normalize();
        if (document == null) {
            throw new EpubParserException("Error while parsing container.xml");
        }

        Element rootElement = (Element) ((Element) document.getDocumentElement().getElementsByTagName("rootfiles").item(0)).getElementsByTagName("rootfile").item(0);
        if (rootElement != null) {
            String opfFile = rootElement.getAttribute("full-path");
            if (opfFile == null) {
                throw new EpubParserException("Missing root file element in container.xml");
            }

            //Log.d(TAG, "Root file: " + opfFile);
            return opfFile;                    //returns opf file
        }
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 18
Project: jforgame   File: XmlUtils.java   View Source Code Vote up 5 votes
public static Document loadConfigFile(String cfgFile) {
	Document dom = null;
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		dom = db.parse(cfgFile);
	} catch (ParserConfigurationException | SAXException pce) {
		logger.error("Parse xml config file error.", pce);
	} catch (IOException ioe) {
		ioe.printStackTrace();
		logger.error("Can't open configuration file.", ioe);
	}
	return dom;
}
 
Example 19
Project: hadoop-oss   File: Configuration.java   View Source Code Vote up 5 votes
private Document parse(DocumentBuilder builder, InputStream is,
    String systemId) throws IOException, SAXException {
  if (!quietmode) {
    LOG.debug("parsing input stream " + is);
  }
  if (is == null) {
    return null;
  }
  try {
    return (systemId == null) ? builder.parse(is) : builder.parse(is,
        systemId);
  } finally {
    is.close();
  }
}
 
Example 20
Project: Compiler   File: GParser.java   View Source Code Vote up 5 votes
private void readXMLFile(String iXMLFile) {
    try {
        File fXMLFile = new File(iXMLFile);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(fXMLFile);

        //  http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        document.getDocumentElement().normalize();

        System.out.println("Root element: " + document.getDocumentElement().getNodeName());

        NodeList nodeList = document.getElementsByTagName("token");

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                int tokenNumber = Integer.parseInt(element.getElementsByTagName("number").item(0).getTextContent());
                System.out.println("Word #"+tokenNumber);
                String isValidStr = element.getElementsByTagName("valid").item(0).getTextContent();
                boolean isValid = Boolean.parseBoolean(isValidStr);
                String typeStr = element.getElementsByTagName("type").item(0).getTextContent();
                int type = parseTypeStringToInt(typeStr);
                String value = element.getElementsByTagName("value").item(0).getTextContent();
                if (isValid) {
                    GWordInfo wordInfo = new GWordInfo(type, value);
                    addWordToLab(wordInfo);
                }
            }
        }


    } catch (Exception error) {
        error.printStackTrace();
    }

}