javax.xml.parsers.DocumentBuilderFactory Java Examples

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory. 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: QuerySchemaLoader.java    From incubator-retired-pirk with Apache License 2.0 8 votes vote down vote up
/**
 * Parses and normalizes the XML document available on the given stream.
 * 
 * @param stream
 *          The input stream.
 * @return A Document representing the XML document.
 * @throws IOException
 *           - failed to read input
 * @throws PIRException
 *           - file could not be parsed
 */
private Document parseXMLDocument(InputStream stream) throws IOException, PIRException
{
  Document doc;
  try
  {
    DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    doc = dBuilder.parse(stream);
  } catch (ParserConfigurationException | SAXException e)
  {
    throw new PIRException("Schema parsing error", e);
  }
  doc.getDocumentElement().normalize();
  logger.info("Root element: " + doc.getDocumentElement().getNodeName());

  return doc;
}
 
Example #2
Source File: EntityRepository.java    From JavaMainRepo with Apache License 2.0 7 votes vote down vote up
public ArrayList<T> load() throws ParserConfigurationException, SAXException, IOException {

		ArrayList<T> entities = new ArrayList<T>();

		File fXmlFile = new File(this.xmlFilename);

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();

		NodeList nodeList = doc.getElementsByTagName(this.entityTag);

		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) node;
				entities.add(getEntityFromXmlElement(element));

			}
		}
		return entities;
	}
 
Example #3
Source File: Bug4967002.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void setAttr(boolean setSrc) {
    DocumentBuilderFactory docBFactory = DocumentBuilderFactory.newInstance();
    Schema sch = createSchema();
    docBFactory.setSchema(sch);
    docBFactory.setNamespaceAware(true);
    docBFactory.setValidating(true);

    final String aSchemaLanguage = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    final String aSchemaSource = "http://java.sun.com/xml/jaxp/properties/schemaSource";

    docBFactory.setAttribute(aSchemaLanguage, "http://www.w3.org/2001/XMLSchema");
    // System.out.println("---- Set schemaLanguage: " +
    // docBFactory.getAttribute(aSchemaLanguage));
    if (setSrc) {
        docBFactory.setAttribute(aSchemaSource, new InputSource(new StringReader(schemaSource)));
        // System.out.println("---- Set schemaSource: " +
        // docBFactory.getAttribute(aSchemaSource));
    }

    try {
        docBFactory.newDocumentBuilder();
        Assert.fail("ParserConfigurationException expected");
    } catch (ParserConfigurationException pce) {
        return; // success
    }
}
 
Example #4
Source File: TestDefaultConfigurations.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static Document createDocument(String content) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new InputSource(new StringReader(content)));
    doc.getDocumentElement().normalize();
    // Don't want to add these settings to the jfc-files we ship since they
    // are not useful to configure. They are however needed to make the test
    // pass.
    insertSetting(doc, "com.oracle.jdk.ActiveSetting", "stackTrace", "false");
    insertSetting(doc, "com.oracle.jdk.ActiveSetting", "threshold", "0 ns");
    insertSetting(doc, "com.oracle.jdk.ActiveRecording", "stackTrace", "false");
    insertSetting(doc, "com.oracle.jdk.ActiveRecording", "threshold", "0 ns");
    insertSetting(doc, "com.oracle.jdk.JavaExceptionThrow", "threshold", "0 ns");
    insertSetting(doc, "com.oracle.jdk.JavaErrorThrow", "threshold", "0 ns");
    return doc;
}
 
Example #5
Source File: XmlUtil.java    From jframe with Apache License 2.0 6 votes vote down vote up
public static Map<String, String> fromXml(InputStream in) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document source = builder.parse(in);

    NodeList nodeList = source.getDocumentElement().getChildNodes();

    Map<String, String> map = new HashMap<>();
    Node node = null;
    for (int i = 0; i < nodeList.getLength(); i++) {
        node = nodeList.item(i);
        map.put(node.getNodeName(), node.getTextContent());
    }
    return map;
}
 
Example #6
Source File: JaxRsStackSupportImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private DocumentBuilder getDocumentBuilder() {
    DocumentBuilder builder = null;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setIgnoringComments(false);
    factory.setIgnoringElementContentWhitespace(false);
    factory.setCoalescing(false);
    factory.setExpandEntityReferences(false);
    factory.setValidating(false);

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Exceptions.printStackTrace(ex);
    }

    return builder;
}
 
Example #7
Source File: EPRHeader.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
Example #8
Source File: GalaxyApplicationMaster.java    From Hi-WAY with Apache License 2.0 6 votes vote down vote up
/**
 * A helper function for processing the Galaxy config file that specifies the extensions and python script locations for Galaxy's data types
 * 
 * @param file
 *            the Galaxy data type config file
 */
private void processDataTypes(File file) {
	try {
		WorkflowDriver.writeToStdout("Processing Galaxy data type config file " + file.getCanonicalPath());
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse(file);
		NodeList datatypeNds = doc.getElementsByTagName("datatype");
		for (int i = 0; i < datatypeNds.getLength(); i++) {
			Element datatypeEl = (Element) datatypeNds.item(i);
			if (!datatypeEl.hasAttribute("extension") || !datatypeEl.hasAttribute("type") || datatypeEl.hasAttribute("subclass"))
				continue;
			String extension = datatypeEl.getAttribute("extension");
			String[] splitType = datatypeEl.getAttribute("type").split(":");
			galaxyDataTypes.put(extension, new GalaxyDataType(splitType[0], splitType[1], extension));
		}
	} catch (SAXException | IOException | ParserConfigurationException e) {
		e.printStackTrace(System.out);
		System.exit(-1);
	}
}
 
Example #9
Source File: DOMHelperTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testGetChildElementsByTagNameNS() throws Exception
{
    String xml = "<root><a xmlns='urn:test'/><b/><n:a xmlns:n='urn:test'/><c/></root>";
    
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(xml)));
    
    Collection<Element> elements = DOMHelper.getChildElementsByTagNameNS(doc.getDocumentElement(), "urn:test", "a");
    
    Assert.assertNotNull(elements);
    Assert.assertEquals(2, elements.size());
    for (Element element : elements)
    {
        Assert.assertEquals("a", element.getLocalName());
    }
}
 
Example #10
Source File: AbstractMarshallerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void marshalEmptyDOMResult() throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	DOMResult domResult = new DOMResult();
	marshaller.marshal(flights, domResult);
	assertTrue("DOMResult does not contain a Document", domResult.getNode() instanceof Document);
	Document result = (Document) domResult.getNode();
	Document expected = builder.newDocument();
	Element flightsElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flights");
	Attr namespace = expected.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tns");
	namespace.setNodeValue("http://samples.springframework.org/flight");
	flightsElement.setAttributeNode(namespace);
	expected.appendChild(flightsElement);
	Element flightElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:flight");
	flightsElement.appendChild(flightElement);
	Element numberElement = expected.createElementNS("http://samples.springframework.org/flight", "tns:number");
	flightElement.appendChild(numberElement);
	Text text = expected.createTextNode("42");
	numberElement.appendChild(text);
	assertThat("Marshaller writes invalid DOMResult", result, isSimilarTo(expected));
}
 
Example #11
Source File: CejshBuilder.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
public CejshBuilder(CejshConfig config, ExportOptions options)
        throws TransformerConfigurationException, ParserConfigurationException, XPathExpressionException {
    this.gcalendar = new GregorianCalendar(UTC);
    this.logLevel = config.getLogLevel();
    this.options = options;
    TransformerFactory xslFactory = TransformerFactory.newInstance();
    tranformationErrorHandler = new TransformErrorListener();
    bwmetaXsl = xslFactory.newTransformer(new StreamSource(config.getCejshXslUrl()));
    if (bwmetaXsl == null) {
        throw new TransformerConfigurationException("Cannot load XSL: " + config.getCejshXslUrl());
    }
    bwmetaXsl.setOutputProperty(OutputKeys.INDENT, "yes");
    bwmetaXsl.setErrorListener(tranformationErrorHandler);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    db = dbf.newDocumentBuilder();
    XPathFactory xPathFactory = ProarcXmlUtils.defaultXPathFactory();
    XPath xpath = xPathFactory.newXPath();
    xpath.setNamespaceContext(new SimpleNamespaceContext().add("m", ModsConstants.NS));
    issnPath = xpath.compile("m:mods/m:identifier[@type='issn' and not(@invalid)]");
    partNumberPath = xpath.compile("m:mods/m:titleInfo/m:partNumber");
    dateIssuedPath = xpath.compile("m:mods/m:originInfo/m:dateIssued");
    reviewedArticlePath = xpath.compile("m:mods/m:genre[text()='article' and @type='peer-reviewed']");
}
 
Example #12
Source File: OutputProfileList.java    From photon with Apache License 2.0 6 votes vote down vote up
/**
 * A method that confirms if the inputStream corresponds to a OutputProfileList document instance.
 *
 * @param resourceByteRangeProvider corresponding to the OutputProfileList XML file.
 * @return a boolean indicating if the input file is a OutputProfileList document
 * @throws IOException - any I/O related error is exposed through an IOException
 */
public static boolean isOutputProfileList(ResourceByteRangeProvider resourceByteRangeProvider) throws IOException {
    try (InputStream inputStream = resourceByteRangeProvider.getByteRangeAsStream(0, resourceByteRangeProvider.getResourceSize() - 1);) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(inputStream);

        //obtain root node
        NodeList nodeList = document.getElementsByTagNameNS(outputProfileList_QNAME.getNamespaceURI(), outputProfileList_QNAME.getLocalPart());
        if (nodeList != null && nodeList.getLength() == 1) {
            return true;
        }
    } catch (ParserConfigurationException | SAXException e) {
        return false;
    }
    return false;
}
 
Example #13
Source File: StandardSREInstallTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Test
public void setFromXML() throws Exception {
	String[] expected = new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
			"<SRE name=\"Hello\" mainClass=\"io.sarl.Boot\" libraryPath=\"" + this.path.toPortableString()
					+ "\" standalone=\"true\">",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"" + this.path.toPortableString()
					+ "\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"x.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"y.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"z.jar\"/>", "</SRE>", };
	StringBuilder b = new StringBuilder();
	for (String s : expected) {
		b.append(s);
		// b.append("\n");
	}
	try (ByteArrayInputStream bais = new ByteArrayInputStream(b.toString().getBytes())) {
		DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		parser.setErrorHandler(new DefaultHandler());
		Element root = parser.parse(new InputSource(bais)).getDocumentElement();
		this.sre.setFromXML(root);
		assertTrue(this.sre.isStandalone());
		assertEquals(this.path, this.sre.getJarFile());
		assertEquals("Hello", this.sre.getName());
		assertEquals("io.sarl.Boot", this.sre.getMainClass());
	}
}
 
Example #14
Source File: DocumentConverter.java    From container with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a given String to a XML document
 *
 * @return Document - converted xml Document
 */
private static Document getDocument(final String documentString) {
    if (documentString.isEmpty()) {
        return emptyDocument();
    }
    // start conversion
    final InputSource iSource = new InputSource(new StringReader(documentString));
    Document doc = null;
    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setIgnoringComments(true);
        final DocumentBuilder db = dbf.newDocumentBuilder();

        // parse
        doc = db.parse(iSource);
        doc.getDocumentElement().normalize();
    } catch (final ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return doc;
}
 
Example #15
Source File: TestJobTrackerXmlJsp.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Read the jobtracker.jspx status page and validate that the XML is well formed.
 */
public void testXmlWellFormed() throws IOException, ParserConfigurationException, SAXException {
  MiniMRCluster cluster = getMRCluster();
  int infoPort = cluster.getJobTrackerRunner().getJobTrackerInfoPort();

  String xmlJspUrl = "http://localhost:" + infoPort + "/jobtracker.jspx";
  LOG.info("Retrieving XML from URL: " + xmlJspUrl);

  DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc = parser.parse(xmlJspUrl);

  // If we get here, then the document was successfully parsed by SAX and is well-formed.
  LOG.info("Document received and parsed.");

  // Make sure it has a <cluster> element as top-level.
  NodeList clusterNodes = doc.getElementsByTagName("cluster");
  assertEquals("There should be exactly 1 <cluster> element", 1, clusterNodes.getLength());
}
 
Example #16
Source File: TransformerTest02.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for transform(StreamSource, StreamResult).
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase01() throws Exception {
    String outputFile = USER_DIR + "transformer02.out";
    String goldFile = GOLDEN_DIR + "transformer02GF.out";
    String xsltFile = XML_DIR + "cities.xsl";
    String xmlFile = XML_DIR + "cities.xml";

    try (FileInputStream fis = new FileInputStream(xmlFile);
            FileOutputStream fos = new FileOutputStream(outputFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DOMSource domSource = new DOMSource(dbf.newDocumentBuilder().
                parse(new File(xsltFile)));

        Transformer transformer = TransformerFactory.newInstance().
                newTransformer(domSource);
        StreamSource streamSource = new StreamSource(fis);
        StreamResult streamResult = new StreamResult(fos);

        transformer.setOutputProperty("indent", "no");
        transformer.transform(streamSource, streamResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #17
Source File: Util.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Constructing the XMLObject Object from a String
 *
 * @param authReqStr
 * @return Corresponding XMLObject which is a SAML2 object
 * @throws Exception
 */
public static XMLObject unmarshall(String authReqStr) throws Exception {
    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = getSecuredDocumentBuilder();
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setIgnoringComments(true);
        Document document = getDocument(documentBuilderFactory, authReqStr);
        if (isSignedWithComments(document)) {
            documentBuilderFactory.setIgnoringComments(false);
            document = getDocument(documentBuilderFactory, authReqStr);
        }
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (Exception e) {
        throw new Exception("Error in constructing AuthRequest from " +
                "the encoded String ", e);
    }
}
 
Example #18
Source File: EPRHeader.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
Example #19
Source File: XMLStreamWriterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @bug 8139584
 * Verifies that the resulting XML contains the standalone setting.
 */
@Test
public void testCreateStartDocument_DOMWriter()
        throws ParserConfigurationException, XMLStreamException {

    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    XMLEventWriter eventWriter = xof.createXMLEventWriter(new DOMResult(doc));
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent event = eventFactory.createStartDocument("iso-8859-15", "1.0", true);
    eventWriter.add(event);
    eventWriter.flush();
    Assert.assertEquals(doc.getXmlEncoding(), "iso-8859-15");
    Assert.assertEquals(doc.getXmlVersion(), "1.0");
    Assert.assertTrue(doc.getXmlStandalone());
}
 
Example #20
Source File: SimpleFontExtensionHelper.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 *
 */
private SimpleFontExtensionHelper()
{
	try
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setFeature(JRXmlUtils.FEATURE_DISALLOW_DOCTYPE, true);
		
		documentBuilder = factory.newDocumentBuilder();
		documentBuilder.setErrorHandler(this);
	}
	catch (ParserConfigurationException e)
	{
		throw new JRRuntimeException(e);
	}
}
 
Example #21
Source File: TruncateHMAC.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        Init.init();
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        validate("signature-enveloping-hmac-sha1-trunclen-0-attack.xml", false);
        validate("signature-enveloping-hmac-sha1-trunclen-8-attack.xml", false);
        // this one should pass
        validate("signature-enveloping-hmac-sha1.xml", true);
        generate_hmac_sha1_40();

        if (atLeastOneFailed) {
            throw new Exception
                ("At least one signature did not validate as expected");
        }
    }
 
Example #22
Source File: DTMManagerDefault.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method createDocumentFragment
 *
 *
 * NEEDSDOC (createDocumentFragment) @return
 */
synchronized public DTM createDocumentFragment()
{

  try
  {
    DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(super.useServicesMechnism());
    dbf.setNamespaceAware(true);

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Node df = doc.createDocumentFragment();

    return getDTM(new DOMSource(df), true, null, false, false);
  }
  catch (Exception e)
  {
    throw new DTMException(e);
  }
}
 
Example #23
Source File: TestConfServlet.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteXml() throws Exception {
  StringWriter sw = new StringWriter();
  ConfServlet.writeResponse(getTestConf(), sw, "xml");
  String xml = sw.toString();

  DocumentBuilderFactory docBuilderFactory
    = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
  Document doc = builder.parse(new InputSource(new StringReader(xml)));
  NodeList nameNodes = doc.getElementsByTagName("name");
  boolean foundSetting = false;
  for (int i = 0; i < nameNodes.getLength(); i++) {
    Node nameNode = nameNodes.item(i);
    String key = nameNode.getTextContent();
    System.err.println("xml key: " + key);
    if (TEST_KEY.equals(key)) {
      foundSetting = true;
      Element propertyElem = (Element)nameNode.getParentNode();
      String val = propertyElem.getElementsByTagName("value").item(0).getTextContent();
      assertEquals(TEST_VAL, val);
    }
  }
  assertTrue(foundSetting);
}
 
Example #24
Source File: MavenUtil.java    From protoc-jar with Apache License 2.0 6 votes vote down vote up
static String parseLastReleaseBuild(File mdFile, ProtocVersion protocVersion) throws IOException {
	int lastBuild = 0;
	try {
		DocumentBuilder xmlBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document xmlDoc = xmlBuilder.parse(mdFile);
		NodeList versions = xmlDoc.getElementsByTagName("version");
		for (int i = 0; i < versions.getLength(); i++) {
			Node ver = versions.item(i);
			String verStr = ver.getTextContent();
			if (verStr.startsWith(protocVersion.mVersion+"-build")) {
				String buildStr = verStr.substring(verStr.indexOf("-build")+"-build".length());
				int build = Integer.parseInt(buildStr);
				if (build > lastBuild) lastBuild = build;
			}
		}
	}
	catch (Exception e) {
		throw new IOException(e);
	}
	if (lastBuild > 0) return protocVersion.mVersion+"-build"+lastBuild;
	return null;
}
 
Example #25
Source File: AbstractWSDLProcessor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a secured document builder to avoid XXE attacks
 *
 * @return secured document builder to avoid XXE attacks
 */
private DocumentBuilderFactory getSecuredDocumentBuilder() {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    try {
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (ParserConfigurationException e) {
        // Skip throwing the error as this exception doesn't break actual DocumentBuilderFactory creation
        log.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or "
                + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE, e);
    }
    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);
    return dbf;
}
 
Example #26
Source File: EPRHeader.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
Example #27
Source File: XTeeSoapProvider.java    From j-road with Apache License 2.0 6 votes vote down vote up
@Override
protected void populatePort(Definition definition, Port port) throws WSDLException {
  super.populatePort(definition, port);
  ExtensionRegistry extensionRegistry = definition.getExtensionRegistry();
  extensionRegistry.mapExtensionTypes(Port.class,
                                      new QName(XTeeWsdlDefinition.XROAD_NAMESPACE,
                                                "address",
                                                XTeeWsdlDefinition.XROAD_PREFIX),
                                      UnknownExtensibilityElement.class);
  UnknownExtensibilityElement element =
      (UnknownExtensibilityElement) extensionRegistry.createExtension(Port.class,
                                                                      new QName(XTeeWsdlDefinition.XROAD_NAMESPACE,
                                                                                "address",
                                                                                XTeeWsdlDefinition.XROAD_NAMESPACE));
  Document doc;
  try {
    doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
  } catch (ParserConfigurationException e) {
    throw new RuntimeException(e);
  }
  Element xRoadAddr = doc.createElementNS(XTeeWsdlDefinition.XROAD_NAMESPACE, "address");
  xRoadAddr.setPrefix(XTeeWsdlDefinition.XROAD_PREFIX);
  xRoadAddr.setAttribute("producer", xRoadDatabase);
  element.setElement(xRoadAddr);
  port.addExtensibilityElement(element);
}
 
Example #28
Source File: LayersLegend.java    From MeteoInfo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Import project XML content
 *
 * @param fileName XML file name
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 */
public void importProjectXML(String fileName) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new File(fileName));

    Element root = doc.getDocumentElement();

    Properties property = System.getProperties();
    String path = System.getProperty("user.dir");
    property.setProperty("user.dir", new File(fileName).getAbsolutePath());
    String pPath = new File(fileName).getParent();

    this.getActiveMapFrame().getMapView().setLockViewUpdate(true);
    this.importProjectXML(pPath, root);
    this.getActiveMapFrame().getMapView().setLockViewUpdate(false);
    this.paintGraphics();
    this.getActiveMapFrame().getMapView().paintLayers();

    property.setProperty("user.dir", path);
}
 
Example #29
Source File: DavCmpEsImpl.java    From io with Apache License 2.0 6 votes vote down vote up
private Element parseProp(String value) {
    // valをDOMでElement化
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}
 
Example #30
Source File: I18nXmlUtility.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Gets a DocumentBuilder instance
 */
public static DocumentBuilder getDocumentBuilder() {
	try {
		if (documentBuilderFactory == null) {
			documentBuilderFactory = DocumentBuilderFactory.newInstance();
		}
		if (documentBuilder == null) {
			documentBuilder = documentBuilderFactory.newDocumentBuilder();
		}

		return documentBuilder;
	}
	catch (Exception e) {
		throw new ContentReviewProviderException("Failed to produce an XML Document Builder", e);
	}
}