Java Code Examples for javax.xml.parsers.DocumentBuilderFactory

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: incubator-retired-pirk   Source File: QuerySchemaLoader.java    License: Apache License 2.0 6 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 Project: JavaMainRepo   Source File: EntityRepository.java    License: Apache License 2.0 6 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 Project: jdk8u60   Source File: EPRHeader.java    License: 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 4
Source Project: Hi-WAY   Source File: GalaxyApplicationMaster.java    License: 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 5
Source Project: jframe   Source File: XmlUtil.java    License: 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 Project: netbeans   Source File: JaxRsStackSupportImpl.java    License: 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 Project: openjdk-jdk9   Source File: Bug4967002.java    License: 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 8
Source Project: xades4j   Source File: DOMHelperTest.java    License: 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 9
Source Project: java-technology-stack   Source File: AbstractMarshallerTests.java    License: 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 10
Source Project: proarc   Source File: CejshBuilder.java    License: 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 11
Source Project: photon   Source File: OutputProfileList.java    License: 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 12
Source Project: sarl   Source File: StandardSREInstallTest.java    License: 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 13
Source Project: container   Source File: DocumentConverter.java    License: 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 14
Source Project: RDFS   Source File: TestJobTrackerXmlJsp.java    License: 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 15
/**
 * 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 16
Source Project: carbon-apimgt   Source File: Util.java    License: 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 17
Source Project: openjdk-8-source   Source File: EPRHeader.java    License: 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 18
/**
 * @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 19
/**
 *
 */
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 20
Source Project: jdk8u-jdk   Source File: TruncateHMAC.java    License: 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 21
Source Project: jdk8u60   Source File: DTMManagerDefault.java    License: 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 22
Source Project: hbase   Source File: TestConfServlet.java    License: 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 23
Source Project: protoc-jar   Source File: MavenUtil.java    License: 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 24
Source Project: carbon-apimgt   Source File: AbstractWSDLProcessor.java    License: 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 25
Source Project: openjdk-8   Source File: EPRHeader.java    License: 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 26
Source Project: j-road   Source File: XTeeSoapProvider.java    License: 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 27
/**
 * 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 28
Source Project: io   Source File: DavCmpEsImpl.java    License: 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 29
Source Project: sakai   Source File: I18nXmlUtility.java    License: 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);
	}
}
 
Example 30
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;
}