Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#newInstance()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#newInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestRMWebServicesAppsModification.java    From big-c with Apache License 2.0 6 votes vote down vote up
protected static void verifyAppStateXML(ClientResponse response,
    RMAppState... appStates) throws ParserConfigurationException,
    IOException, SAXException {
  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 nodes = dom.getElementsByTagName("appstate");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  Element element = (Element) nodes.item(0);
  String state = WebServicesTestUtils.getXmlString(element, "state");
  boolean valid = false;
  for (RMAppState appState : appStates) {
    if (appState.toString().equals(state)) {
      valid = true;
    }
  }
  String msg = "app state incorrect, got " + state;
  assertTrue(msg, valid);
}
 
Example 2
Source File: Bug6564400.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testConformantDOM() throws ParserConfigurationException, SAXException, IOException {
    InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");

    // Set the options on the DocumentFactory to remove comments, remove
    // whitespace
    // and validate against the schema.
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringComments(true);
    docFactory.setIgnoringElementContentWhitespace(true);
    docFactory.setSchema(schema);
    docFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace", true);

    DocumentBuilder parser = docFactory.newDocumentBuilder();
    Document xmlDoc = parser.parse(xmlFile);

    boolean ok = dump(xmlDoc, true);
    Assert.assertEquals(false, ok);
}
 
Example 3
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checking Text content in XML file.
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testMoreUserInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

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

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

    Document document = docBuilder.parse(xmlFile);
    Element account = (Element)document
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
    String textContent = account.getTextContent();
    assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6));
    assertEquals(textContent, "RachelGreen744");

    Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID");
    assertTrue(accountID.getTextContent().trim().equals("1"));

    assertFalse(eh.isAnyError());
}
 
Example 4
Source File: TikaProcessorTest.java    From jesterj with Apache License 2.0 6 votes vote down vote up
@Test
public void testXml() throws ParserConfigurationException, IOException, SAXException, TikaException {
  DocumentBuilderFactory factory =
      DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  ByteArrayInputStream input = new ByteArrayInputStream(XML_CONFIG.getBytes("UTF-8"));
  org.w3c.dom.Document doc = builder.parse(input);

  TikaProcessor proc = new TikaProcessor.Builder().named("foo").truncatingTextTo(20)
      .configuredWith(doc)
      .build();
  //System.out.println(new String(new byte[] {32, 32, 32, 84, 104, 101, 32, 116, 105, 116, 108, 101, 32, 84, 104, 105, 115, 32, 105, 115}));
  expect(mockDocument.getRawData()).andReturn(XML.getBytes()).anyTimes();
  mockDocument.setRawData(aryEq("   The title This is".getBytes()));
  expect(mockDocument.put("X_Parsed_By", "org.apache.tika.parser.CompositeParser")).andReturn(true);
  expect(mockDocument.put("Content_Type", "application/xml")).andReturn(true);

  replay();
  proc.processDocument(mockDocument);
}
 
Example 5
Source File: TestRMWebServicesApps.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleAppsXML() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  RMApp app1 = rm.submitApp(CONTAINER_MB, "testwordcount", "user1");
  amNodeManager.nodeHeartbeat(true);
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps").path(app1.getApplicationId().toString())
      .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 nodes = dom.getElementsByTagName("app");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyAppsXML(nodes, app1);
  rm.stop();
}
 
Example 6
Source File: ExperimentationPlanFactory.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static Document buildXmlDocument(final List<IExperimentJob> jobs) throws ParserConfigurationException {
	final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	final Document doc = docBuilder.newDocument();
	final Element rootElement = doc.createElement(XmlTAG.EXPERIMENT_PLAN_TAG);
	doc.appendChild(rootElement);

	for (final IExperimentJob job : jobs) {
		final Element jb = job.asXMLDocument(doc);
		rootElement.appendChild(jb);
	}

	return doc;
}
 
Example 7
Source File: LegacyAbstractAnalyticsFacetTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected static void setResponse(String response) throws ParserConfigurationException, IOException, SAXException {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true); // never forget this!
  DocumentBuilder builder = factory.newDocumentBuilder();
  doc = builder.parse(new InputSource(new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8))));
  rawResponse = response;
}
 
Example 8
Source File: LoincToDEConvertor.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void loadLoinc() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(true);
	DocumentBuilder builder = factory.newDocumentBuilder();

	xml = builder.parse(new FileInputStream(definitions)); 
}
 
Example 9
Source File: XMLHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new DocumentBuilderFactory, with sensible defaults
 */
public static DocumentBuilderFactory getDocumentBuilderFactory() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setExpandEntityReferences(false);
    trySetSAXFeature(factory, XMLConstants.FEATURE_SECURE_PROCESSING, true);
    trySetSAXFeature(factory, "http://xml.org/sax/features/external-general-entities", false);
    trySetSAXFeature(factory, "http://xml.org/sax/features/external-parameter-entities", false);
    trySetSAXFeature(factory, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    trySetSAXFeature(factory, "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    return factory;
}
 
Example 10
Source File: AbstractBuilder.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public AbstractBuilder () throws ParserConfigurationException
{
    this.transformerFactory = TransformerFactory.newInstance ();

    this.dbf = DocumentBuilderFactory.newInstance ();
    this.db = this.dbf.newDocumentBuilder ();
}
 
Example 11
Source File: JunitXmlReportWriter.java    From ossindex-gradle-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private DocumentBuilder getDocBuilder() {
  DocumentBuilder docBuilder = null;
  DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  try {
    docBuilder = docFactory.newDocumentBuilder();
  }
  catch (ParserConfigurationException e) {
    e.printStackTrace();
    System.exit(1);
  }
  return docBuilder;
}
 
Example 12
Source File: XmlSecurity.java    From Box with Apache License 2.0 5 votes vote down vote up
public static DocumentBuilderFactory getSecureDbf() throws ParserConfigurationException {
	synchronized (XmlSecurity.class) {
		if (secureDbf == null) {
			secureDbf = DocumentBuilderFactory.newInstance();
			secureDbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
			secureDbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
			secureDbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
			secureDbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
			secureDbf.setFeature("http://apache.org/xml/features/dom/create-entity-ref-nodes", false);
			secureDbf.setXIncludeAware(false);
			secureDbf.setExpandEntityReferences(false);
		}
	}
	return secureDbf;
}
 
Example 13
Source File: DocumentBuilderAccessor.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
protected DocumentBuilder initialValue() {
    DocumentBuilder builder = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    return builder;
}
 
Example 14
Source File: HtmlAssetTranslator.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
private static void translateOneFile(String language, Path targetHtmlDir, Path sourceFile,
		String translationTextTranslated) throws IOException {

	Path destFile = targetHtmlDir.resolve(sourceFile.getFileName());

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	Document document;
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		document = builder.parse(sourceFile.toFile());
	} catch (ParserConfigurationException pce) {
		throw new IllegalStateException(pce);
	} catch (SAXException sae) {
		throw new IOException(sae);
	}

	Element rootElement = document.getDocumentElement();
	rootElement.normalize();

	Queue<Node> nodes = new LinkedList<>();
	nodes.add(rootElement);

	while (!nodes.isEmpty()) {
		Node node = nodes.poll();
		if (shouldTranslate(node)) {
			NodeList children = node.getChildNodes();
			for (int i = 0; i < children.getLength(); i++) {
				nodes.add(children.item(i));
			}
		}
		if (node.getNodeType() == Node.TEXT_NODE) {
			String text = node.getTextContent();
			if (!text.trim().isEmpty()) {
				text = StringsResourceTranslator.translateString(text, language);
				node.setTextContent(' ' + text + ' ');
			}
		}
	}

	Node translateText = document.createTextNode(translationTextTranslated);
	Node paragraph = document.createElement("p");
	paragraph.appendChild(translateText);
	Node body = rootElement.getElementsByTagName("body").item(0);
	body.appendChild(paragraph);

	DOMImplementationRegistry registry;
	try {
		registry = DOMImplementationRegistry.newInstance();
	} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
		throw new IllegalStateException(e);
	}

	DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
	LSSerializer writer = impl.createLSSerializer();
	String fileAsString = writer.writeToString(document);
	// Replace default XML header with HTML DOCTYPE
	fileAsString = fileAsString.replaceAll("<\\?xml[^>]+>", "<!DOCTYPE HTML>");
	Files.write(destFile, Collections.singleton(fileAsString), StandardCharsets.UTF_8);
}
 
Example 15
Source File: DomBuildingSaxHandler.java    From edireader with GNU General Public License v3.0 4 votes vote down vote up
public DomBuildingSaxHandler() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.newDocument();

}
 
Example 16
Source File: SOAPActionProcessorImpl.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
protected DocumentBuilderFactory createDocumentBuilderFactory() throws FactoryConfigurationError {
	return DocumentBuilderFactory.newInstance();
}
 
Example 17
Source File: Wallet.java    From ethereumj with MIT License 4 votes vote down vote up
/**
 * Save wallet file to the disk
 */
public void save() throws ParserConfigurationException, ParserConfigurationException, TransformerException {

    /**

     <wallet high="8933">
       <row id=1>
                  <address nonce="1" >7c63d6d8b6a4c1ec67766ae123637ca93c199935<address/>
                  <privkey>roman<privkey/>
                  <value>20000000<value/>
       </row>
       <row id=2>
                  <address nonce="6" >b5da3e0ba57da04f94793d1c334e476e7ce7b873<address/>
                  <privkey>cow<privkey/>
                  <value>900099909<value/>
       </row>
     </wallet>

     */

    String dir = System.getProperty("user.dir");
    String fileName = dir + "/wallet.xml";

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    Document doc = docBuilder.newDocument();
    Element walletElement = doc.createElement("wallet");
    doc.appendChild(walletElement);

    Attr high = doc.createAttribute("high");
    high.setValue(Long.toString( this.high ));
    walletElement.setAttributeNode(high);

    int i = 0;
    for (Account account :  getAccountCollection()) {

        Element raw = doc.createElement("raw");
        Attr id = doc.createAttribute("id");
        id.setValue(Integer.toString(i++));
        raw.setAttributeNode(id);

        Element addressE = doc.createElement("address");
        addressE.setTextContent(Hex.toHexString(account.getEcKey().getAddress()));

        Attr nonce = doc.createAttribute("nonce");
        nonce.setValue("0");
        addressE.setAttributeNode(nonce);

        Element privKey = doc.createElement("privkey");
        privKey.setTextContent(Hex.toHexString(account.getEcKey().getPrivKeyBytes()));

        Element value   = doc.createElement("value");
        value.setTextContent(account.getBalance().toString());

        raw.appendChild(addressE);
        raw.appendChild(privKey);
        raw.appendChild(value);

        walletElement.appendChild(raw);
    }
    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(fileName));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);
}
 
Example 18
Source File: GENAEventProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
protected DocumentBuilderFactory createDocumentBuilderFactory() throws FactoryConfigurationError {
	return DocumentBuilderFactory.newInstance();
}
 
Example 19
Source File: XML2Bin.java    From 920-text-editor-v2 with Apache License 2.0 4 votes vote down vote up
private static void parseXml(final File file, StringBuilder mapCode) throws Exception {
        String clsName = fileNameToResName(file.getName()) + "_lang";

        DocumentBuilderFactory dbFactory
                = DocumentBuilderFactory.newInstance();
//        dbFactory.setValidating(false);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        dBuilder.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String s, String systemId) throws SAXException, IOException {
                if (systemId.contains("xmode.dtd")) {
                    return new InputSource(new FileInputStream(new File(assetsPath, "xmode.dtd")));
                }
                return null;
            }
        });
        Document doc = dBuilder.parse(file);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getChildNodes();
        int length = nList.getLength();
        for (int i = 0; i < length; i++) {
            Node item = nList.item(i);
            o("node " + item.getNodeName() + " " + item.getNodeType());
            if (item.getNodeType() == Node.ELEMENT_NODE) {

                if (!item.getNodeName().equals("MODE"))
                    throw new RuntimeException("!MODE: " + item.getNodeName());
                File langFile = new File(rawPath, clsName);
                packer = MessagePack.newDefaultPacker(new FileOutputStream(langFile));

                handleChild((Element)item);

                mapCode.append(space(12)).append("case ").append(textString(file.getName()))
                        .append(": return R.raw.").append(clsName).append(";\n");


                packer.close();
            }
        }
    }
 
Example 20
Source File: MessageScript.java    From onpc with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void initialize(@NonNull final Intent intent)
{
    final String data = intent.getDataString();
    if (data == null || data.isEmpty())
    {
        Logging.info(this, "intent data parameter empty: no script to parse");
        return;
    }

    try
    {
        InputStream stream = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8")));
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
        factory.setExpandEntityReferences(false);
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.parse(stream);
        final Node object = doc.getDocumentElement();
        //noinspection ConstantConditions
        if (object instanceof Element)
        {
            //noinspection CastCanBeRemovedNarrowingVariableType
            final Element elem = (Element) object;
            if (elem.getTagName().equals("onpcScript"))
            {
                if (elem.getAttribute("host") != null)
                {
                    host = elem.getAttribute("host");
                }
                port = Utils.parseIntAttribute(elem, "port", ConnectionIf.EMPTY_PORT);
                zone = Utils.parseIntAttribute(elem, "zone", ReceiverInformationMsg.DEFAULT_ACTIVE_ZONE);
            }
            for (Node prop = elem.getFirstChild(); prop != null; prop = prop.getNextSibling())
            {
                if (prop instanceof Element)
                {
                    final Element action = (Element) prop;
                    if (action.getTagName().equals("send"))
                    {
                        final String cmd = action.getAttribute("cmd");
                        if (cmd == null)
                        {
                            throw new Exception("missing command code in 'send' command");
                        }
                        final String par = action.getAttribute("par");
                        if (par == null)
                        {
                            throw new Exception("missing command parameter in 'send' command");
                        }
                        final int milliseconds = Utils.parseIntAttribute(action, "wait", -1);
                        final String wait = action.getAttribute("wait");
                        final String resp = action.getAttribute("resp");
                        if (milliseconds < 0 && (wait == null || wait.isEmpty()))
                        {
                            Logging.info(this, "missing time or wait CMD in 'send' command");
                            return;
                        }
                        actions.add(new Action(cmd, par, milliseconds, wait, resp));
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        // TODO - raise this to the user's attention - they stuffed up and they'd probably like to know
        Logging.info(this, "Failed to parse onpcScript pass in intent: " + e.getLocalizedMessage());
        actions.clear();
    }
    for (Action a : actions)
    {
        Logging.info(this, a.toString());
    }
}