Here are the examples of the java api class javax.xml.parsers.DocumentBuilder taken from open source projects.
1. DomUtils#getDocumentBuilder()
Project: opensearchserver
File: DomUtils.java
File: DomUtils.java
private static final DocumentBuilder getDocumentBuilder(final boolean errorSilent) throws ParserConfigurationException { DocumentBuilderFactory dbf = getDocumentBuilderFactory(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); dbf.setNamespaceAware(false); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); db.setEntityResolver(new NullResolver()); db.setErrorHandler(errorSilent ? ParserErrorHandler.SILENT_ERROR_HANDLER : ParserErrorHandler.STANDARD_ERROR_HANDLER); return db; }
2. ParserFactoryImpl#getParser()
Project: geronimo
File: ParserFactoryImpl.java
File: ParserFactoryImpl.java
public DocumentBuilder getParser() throws ParserConfigurationException { DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) { log.warn("SAX parse error (ignored)", exception); //throw exception; } public void fatalError(SAXParseException exception) { log.warn("Fatal SAX parse error (ignored)", exception); //throw exception; } public void warning(SAXParseException exception) { log.warn("SAX parse warning", exception); } }); return builder; }
3. UserController#testUserError()
Project: openjdk
File: UserController.java
File: UserController.java
/** * Checking for Row 8 from the schema table when setting the schemaSource * without the schemaLanguage must report an error. * * @throws Exception If any errors occur. */ @Test(expectedExceptions = IllegalArgumentException.class) public void testUserError() throws Exception { String xmlFile = XML_DIR + "userInfo.xml"; String schema = "http://java.sun.com/xml/jaxp/properties/schemaSource"; String schemaValue = "http://dummy.com/dummy.xsd"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(schema, schemaValue); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); MyErrorHandler eh = new MyErrorHandler(); docBuilder.setErrorHandler(eh); docBuilder.parse(xmlFile); assertFalse(eh.isAnyError()); }
4. DocumentBuilderFactoryTest#testCheckSchemaSupport1()
Project: openjdk
File: DocumentBuilderFactoryTest.java
File: DocumentBuilderFactoryTest.java
/** * Test the default functionality of schema support method. * @throws Exception If any errors occur. */ @Test public void testCheckSchemaSupport1() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true); dbf.setNamespaceAware(true); dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", W3C_XML_SCHEMA_NS_URI); MyErrorHandler eh = MyErrorHandler.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(eh); db.parse(new File(XML_DIR, "test.xml")); assertFalse(eh.isErrorOccured()); }
5. XML#createDOMParser()
Project: oodt
File: XML.java
File: XML.java
/** Create a DOM parser. * * This method creates a new DOM parser that has validation turned on and * ignorable whitespace not included, and has a default error handler that prints * error messages and warnings to the standard error stream. * * @return A new DOM parser. */ public static DOMParser createDOMParser() { DocumentBuilder builder = getStandardDocumentBuilder(); builder.setEntityResolver(ENTERPRISE_ENTITY_RESOLVER); builder.setErrorHandler(new ErrorHandler() { public void error(SAXParseException ex) { System.err.println("Parse error: " + ex.getMessage()); ex.printStackTrace(); } public void warning(SAXParseException ex) { System.err.println("Parse warning: " + ex.getMessage()); } public void fatalError(SAXParseException ex) { System.err.println("Fatal parse error: " + ex.getMessage()); ex.printStackTrace(); } }); return new DOMParser(builder); }
6. XMLTools#parseDOM()
Project: bioformats
File: XMLTools.java
File: XMLTools.java
/** Parses a DOM from the given XML input stream. */ public static Document parseDOM(InputStream is) throws ParserConfigurationException, SAXException, IOException { final InputStream in = is.markSupported() ? is : new BufferedInputStream(is); checkUTF8(in); // Java XML factories are not declared to be thread safe DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); db.setErrorHandler(new ParserErrorHandler()); return db.parse(in); }
7. WSDLWrapperTest#newDocument()
Project: axis2-java
File: WSDLWrapperTest.java
File: WSDLWrapperTest.java
private Document newDocument(InputStream inp) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = getDOMFactory(); DocumentBuilder db; synchronized (dbf) { try { db = dbf.newDocumentBuilder(); } catch (Exception e) { dbf = getDOMFactory(); db = dbf.newDocumentBuilder(); } } db.setEntityResolver(new DefaultEntityResolver()); db.setErrorHandler(new ParserErrorHandler()); return (db.parse(inp)); }
8. XMLUtils#newDocument()
Project: axis2-java
File: XMLUtils.java
File: XMLUtils.java
/** * Gets a new Document read from the input source. * * @return Returns Document. * @throws ParserConfigurationException if construction problems occur * @throws SAXException if the document has xml sax problems * @throws IOException if i/o exceptions occur */ public static Document newDocument(InputSource inp) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder db; synchronized (dbf) { try { db = dbf.newDocumentBuilder(); } catch (Exception e) { dbf = getDOMFactory(); db = dbf.newDocumentBuilder(); } } db.setEntityResolver(new DefaultEntityResolver()); db.setErrorHandler(new ParserErrorHandler()); return (db.parse(inp)); }
9. UserController#testMoreUserInfo()
Project: openjdk
File: UserController.java
File: UserController.java
/** * Checking Text content in XML file. * @see <a href="content/accountInfo.xml">accountInfo.xml</a> * * @throws Exception If any errors occur. */ @Test(groups = { "readLocalFiles" }) 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()); }
10. AuctionItemRepository#testEntityExpansionDOMPos()
Project: openjdk
File: AuctionItemRepository.java
File: AuctionItemRepository.java
/** * Use a DocumentBuilder to create a DOM object and see if Secure Processing * feature affects the entity expansion. * * @throws Exception If any errors occur. */ @Test public void testEntityExpansionDOMPos() throws Exception { DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setFeature(FEATURE_SECURE_PROCESSING, true); setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(10000)); DocumentBuilder dBuilder = dfactory.newDocumentBuilder(); MyErrorHandler eh = new MyErrorHandler(); dBuilder.setErrorHandler(eh); try { setPermissions(new FilePermission(ENTITY_XML, "read")); dBuilder.parse(ENTITY_XML); assertFalse(eh.isAnyError()); } finally { setPermissions(); } }
11. AuctionController#testGetTypeInfo()
Project: openjdk
File: AuctionController.java
File: AuctionController.java
/** * Check usage of TypeInfo interface introduced in DOM L3. * * @throws Exception If any errors occur. */ @Test(groups = { "readLocalFiles" }) public void testGetTypeInfo() throws Exception { String xmlFile = XML_DIR + "accountInfo.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(new MyErrorHandler()); Document document = docBuilder.parse(xmlFile); Element userId = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0); TypeInfo typeInfo = userId.getSchemaTypeInfo(); assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger")); assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI)); Element role = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0); TypeInfo roletypeInfo = role.getSchemaTypeInfo(); assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell")); assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS)); }
12. DocumentBuilderFactoryTest#testCheckElementContentWhitespace()
Project: openjdk
File: DocumentBuilderFactoryTest.java
File: DocumentBuilderFactoryTest.java
/** * 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)); }
13. XmlUtils#createDocument()
Project: mrgeo
File: XmlUtils.java
File: XmlUtils.java
public static Document createDocument() throws IOException { DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = dBF.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException("Error creating document builder. (" + e.getMessage() + ")"); } return builder.newDocument(); }
14. TimeFilterTest#configure()
Project: log4j-extras
File: TimeFilterTest.java
File: TimeFilterTest.java
/** * Configure log4j from resource. * @param resourceName resource name. * @throws Exception if IO or other error. */ private final void configure(final String resourceName) throws Exception { Logger.getRootLogger().getLoggerRepository().resetConfiguration(); InputStream is = getClass().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Could not find resource " + resourceName); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new Log4jEntityResolver()); Document doc = builder.parse(is); DOMConfigurator.configure(doc.getDocumentElement()); }
15. SimpleFilterTest#configure()
Project: log4j-extras
File: SimpleFilterTest.java
File: SimpleFilterTest.java
private final void configure(final String resourceName) throws Exception { InputStream is = getClass().getResourceAsStream(resourceName); if (is == null) { throw new FileNotFoundException("Could not find resource " + resourceName); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new Log4jEntityResolver()); Document doc = builder.parse(is); DOMConfigurator.configure(doc.getDocumentElement()); }
16. XMLUtils#parse()
Project: Jenkins2
File: XMLUtils.java
File: XMLUtils.java
/** * Parse the supplied XML stream data to a {@link Document}. * <p> * This function does not close the stream. * * @param stream The XML stream. * @return The XML {@link Document}. * @throws SAXException Error parsing the XML stream data e.g. badly formed XML. * @throws IOException Error reading from the steam. * @since 2.0 */ @Nonnull public static Document parse(@Nonnull Reader stream) throws SAXException, IOException { DocumentBuilder docBuilder; try { docBuilder = newDocumentBuilderFactory().newDocumentBuilder(); docBuilder.setEntityResolver(RestrictiveEntityResolver.INSTANCE); } catch (ParserConfigurationException e) { throw new IllegalStateException("Unexpected error creating DocumentBuilder.", e); } return docBuilder.parse(new InputSource(stream)); }
17. XmlDomParser#parse()
Project: buck
File: XmlDomParser.java
File: XmlDomParser.java
public static Document parse(InputSource xml, boolean namespaceAware) throws IOException, SAXException { DocumentBuilder docBuilder; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (namespaceAware) { factory.setNamespaceAware(namespaceAware); } docBuilder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } return docBuilder.parse(xml); }
18. MergeJPAPersistenceResource#compileMappingFiles()
Project: broadleaf_modify
File: MergeJPAPersistenceResource.java
File: MergeJPAPersistenceResource.java
private void compileMappingFiles(List<String> mappingFiles, byte[] sourceArray) throws IOException, ParserConfigurationException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); parser.setErrorHandler(handler); Document dom = parser.parse(new ByteArrayInputStream(sourceArray)); NodeList nodes = dom.getElementsByTagName("/persistence/persistence-unit/mapping-file"); if (nodes != null && nodes.getLength() > 0) { int length = nodes.getLength(); for (int j = 0; j < length; j++) { Node node = nodes.item(j); mappingFiles.add(node.getNodeValue()); } } }
19. MergeJPAPersistenceResource#compileMappingFiles()
Project: BroadleafCommerce
File: MergeJPAPersistenceResource.java
File: MergeJPAPersistenceResource.java
private void compileMappingFiles(List<String> mappingFiles, byte[] sourceArray) throws IOException, ParserConfigurationException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); parser.setErrorHandler(handler); Document dom = parser.parse(new ByteArrayInputStream(sourceArray)); NodeList nodes = dom.getElementsByTagName("/persistence/persistence-unit/mapping-file"); if (nodes != null && nodes.getLength() > 0) { int length = nodes.getLength(); for (int j = 0; j < length; j++) { Node node = nodes.item(j); mappingFiles.add(node.getNodeValue()); } } }
20. XMLPropertyListParser#getDocBuilder()
Project: bazel
File: XMLPropertyListParser.java
File: XMLPropertyListParser.java
/** * Gets a DocumentBuilder to parse a XML property list. * As DocumentBuilders are not thread-safe a new DocBuilder is generated for each request. * * @return A new DocBuilder that can parse property lists w/o an internet connection. * @throws javax.xml.parsers.ParserConfigurationException If a document builder for parsing a XML property list * could not be created. This should not occur. */ private static synchronized DocumentBuilder getDocBuilder() throws ParserConfigurationException { if (docBuilderFactory == null) initDocBuilderFactory(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); docBuilder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { if (// older publicId "-//Apple Computer//DTD PLIST 1.0//EN".equals(publicId) || "-//Apple//DTD PLIST 1.0//EN".equals(publicId)) { // it from the network. return new InputSource(new ByteArrayInputStream(new byte[0])); } return null; } }); return docBuilder; }
21. DomUtil#readXml()
Project: commons-modeler
File: DomUtil.java
File: DomUtil.java
/** Read XML as DOM. */ public static Document readXml(InputStream is) throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(false); dbf.setIgnoringElementContentWhitespace(true); //dbf.setCoalescing(true); //dbf.setExpandEntityReferences(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); db.setEntityResolver(new NullResolver()); // db.setErrorHandler( new MyErrorHandler()); Document doc = db.parse(is); return doc; }
22. TestXMLConfiguration#createValidatingDocBuilder()
Project: commons-configuration
File: TestXMLConfiguration.java
File: TestXMLConfiguration.java
/** * Creates a validating document builder. * @return the document builder * @throws ParserConfigurationException if an error occurs */ private DocumentBuilder createValidatingDocBuilder() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new DefaultHandler() { @Override public void error(SAXParseException ex) throws SAXException { throw ex; } }); return builder; }
23. Santuario273Test#testC14n11Base()
Project: santuario-java
File: Santuario273Test.java
File: Santuario273Test.java
@org.junit.Test public void testC14n11Base() throws Exception { DocumentBuilder documentBuilder = XMLUtils.createDocumentBuilder(true); documentBuilder.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler()); byte inputBytes[] = input.getBytes(); Document doc = documentBuilder.parse(new ByteArrayInputStream(inputBytes)); Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS); XPathFactory xpf = XPathFactory.newInstance(); XPath xPath = xpf.newXPath(); xPath.setNamespaceContext(new DSNamespaceContext()); Node signedInfo = (Node) xPath.evaluate("//ds:SignedInfo[1]", doc, XPathConstants.NODE); byte[] output = c14n.canonicalizeSubtree(signedInfo); assertEquals(new String(output, "UTF-8"), expectedResult); }
24. CanonDirect#main()
Project: santuario-java
File: CanonDirect.java
File: CanonDirect.java
/** * Method main * * @param args * @throws Exception */ public static void main(String args[]) throws Exception { org.apache.xml.security.Init.init(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); dfactory.setValidating(true); DocumentBuilder documentBuilder = dfactory.newDocumentBuilder(); // this is to throw away all validation warnings documentBuilder.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler()); byte inputBytes[] = input.getBytes(); Document doc = documentBuilder.parse(new ByteArrayInputStream(inputBytes)); // after playing around, we have our document now Canonicalizer c14n = Canonicalizer.getInstance("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"); byte outputBytes[] = c14n.canonicalizeSubtree(doc); System.out.println(new String(outputBytes)); }
25. PlutoWebXmlRewriter#parseXml()
Project: portals-pluto
File: PlutoWebXmlRewriter.java
File: PlutoWebXmlRewriter.java
protected static Document parseXml(InputStream source) throws Exception { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId) throws SAXException, java.io.IOException { if (systemId.equals("http://java.sun.com/dtd/web-app_2_3.dtd")) { return new InputSource(getClass().getResourceAsStream("web-app_2_3.dtd")); } return null; } }); Document document = builder.parse(source); return document; }
26. PDXFAResource#getDocument()
Project: pdfbox
File: PDXFAResource.java
File: PDXFAResource.java
/** * Get the XFA content as W3C document. * * @see #getBytes() * * @return the XFA content * * @throws ParserConfigurationException parser exception. * @throws SAXException parser exception. * @throws IOException if something went wrong when reading the XFA content. * */ public Document getDocument() throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(this.getBytes())); }
27. XmlProcessor#getDocumentBuilderFromPool()
Project: pad
File: XmlProcessor.java
File: XmlProcessor.java
private synchronized DocumentBuilder getDocumentBuilderFromPool() throws javax.xml.parsers.ParserConfigurationException { DocumentBuilder result; if (documentBuilder == null) { javax.xml.parsers.DocumentBuilderFactory factory = getDomFactory(); result = factory.newDocumentBuilder(); } else { result = documentBuilder; documentBuilder = null; } result.setErrorHandler(errorHandler); return result; }
28. DomUtils#readXml2()
Project: opensearchserver
File: DomUtils.java
File: DomUtils.java
public static final Document readXml2(final InputSource source) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = getDocumentBuilderFactory(); factory.setValidating(false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = null; db = factory.newDocumentBuilder(); return db.parse(source); }
29. Bug4972882#test1()
Project: openjdk
File: Bug4972882.java
File: Bug4972882.java
@Test public void test1() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI); dbf.setAttribute(SCHEMA_SOURCE, Bug4972882.class.getResource("targetNS00101m2_stub.xsd").toExternalForm()); DocumentBuilder builder = dbf.newDocumentBuilder(); builder.setErrorHandler(new DraconianErrorHandler()); try { builder.parse(Bug4972882.class.getResource("targetNS00101m2_stub.xml").toExternalForm()); Assert.fail("failure expected"); } catch (SAXException e) { Assert.assertTrue(e.getMessage().indexOf("sch-props-correct.2") != -1); } }
30. BasicFunctionalityTest#testXMLWriter()
Project: lucene-solr
File: BasicFunctionalityTest.java
File: BasicFunctionalityTest.java
@Test public void testXMLWriter() throws Exception { SolrQueryResponse rsp = new SolrQueryResponse(); rsp.add("\"quoted\"", "\"value\""); StringWriter writer = new StringWriter(32000); SolrQueryRequest req = req("foo"); XMLWriter.writeResponse(writer, req, rsp); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.parse(new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8))); req.close(); }
31. TMXStreamingOutputTest#writeToXmlWithValidation()
Project: zanata-server
File: TMXStreamingOutputTest.java
File: TMXStreamingOutputTest.java
private Document writeToXmlWithValidation(StreamingOutput output) throws IOException, SAXException { StringBuilderWriter sbWriter = new StringBuilderWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(sbWriter); output.write(writerOutputStream); writerOutputStream.close(); String xml = sbWriter.toString(); assertValidTMX(xml); DocumentBuilder controlParser = XMLUnit.newControlParser(); controlParser.setEntityResolver(new TmxDtdResolver()); Document doc = XMLUnit.buildDocument(controlParser, new StringReader(xml)); return doc; }
32. DomUtilities#readDocument()
Project: WS-Attacker
File: DomUtilities.java
File: DomUtilities.java
/** * Reads an XML file and returns a Document. * * @param file * @return Document * @throws ParserConfigurationException * @throws FileNotFoundException * @throws SAXException * @throws IOException */ public static Document readDocument(InputStream is) throws SAXException, IOException { DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance(); fac.setNamespaceAware(true); // fac.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = null; try { builder = fac.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(String.format("%s.readDocument() could not instantiate DocumentBuilderFactory. This should never happen", DomUtilities.class.getName()), e); } return builder.parse(is); }
33. XmlConverter#toDOMSourceFromStream()
Project: camel
File: XmlConverter.java
File: XmlConverter.java
@Converter public DOMSource toDOMSourceFromStream(StreamSource source, Exchange exchange) throws ParserConfigurationException, IOException, SAXException { Document document; String systemId = source.getSystemId(); DocumentBuilder builder = getDocumentBuilderFactory(exchange).newDocumentBuilder(); Reader reader = source.getReader(); if (reader != null) { document = builder.parse(new InputSource(reader)); } else { InputStream inputStream = source.getInputStream(); if (inputStream != null) { InputSource inputsource = new InputSource(inputStream); inputsource.setSystemId(systemId); document = builder.parse(inputsource); } else { throw new IOException("No input stream or reader available on StreamSource: " + source); } } return new DOMSource(document, systemId); }
34. ConfigurationRequestConverter#toXML()
Project: c2mon
File: ConfigurationRequestConverter.java
File: ConfigurationRequestConverter.java
/** * Create an XML string representation of the ProcessConnectionRequest object. * @throws ParserConfigurationException if exception occurs in XML parser * @throws TransformerException if exception occurs in XML parser * @param configurationRequest the request object to convert to XML * @return XML as String */ public synchronized String toXML(final ConfigurationRequest configurationRequest) throws ParserConfigurationException, TransformerException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document dom = builder.newDocument(); Element rootElt = dom.createElement(CONFIGURATION_XML_ROOT); rootElt.setAttribute(CONFIGURATION_ID_ATTRIBUTE, Integer.toString(configurationRequest.getConfigId())); dom.appendChild(rootElt); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); Source source = new DOMSource(dom); transformer.transform(source, result); return writer.getBuffer().toString(); }
35. WorkspaceGeneratorTest#testWorkspaceWithCustomFilePaths()
Project: buck
File: WorkspaceGeneratorTest.java
File: WorkspaceGeneratorTest.java
@Test public void testWorkspaceWithCustomFilePaths() throws Exception { generator.addFilePath(Paths.get("grandparent/parent/Project.xcodeproj"), Optional.of(Paths.get("VirtualParent"))); Path workspacePath = generator.writeWorkspace(); Path contentsPath = workspacePath.resolve("contents.xcworkspacedata"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document workspace = dBuilder.parse(projectFilesystem.newFileInputStream(contentsPath)); assertThat(workspace, hasXPath("/Workspace/Group[@name=\"VirtualParent\"]/FileRef/@location", equalTo("container:grandparent/parent/Project.xcodeproj"))); }
36. WorkspaceGeneratorTest#testNestedWorkspaceContainsCorrectFileRefs()
Project: buck
File: WorkspaceGeneratorTest.java
File: WorkspaceGeneratorTest.java
@Test public void testNestedWorkspaceContainsCorrectFileRefs() throws Exception { generator.addFilePath(Paths.get("./grandparent/parent/Project.xcodeproj")); Path workspacePath = generator.writeWorkspace(); Path contentsPath = workspacePath.resolve("contents.xcworkspacedata"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document workspace = dBuilder.parse(projectFilesystem.newFileInputStream(contentsPath)); assertThat(workspace, hasXPath("/Workspace/Group[@name=\"grandparent\"]/FileRef/@location", equalTo("container:grandparent/parent/Project.xcodeproj"))); }
37. WorkspaceGeneratorTest#testFlatWorkspaceContainsCorrectFileRefs()
Project: buck
File: WorkspaceGeneratorTest.java
File: WorkspaceGeneratorTest.java
@Test public void testFlatWorkspaceContainsCorrectFileRefs() throws Exception { generator.addFilePath(Paths.get("./Project.xcodeproj")); Path workspacePath = generator.writeWorkspace(); Path contentsPath = workspacePath.resolve("contents.xcworkspacedata"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document workspace = dBuilder.parse(projectFilesystem.newFileInputStream(contentsPath)); assertThat(workspace, hasXPath("/Workspace[@version = \"1.0\"]")); assertThat(workspace, hasXPath("/Workspace/FileRef/@location", equalTo("container:Project.xcodeproj"))); }
38. InOutCurrentTest#setUp()
Project: bioformats
File: InOutCurrentTest.java
File: InOutCurrentTest.java
@Parameters({ "mockClassName" }) @BeforeClass public void setUp(@Optional String mockClassName) throws Exception { if (mockClassName == null) { mockClassName = "loci.formats.utests.ObjectBasedOMEModelMock"; } Class mockClass = Class.forName(mockClassName); Constructor constructor = mockClass.getDeclaredConstructor(); mock = (OMEModelMock) constructor.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); document = parser.newDocument(); ome = (OMEXMLMetadataRoot) mock.getRoot(); // Produce a valid OME DOM element hierarchy Element root = ome.asXMLElement(document); root.setAttribute("xmlns", XML_NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xsi:schemaLocation", XML_NS + " " + SCHEMA_LOCATION); document.appendChild(root); // Produce string XML asString = asString(); }
39. SPWModelReaderTest#writeMockToFile()
Project: bioformats
File: SPWModelReaderTest.java
File: SPWModelReaderTest.java
/** * Writes a model mock to a file as XML. * @param mock Mock to build a DOM tree of and serialize to XML. * @param file File to write serialized XML to. * @param withBinData Whether or not to do BinData post processing. * @throws Exception If there is an error writing the XML to the file. */ public static void writeMockToFile(ModelMock mock, File file, boolean withBinData) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = mock.getRoot().asXMLElement(document); SPWModelMock.postProcess(root, document, withBinData); // Write the OME DOM to the requested file OutputStream stream = new FileOutputStream(file); stream.write(SPWModelMock.asString(document).getBytes()); }
40. SPWModelMock#main()
Project: bioformats
File: SPWModelMock.java
File: SPWModelMock.java
public static void main(String[] args) throws Exception { SPWModelMock mock = new SPWModelMock(false); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = mock.ome.asXMLElement(document); SPWModelMock.postProcess(root, document, true); // Produce string XML OutputStream outputStream = new FileOutputStream(args[0]); outputStream.write(SPWModelMock.asString(document).getBytes()); }
41. PumpWithLightSourceSettingsTest#testLightSourceType()
Project: bioformats
File: PumpWithLightSourceSettingsTest.java
File: PumpWithLightSourceSettingsTest.java
@Test public void testLightSourceType() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = ome.asXMLElement(document); SPWModelMock.postProcess(root, document, false); OMEModel model = new OMEModelImpl(); ome = new OME(document.getDocumentElement(), model); model.resolveReferences(); }
42. MapAnnotationTest#testMapAnnotationValid()
Project: bioformats
File: MapAnnotationTest.java
File: MapAnnotationTest.java
@Test public void testMapAnnotationValid() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = ome.asXMLElement(document); SPWModelMock.postProcess(root, document, false); OMEModel model = new OMEModelImpl(); ome = new OME(document.getDocumentElement(), model); model.resolveReferences(); }
43. ImagingEnvironmentMapTest#testGenericExcitationSourceValid()
Project: bioformats
File: ImagingEnvironmentMapTest.java
File: ImagingEnvironmentMapTest.java
@Test public void testGenericExcitationSourceValid() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = ome.asXMLElement(document); SPWModelMock.postProcess(root, document, false); OMEModel model = new OMEModelImpl(); ome = new OME(document.getDocumentElement(), model); model.resolveReferences(); }
44. GenericExcitationMapTest#testGenericExcitationSourceValid()
Project: bioformats
File: GenericExcitationMapTest.java
File: GenericExcitationMapTest.java
@Test public void testGenericExcitationSourceValid() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = ome.asXMLElement(document); SPWModelMock.postProcess(root, document, false); OMEModel model = new OMEModelImpl(); ome = new OME(document.getDocumentElement(), model); model.resolveReferences(); }
45. BaseModelMock#main()
Project: bioformats
File: BaseModelMock.java
File: BaseModelMock.java
public static void main(String[] args) throws Exception { BaseModelMock mock = new BaseModelMock(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.newDocument(); // Produce a valid OME DOM element hierarchy Element root = mock.ome.asXMLElement(document); SPWModelMock.postProcess(root, document, true); // Produce string XML OutputStream outputStream = new FileOutputStream(args[0]); outputStream.write(SPWModelMock.asString(document).getBytes()); }
46. XMLWindow#setXML()
Project: bioformats
File: XMLWindow.java
File: XMLWindow.java
/** Displays XML from the given file. */ public void setXML(File file) throws ParserConfigurationException, SAXException, IOException { setDocument(null); // parse XML from file into DOM structure DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance(); DocumentBuilder db = docFact.newDocumentBuilder(); Document doc = db.parse(file); setDocument(doc); }
47. XMLWindow#setXML()
Project: bioformats
File: XMLWindow.java
File: XMLWindow.java
// -- XMLWindow methods -- /** Displays XML from the given string. */ public void setXML(String xml) throws ParserConfigurationException, SAXException, IOException { setDocument(null); // parse XML from string into DOM structure DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance(); DocumentBuilder db = docFact.newDocumentBuilder(); ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes(Constants.ENCODING)); Document doc = db.parse(is); is.close(); setDocument(doc); }
48. OMEXMLServiceImpl#isEqual()
Project: bioformats
File: OMEXMLServiceImpl.java
File: OMEXMLServiceImpl.java
/** @see OMEXMLService#isEqual(OMEXMLMetadata, OMEXMLMetadata) */ @Override public boolean isEqual(OMEXMLMetadata src1, OMEXMLMetadata src2) { src1.resolveReferences(); src2.resolveReferences(); OMEXMLMetadataRoot omeRoot1 = (OMEXMLMetadataRoot) src1.getRoot(); OMEXMLMetadataRoot omeRoot2 = (OMEXMLMetadataRoot) src2.getRoot(); DocumentBuilder builder = null; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { return false; } Document doc1 = builder.newDocument(); Document doc2 = builder.newDocument(); Element root1 = omeRoot1.asXMLElement(doc1); Element root2 = omeRoot2.asXMLElement(doc2); return equals(root1, root2); }
49. ProcessList#parse()
Project: binnavi
File: ProcessList.java
File: ProcessList.java
/** * Parses a process list in binary form. * * @param data The binary data. * * @return The parsed process list. * * @throws ParserConfigurationException Thrown if there was a problem with the parser * configuration. * @throws SAXException Thrown if the process list could not be parsed. * @throws IOException Thrown if the process list could not be read. */ public static ProcessList parse(final byte[] data) throws ParserConfigurationException, SAXException, IOException { final List<ProcessDescription> processes = new ArrayList<>(); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(new ByteArrayInputStream(data, 0, data.length)); final NodeList nodes = document.getFirstChild().getChildNodes(); for (int i = 0; i < nodes.getLength(); ++i) { final Node node = nodes.item(i); final String nodeName = node.getNodeName(); if ("Process".equals(nodeName)) { final String pid = node.getAttributes().getNamedItem("pid").getNodeValue(); final String name = node.getAttributes().getNamedItem("name").getNodeValue(); processes.add(new ProcessDescription(Integer.valueOf(pid), name)); } else { NaviLogger.severe("Error: Unknown node name " + nodeName); } } return new ProcessList(processes); }
50. InvokeDecoder#Domparser()
Project: BeanSpy
File: InvokeDecoder.java
File: InvokeDecoder.java
/** * <p> * Helper DOM parser to retrieve data from an XML document * </p> * * @param inputXml * input XML document to parse * @param xpathQuery * XPath query for the document * * @throws XPathExpressionException * represents an error in an XPath expression. * @throws ParserConfigurationException * Indicates a serious configuration error. * @throws SAXException * Encapsulate a general SAX error or warning * @throws IOException * Signals that an I/O exception of some sort has occurred. */ static NodeList Domparser(String inputXml, String xpathQuery) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); StringReader input = new StringReader(inputXml); Document doc = builder.parse(new InputSource(input)); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); XPathExpression expr = xpath.compile(xpathQuery); NodeList results = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); return results; }
51. ManifestMergerAction#removePermissions()
Project: bazel
File: ManifestMergerAction.java
File: ManifestMergerAction.java
private static Path removePermissions(Path manifest, Path outputDir) throws IOException, ParserConfigurationException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError, SAXException { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = docBuilder.parse(manifest.toFile()); for (String tag : PERMISSION_TAGS) { NodeList permissions = doc.getElementsByTagName(tag); if (permissions != null) { for (int i = permissions.getLength() - 1; i >= 0; i--) { Node permission = permissions.item(i); permission.getParentNode().removeChild(permission); } } } Path output = outputDir.resolve(manifest.getFileName()); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), new StreamResult(output.toFile())); return output; }
52. ParseXMLUtilMethods#parseFile()
Project: azure-tools-for-java
File: ParseXMLUtilMethods.java
File: ParseXMLUtilMethods.java
/** Parses XML file and returns XML document. * @param fileName XML file to parse * @return XML document or <B>null</B> if error occurred * @throws Exception object */ public static Document parseFile(String fileName) throws Exception { DocumentBuilder docBuilder; Document doc = null; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringElementContentWhitespace(true); try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new Exception(pXMLParseExcp, e); } File sourceFile = new File(fileName); try { doc = docBuilder.parse(sourceFile); } catch (SAXException e) { throw new Exception(pXMLParseExcp, e); } catch (IOException e) { throw new Exception(pXMLParseExcp, e); } return doc; }
53. StatelessFilterCommand#getAssertionFromDefaltedContent()
Project: azure-tools-for-java
File: StatelessFilterCommand.java
File: StatelessFilterCommand.java
protected SAMLAssertion getAssertionFromDefaltedContent(String deflatedAssertionXML, TrustParameters trustParams, HttpServletRequest httpRequest) throws IOException, DataFormatException, ParserConfigurationException, SAXException, AssertionNotFoundException, Exception { byte[] assertionXML = inflateAssertionXML(deflatedAssertionXML); assertionXML = Utils.decrypt(trustParams.getSecretKey(), assertionXML); Utils.logDebug("Assertion received in the cookie is :" + Utils.getStringFromUTF8Bytes(assertionXML), LOG); // load into xml DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); // very important docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new ByteArrayInputStream(assertionXML)); return SAMLAssertion.getAssertionFromAssertionDocument(doc); }
54. ACSFederationAuthFilter#getSAMLAssertionFromACSResponse()
Project: azure-tools-for-java
File: ACSFederationAuthFilter.java
File: ACSFederationAuthFilter.java
SAMLAssertion getSAMLAssertionFromACSResponse(HttpServletRequest request) { String securityTokenResponse = request.getParameter("wresult"); Utils.logDebug("wsresult in the response from ACS is " + securityTokenResponse, LOG); if (securityTokenResponse == null) { return null; } // None of Java XML objects are thread-safe. Better to create instance on demand rather than caching. DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); // very important, must docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder; SAMLAssertion assertion = null; try { docBuilder = docBuilderFactory.newDocumentBuilder(); Document respDoc = docBuilder.parse(new ByteArrayInputStream(Utils.getUTF8Bytes(securityTokenResponse))); // Find the response token Element responseToken = (Element) respDoc.getDocumentElement().getElementsByTagNameNS("http://schemas.xmlsoap.org/ws/2005/02/trust", "RequestedSecurityToken").item(0); assertion = SAMLAssertion.getAssertionFromSecurityToken(responseToken); } catch (Exception e) { Utils.logError("Exception while parsing the security token response from ACS.", e, LOG); } return assertion; }
55. XMLUtil#parseXMLFile()
Project: azure-tools-for-java
File: XMLUtil.java
File: XMLUtil.java
/** * Parses contents of given XML file and returns DOM Object * @param fileName Path of XML file * @return * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public static Document parseXMLFile(final File xmlFile) throws ParserConfigurationException, SAXException, IOException { if (xmlFile == null) return null; Document doc = null; DocumentBuilder docBuilder; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringElementContentWhitespace(true); docBuilder = docBuilderFactory.newDocumentBuilder(); doc = docBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); return doc; }
56. XmlHelper#getXMLValue()
Project: azure-tools-for-java
File: XmlHelper.java
File: XmlHelper.java
public static Object getXMLValue(String xml, String xQuery, QName resultType) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(xml))); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xPath = xPathfactory.newXPath(); XPathExpression xPathExpression = xPath.compile(xQuery); return xPathExpression.evaluate(doc, resultType); }
57. ParseXML#parseFile()
Project: azure-tools-for-java
File: ParseXML.java
File: ParseXML.java
/** * Parses XML file and returns XML document. * * @param fileName XML file to parse * @return XML document or <B>null</B> if error occurred * @throws Exception object */ static Document parseFile(String fileName) throws Exception { DocumentBuilder docBuilder; Document doc = null; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringElementContentWhitespace(true); try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new Exception(AzureBundle.message("pXMLParseExcp")); } File sourceFile = new File(fileName); try { doc = docBuilder.parse(sourceFile); } catch (SAXException e) { throw new Exception(AzureBundle.message("pXMLParseExcp")); } catch (IOException e) { throw new Exception(AzureBundle.message("pXMLParseExcp")); } return doc; }
58. ParseXML#parseFile()
Project: Azure-Toolkit-for-IntelliJ
File: ParseXML.java
File: ParseXML.java
/** * Parses XML file and returns XML document. * * @param fileName XML file to parse * @return XML document or <B>null</B> if error occurred * @throws Exception object */ static Document parseFile(String fileName) throws Exception { DocumentBuilder docBuilder; Document doc = null; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringElementContentWhitespace(true); try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new Exception(AzureBundle.message("pXMLParseExcp")); } File sourceFile = new File(fileName); try { doc = docBuilder.parse(sourceFile); } catch (SAXException e) { throw new Exception(AzureBundle.message("pXMLParseExcp")); } catch (IOException e) { throw new Exception(AzureBundle.message("pXMLParseExcp")); } return doc; }
59. ServiceFileCreator#getServiceModel()
Project: axis2-java
File: ServiceFileCreator.java
File: ServiceFileCreator.java
private Document getServiceModel(String serviceName, String className, ArrayList methods) { DocumentBuilder builder = null; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } Document doc = builder.newDocument(); Element rootElement = doc.createElement("interface"); rootElement.setAttribute("classpackage", ""); rootElement.setAttribute("name", className); rootElement.setAttribute("servicename", serviceName); Element methodElement = null; int size = methods.size(); for (int i = 0; i < size; i++) { methodElement = doc.createElement("method"); rootElement.setAttribute("name", methods.get(i).toString()); rootElement.appendChild(methodElement); } doc.appendChild(rootElement); return doc; }
60. ServiceFileCreator#getServiceModel()
Project: axis2-java
File: ServiceFileCreator.java
File: ServiceFileCreator.java
private Document getServiceModel(String serviceName, String className, ArrayList methods) { DocumentBuilder builder = null; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } Document doc = builder.newDocument(); Element rootElement = doc.createElement("interface"); rootElement.setAttribute("classpackage", ""); rootElement.setAttribute("name", className); rootElement.setAttribute("servicename", serviceName); Element methodElement = null; int size = methods.size(); for (int i = 0; i < size; i++) { methodElement = doc.createElement("method"); rootElement.setAttribute("name", methods.get(i).toString()); rootElement.appendChild(methodElement); } doc.appendChild(rootElement); return doc; }
61. SOAPPartTest#_testInputEncoding()
Project: axis2-java
File: SOAPPartTest.java
File: SOAPPartTest.java
public void _testInputEncoding() throws Exception { DOMSource domSource; DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new File(System.getProperty("basedir", ".") + "/test-resources" + File.separator + "soap-part.xml")); domSource = new DOMSource(document); SOAPMessage message = MessageFactory.newInstance().createMessage(); // Get the SOAP part and set its content to domSource SOAPPart soapPart = message.getSOAPPart(); soapPart.setContent(domSource); message.saveChanges(); SOAPPart sp = message.getSOAPPart(); // String inputEncoding = sp.getInputEncoding(); // assertNotNull(inputEncoding); }
62. SOAPEnvelopeTest#createDocument()
Project: axis2-java
File: SOAPEnvelopeTest.java
File: SOAPEnvelopeTest.java
private Element createDocument() throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element getLastTradePrice = document.createElementNS("http://example.com", "m:GetLastTradePrice"); Element symbol = document.createElement("symbol"); getLastTradePrice.appendChild(symbol); org.w3c.dom.Text def = document.createTextNode("DEF"); symbol.appendChild(def); document.appendChild(getLastTradePrice); return getLastTradePrice; }
63. WSDLToAxisServiceBuilder#getDOMDocumentBuilder()
Project: axis2-java
File: WSDLToAxisServiceBuilder.java
File: WSDLToAxisServiceBuilder.java
/** * Utility method that returns a DOM Builder * * @return a namespace-aware DOM DocumentBuilder */ protected DocumentBuilder getDOMDocumentBuilder() { DocumentBuilder documentBuilder; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } return documentBuilder; }
64. WSDL20ToAxisServiceBuilder#readInTheWSDLFile()
Project: axis2-java
File: WSDL20ToAxisServiceBuilder.java
File: WSDL20ToAxisServiceBuilder.java
private Description readInTheWSDLFile(InputStream inputStream) throws WSDLException, AxisFault { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder; Document document; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.parse(inputStream); } catch (ParserConfigurationException e) { throw AxisFault.makeFault(e); } catch (IOException e) { throw AxisFault.makeFault(e); } catch (SAXException e) { throw AxisFault.makeFault(e); } return readInTheWSDLFile(document); }
65. WSDL20ToAxisServiceBuilder#readInTheWSDLFile()
Project: axis2-java
File: WSDL20ToAxisServiceBuilder.java
File: WSDL20ToAxisServiceBuilder.java
private Description readInTheWSDLFile(String wsdlURI) throws WSDLException, AxisFault { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder; Document document; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.parse(wsdlURI); } catch (ParserConfigurationException e) { throw AxisFault.makeFault(e); } catch (IOException e) { throw AxisFault.makeFault(e); } catch (SAXException e) { throw AxisFault.makeFault(e); } return readInTheWSDLFile(document); }
66. DOMSourceDispatchTests#createDOMSourceFromString()
Project: axis2-java
File: DOMSourceDispatchTests.java
File: DOMSourceDispatchTests.java
/** * Create a DOMSource with the provided String as the content * @param input * @return */ private DOMSource createDOMSourceFromString(String input) throws Exception { byte[] bytes = input.getBytes(); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); Document domTree = domBuilder.parse(stream); Node node = domTree.getDocumentElement(); DOMSource domSource = new DOMSource(node); return domSource; }
67. EndpointReferenceUtilsTests#test200408ConversionStartingFromJAXWS()
Project: axis2-java
File: EndpointReferenceUtilsTests.java
File: EndpointReferenceUtilsTests.java
public void test200408ConversionStartingFromJAXWS() throws Exception { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); dbfac.setNamespaceAware(true); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document jaxwsDoc = docBuilder.parse(new InputSource(new StringReader(EPR200408))); Source source = new DOMSource(jaxwsDoc); SubmissionEndpointReference jaxwsEPR = new SubmissionEndpointReference(source); EndpointReference axis2EPR = EndpointReferenceUtils.createAxis2EndpointReference(""); String addressingNamespace = EndpointReferenceUtils.convertToAxis2(axis2EPR, jaxwsEPR); OMElement eprElement = EndpointReferenceHelper.toOM(OMF, axis2EPR, ELEMENT200408, addressingNamespace); assertXMLEqual(EPR200408, eprElement.toString()); SubmissionEndpointReference jaxwsResult = (SubmissionEndpointReference) EndpointReferenceUtils.convertFromAxis2(axis2EPR, Submission.WSA_NAMESPACE); assertXMLEqual(EPR200408, jaxwsResult.toString()); }
68. AbstractSchemaCompilerTester#setUp()
Project: axis2-java
File: AbstractSchemaCompilerTester.java
File: AbstractSchemaCompilerTester.java
protected void setUp() throws Exception { //load the current Schema through a file //first read the file into a DOM DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); Document doc = builder.parse(new File(System.getProperty("basedir", ".") + "/" + fileName)); //now read it to a schema XmlSchemaCollection schemaCol = getSchemaReader(); currentSchema = schemaCol.read(doc, null); outputFolder = new File(TEMP_OUT_FOLDER); if (outputFolder.exists()) { if (outputFolder.isFile()) { outputFolder.delete(); outputFolder.mkdirs(); } } else { outputFolder.mkdirs(); } }
69. XMLUtils#newDocument()
Project: axis1-java
File: XMLUtils.java
File: XMLUtils.java
/** * Get a new Document read from the input source * @return Document * @throws ParserConfigurationException if construction problems occur * @throws SAXException if the document has xml sax problems * @throws IOException if i/o exceptions occur */ public static Document newDocument(InputSource inp) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder db = null; try { db = getDocumentBuilder(); try { db.setEntityResolver(DefaultEntityResolver.INSTANCE); } catch (Throwable t) { log.debug("Failed to set EntityResolver on DocumentBuilder", t); } try { db.setErrorHandler(new XMLUtils.ParserErrorHandler()); } catch (Throwable t) { log.debug("Failed to set ErrorHandler on DocumentBuilder", t); } Document doc = db.parse(inp); return doc; } finally { if (db != null) { releaseDocumentBuilder(db); } } }
70. XMLUtils#newDocument()
Project: axis1-java
File: XMLUtils.java
File: XMLUtils.java
/** * Get an empty new Document * * @return Document * @throws ParserConfigurationException if construction problems occur */ public static Document newDocument() throws ParserConfigurationException { DocumentBuilder db = null; try { db = getDocumentBuilder(); Document doc = db.newDocument(); return doc; } finally { if (db != null) { releaseDocumentBuilder(db); } } }
71. EclipseProcessorCommand#getProjectName()
Project: artemis-odb
File: EclipseProcessorCommand.java
File: EclipseProcessorCommand.java
private String getProjectName() { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new File(projectFolder, ".project")); doc.getDocumentElement().normalize(); XPathFactory xFactory = XPathFactory.newInstance(); XPath xpath = xFactory.newXPath(); XPathExpression expr = xpath.compile("/projectDescription/name/text()"); return (String) expr.evaluate(doc, XPathConstants.STRING); } catch (Exception e) { throw new RuntimeException(e); } }
72. PageExtract#getXmlChildren()
Project: apps-android-wikipedia
File: PageExtract.java
File: PageExtract.java
/** * Parse the given HTML string and return a list of the immediate XML child nodes of that HTML. * * @param html HTML contents. * @return The list of XML child nodes, or null if there was an error. */ private NodeList getXmlChildren(String html) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { L.e(e); return null; } InputSource inputSource = new InputSource(new StringReader("<dummy>" + html + "</dummy>")); Document document; try { document = builder.parse(inputSource); } catch (Exception e) { L.e(e); return null; } return document.getFirstChild().getChildNodes(); }
73. XmlAgentConfigurationBuilder#getTopTag()
Project: ApplicationInsights-Java
File: XmlAgentConfigurationBuilder.java
File: XmlAgentConfigurationBuilder.java
public Element getTopTag(File configurationFile) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(configurationFile); doc.getDocumentElement().normalize(); NodeList topTags = doc.getElementsByTagName(MAIN_TAG); if (topTags == null || topTags.getLength() == 0) { return null; } Node topNodeTag = topTags.item(0); if (topNodeTag.getNodeType() != Node.ELEMENT_NODE) { return null; } Element topElementTag = (Element) topNodeTag; return topElementTag; }
74. StramWebServicesTest#verifyAMInfoXML()
Project: apex-core
File: StramWebServicesTest.java
File: StramWebServicesTest.java
void verifyAMInfoXML(String xml, TestAppContext ctx) 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 nodes = dom.getElementsByTagName(StramWebServices.PATH_INFO); assertEquals("incorrect number of elements", 1, nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); verifyAMInfoGeneric(ctx, getXmlString(element, "id"), getXmlString(element, "user"), getXmlString(element, "name"), getXmlLong(element, "startTime"), getXmlLong(element, "elapsedTime")); } }
75. MissionParser#getDocumentFromInputStream()
Project: android-play-games-in-motion
File: MissionParser.java
File: MissionParser.java
/** * Creates a Document given an InputStream. * @param missionStream The stream to open a document from. * @return The document, successfully parsed from xml. * @throws MissionParseException */ private static Document getDocumentFromInputStream(InputStream missionStream) throws MissionParseException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); throw new MissionParseException("ParserConfigurationException while reading mission."); } Document doc; try { doc = builder.parse(missionStream); } catch (SAXException e) { e.printStackTrace(); throw new MissionParseException("SAXException while reading mission."); } catch (IOException e) { e.printStackTrace(); throw new MissionParseException("IOException while reading mission."); } return doc; }
76. LDAPUserStoreTest#testConfigure()
Project: airavata
File: LDAPUserStoreTest.java
File: LDAPUserStoreTest.java
public void testConfigure() throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(this.getClass().getClassLoader().getResourceAsStream("ldap-authenticator.xml")); doc.getDocumentElement().normalize(); NodeList configurations = doc.getElementsByTagName("specificConfigurations"); UserStore userStore = new LDAPUserStore(); userStore.configure(configurations.item(0)); assertTrue(userStore.authenticate("amilaj", "secret")); }
77. JDBCUserStoreTest#testAuthenticate()
Project: airavata
File: JDBCUserStoreTest.java
File: JDBCUserStoreTest.java
@Test public void testAuthenticate() throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(this.getClass().getClassLoader().getResourceAsStream("jdbc-authenticator.xml")); doc.getDocumentElement().normalize(); NodeList configurations = doc.getElementsByTagName("specificConfigurations"); UserStore userStore = new JDBCUserStore(); userStore.configure(configurations.item(0)); Assert.assertTrue(userStore.authenticate("amilaj", "secret")); Assert.assertFalse(userStore.authenticate("amilaj", "1secret")); Assert.assertFalse(userStore.authenticate("lahiru", "1234")); }
78. ConfigurationReader#loadConfigurations()
Project: airavata
File: ConfigurationReader.java
File: ConfigurationReader.java
private void loadConfigurations() throws ParserConfigurationException, IOException, SAXException { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("credential-store/client.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputStream); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("credential-store"); readElementValue(nodeList); }
79. XMLUtil#readerToElement()
Project: activemq-artemis
File: XMLUtil.java
File: XMLUtil.java
public static Element readerToElement(final Reader r) throws Exception { // Read into string StringBuffer buff = new StringBuffer(); int c; while ((c = r.read()) != -1) { buff.append((char) c); } // Quick hardcoded replace, FIXME this is a kludge - use regexp to match properly String s = buff.toString(); StringReader sreader = new StringReader(s); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6529766 factory.setNamespaceAware(true); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(new InputSource(sreader)); return doc.getDocumentElement(); }
80. DMLConfig#parseConfig()
Project: incubator-systemml
File: DMLConfig.java
File: DMLConfig.java
/** * Method to parse configuration * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ private void parseConfig() throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //ignore XML comments factory.setIgnoringComments(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document domTree = null; if (_fileName.startsWith("hdfs:") || // config file from DFS _fileName.startsWith("gpfs:")) { if (!LocalFileUtils.validateExternalFilename(_fileName, true)) throw new IOException("Invalid (non-trustworthy) hdfs config filename."); FileSystem DFS = FileSystem.get(ConfigurationManager.getCachedJobConf()); Path configFilePath = new Path(_fileName); domTree = builder.parse(DFS.open(configFilePath)); } else // config from local file system { if (!LocalFileUtils.validateExternalFilename(_fileName, false)) throw new IOException("Invalid (non-trustworthy) local config filename."); domTree = builder.parse(_fileName); } _xmlRoot = domTree.getDocumentElement(); }
81. ActivityXMLActivitySerializer#fixDateFormats()
Project: incubator-streams
File: ActivityXMLActivitySerializer.java
File: ActivityXMLActivitySerializer.java
private JSONObject fixDateFormats(JSONObject json, String xml) throws Exception { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); Document doc = docBuilder.parse(is); //why? doc.getDocumentElement().normalize(); if (json.optLong("published", -1L) != -1L) { json.put("published", getValueFromXML("published", doc)); } if (json.optLong("updated", -1L) != -1L) { json.put("updated", getValueFromXML("updated", doc)); } if (json.optLong("created", -1L) != -1L) { json.put("created", getValueFromXML("created", doc)); } return json; }
82. DOMUtil#loadDocument()
Project: incubator-openaz
File: DOMUtil.java
File: DOMUtil.java
public static Document loadDocument(InputStream inputStreamDocument) throws DOMStructureException { DocumentBuilder documentBuilder = getDocumentBuilder(); /* * Parse the XML file */ Document document = null; try { document = documentBuilder.parse(inputStreamDocument); if (document == null) { throw new DOMStructureException("Null document returned"); } } catch (Exception ex) { throw new DOMStructureException("Exception loading file from stream: " + ex.getMessage(), ex); } return document; }
83. DOMUtil#loadDocument()
Project: incubator-openaz
File: DOMUtil.java
File: DOMUtil.java
public static Document loadDocument(File fileDocument) throws DOMStructureException { DocumentBuilder documentBuilder = getDocumentBuilder(); /* * Parse the XML file */ Document document = null; try { document = documentBuilder.parse(fileDocument); if (document == null) { throw new DOMStructureException("Null document returned"); } } catch (Exception ex) { throw new DOMStructureException("Exception loading file \"" + fileDocument.getAbsolutePath() + "\": " + ex.getMessage(), ex); } return document; }
84. SimpleObjetWrapperTest#testWontWrapDOM()
Project: incubator-freemarker
File: SimpleObjetWrapperTest.java
File: SimpleObjetWrapperTest.java
@Test public void testWontWrapDOM() throws SAXException, IOException, ParserConfigurationException, TemplateModelException { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader("<doc><sub a='1' /></doc>")); Document doc = db.parse(is); SimpleObjectWrapper sow = new SimpleObjectWrapper(Configuration.VERSION_2_3_22); try { sow.wrap(doc); fail(); } catch (TemplateModelException e) { assertThat(e.getMessage(), containsString("won't wrap")); } }
85. NodeModel#parse()
Project: incubator-freemarker
File: NodeModel.java
File: NodeModel.java
/** * Create a NodeModel from an XML file. * @param removeComments whether to remove all comment nodes * (recursively) from the tree before processing * @param removePIs whether to remove all processing instruction nodes * (recursively from the tree before processing */ public static NodeModel parse(File f, boolean removeComments, boolean removePIs) throws SAXException, IOException, ParserConfigurationException { DocumentBuilder builder = getDocumentBuilderFactory().newDocumentBuilder(); ErrorHandler errorHandler = getErrorHandler(); if (errorHandler != null) builder.setErrorHandler(errorHandler); Document doc = builder.parse(f); if (removeComments) { removeComments(doc); } if (removePIs) { removePIs(doc); } mergeAdjacentText(doc); return wrap(doc); }
86. XmlHelper#getConfigs()
Project: incubator-eagle
File: XmlHelper.java
File: XmlHelper.java
public static Map<String, String> getConfigs(InputStream is) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dt = db.parse(is); Element element = dt.getDocumentElement(); Map<String, String> config = new TreeMap<String, String>(); NodeList propertyList = element.getElementsByTagName("property"); int length = propertyList.getLength(); for (int i = 0; i < length; i++) { Node property = propertyList.item(i); String key = property.getChildNodes().item(0).getTextContent(); String value = property.getChildNodes().item(1).getTextContent(); config.put(key, value); } return config; }
87. TestUtils#marshallUnmarshall()
Project: igv
File: TestUtils.java
File: TestUtils.java
/** * Marshalls {@code inObj} and unmarshalls the result, returning the * unmarshalled version * * @param inObj * @return * @throws Exception */ public static <T> T marshallUnmarshall(T inObj) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); JAXBContext jc = JAXBContext.newInstance(inObj.getClass()); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FRAGMENT, true); //This JAXBElement business is necessary because we don't know if we have @XmlRootElement on inObj JAXBElement inel = new JAXBElement(new QName("", "obj"), inObj.getClass(), inObj); //m.marshal(inel, System.out); m.marshal(inel, doc); Unmarshaller u = jc.createUnmarshaller(); JAXBElement el = (JAXBElement) u.unmarshal(doc, inObj.getClass()); return (T) el.getValue(); }
88. ContainerMemberFactory#replaceNamespace()
Project: idecore
File: ContainerMemberFactory.java
File: ContainerMemberFactory.java
static String replaceNamespace(String originalContents, String newTopLevelNamespace) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(originalContents))); doc.getDocumentElement().removeAttribute("xmlns"); doc.getDocumentElement().setAttribute("xmlns", newTopLevelNamespace); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.getBuffer().toString(); }
89. XmlUtil#createXml()
Project: hutool
File: XmlUtil.java
File: XmlUtil.java
// -------------------------------------------------------------------------------------- Create /** * ??XML??<br> * ???XML???utf8????????????toStr?toFile?????XML????????????? * * @param rootElementName ????? * @return XML?? */ public static Document createXml(String rootElementName) { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = dbf.newDocumentBuilder(); } catch (Exception e) { throw new UtilException("Create xml document error!", e); } Document doc = builder.newDocument(); doc.appendChild(doc.createElement(rootElementName)); return doc; }
90. ChukwaMetricsList#toXml()
Project: HiTune
File: ChukwaMetricsList.java
File: ChukwaMetricsList.java
public String toXml() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement(getRecordType()); doc.appendChild(root); root.setAttribute("ts", getTimestamp() + ""); for (ChukwaMetrics metrics : getMetricsList()) { Element elem = doc.createElement("Metrics"); elem.setAttribute("key", metrics.getKey()); for (Entry<String, String> attr : metrics.getAttributes().entrySet()) { elem.setAttribute(attr.getKey(), attr.getValue()); } root.appendChild(elem); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("indent", "yes"); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); }
91. TestJobTrackerXmlJsp#testXmlWellFormed()
Project: hadoop-mapreduce
File: TestJobTrackerXmlJsp.java
File: TestJobTrackerXmlJsp.java
/** * 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()); }
92. TestJobTrackerXmlJsp#testXmlWellFormed()
Project: hadoop-20
File: TestJobTrackerXmlJsp.java
File: TestJobTrackerXmlJsp.java
/** * 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()); }
93. ConfigManager#getRootElement()
Project: hadoop-20
File: ConfigManager.java
File: ConfigManager.java
/** * Get the root element of the XML document * @return the root element of the XML document * @throws IOException * @throws SAXException * @throws ParserConfigurationException */ private Element getRootElement(String fileName) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringComments(true); DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); Document doc = builder.parse(new File(fileName)); Element root = doc.getDocumentElement(); if (!matched(root, CONFIGURATION_TAG_NAME)) { throw new IOException("Bad " + fileName); } return root; }
94. OpenWeatherMapWI#getXMLStatusFile()
Project: freedomotic
File: OpenWeatherMapWI.java
File: OpenWeatherMapWI.java
private Document getXMLStatusFile(int dom, int moy, int zone, int dst) throws MalformedURLException, SAXException, IOException { //get the xml file from the socket connection DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; try { dBuilder = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { LOG.error(ex.getLocalizedMessage()); } Document doc; String statusFileURL = "http://api.openweathermap.org/data/2.5/weather?APPID=45ff563b52c93b074d3d23e46f6fa6a3&lat=" + latitude + "&lon=" + longitude + "&mode=xml&type=accurate&units=metric"; LOG.info("Getting twilight data from: {}", statusFileURL); doc = dBuilder.parse(new URL(statusFileURL).openStream()); doc.getDocumentElement().normalize(); return doc; }
95. EarthToolsWI#getXMLStatusFile()
Project: freedomotic
File: EarthToolsWI.java
File: EarthToolsWI.java
private Document getXMLStatusFile(int dom, int moy, int zone, int dst) throws MalformedURLException, SAXException, IOException { //get the xml file from the socket connection DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; try { dBuilder = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { LOG.error(ex.getLocalizedMessage()); } Document doc = null; String statusFileURL = null; statusFileURL = "http://new.earthtools.org/sun/" + latitude + "/" + longitude + "/" + dom + "/" + moy + "/" + zone + "/" + dst; LOG.info("Getting twilight data from: {}", statusFileURL); doc = dBuilder.parse(new URL(statusFileURL).openStream()); doc.getDocumentElement().normalize(); return doc; }
96. DocumentHelper#createDocument()
Project: forrest
File: DocumentHelper.java
File: DocumentHelper.java
/** * Creates a document. A xmlns:prefix="namespaceUri" attribute is added to * the document element. * @param namespaceUri The namespace URL of the root element. * @param qualifiedName The qualified name of the root element. * @param documentType The type of document to be created or null. When * doctype is not null, its Node.ownerDocument attribute is set * to the document being created. * @return A new Document object. * @throws DOMException if an error occurs * @throws ParserConfigurationException if an error occurs * @see org.w3c.dom.DOMImplementation#createDocument(String, String, * DocumentType) */ public static Document createDocument(String namespaceUri, String qualifiedName, DocumentType documentType) throws DOMException, ParserConfigurationException { DocumentBuilder builder = createBuilder(); Document document = builder.getDOMImplementation().createDocument(namespaceUri, qualifiedName, documentType); // add xmlns:prefix attribute String name = "xmlns"; int index = qualifiedName.indexOf(":"); if (index > -1) { name += (":" + qualifiedName.substring(0, index)); } document.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/", name, namespaceUri); return document; }
97. DOMUtilities#loadDOM()
Project: forrest
File: DOMUtilities.java
File: DOMUtilities.java
/** * This loads an XML file into a DOM called document * */ public static Document loadDOM(String path) { // Loads the XML file iton the DOM document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser; try { parser = factory.newDocumentBuilder(); document = null; document = parser.parse(new File(path)); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return document; }
98. Echo#getDocument()
Project: flex-blazeds
File: Echo.java
File: Echo.java
/** * * @return a document which multiple namespaces * @throws Exception */ public Document getDocument() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder dbuilder = dbf.newDocumentBuilder(); Document doc = dbuilder.newDocument(); Element root = doc.createElementNS("http://www.adobe.com/qa", "qa:testsuites"); doc.appendChild(root); Element flexunit = doc.createElementNS("http://foo", "foo:flexunit"); root.appendChild(flexunit); flexunit.appendChild(doc.createTextNode("bar")); return doc; }
99. XmlUtil#getDocumentBuilder()
Project: fitnesse
File: XmlUtil.java
File: XmlUtil.java
private static DocumentBuilder getDocumentBuilder() { DocumentBuilder builder = documentBuilder.get(); if (builder == null) { try { builder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } documentBuilder.set(builder); } return builder; }
100. ExportHelper#importCardsXml()
Project: farebot
File: ExportHelper.java
File: ExportHelper.java
public static Uri[] importCardsXml(Context context, String xml) throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xml))); Element rootElement = doc.getDocumentElement(); if (rootElement.getNodeName().equals("card")) { return new Uri[] { importCard(context, rootElement) }; } NodeList cardNodes = rootElement.getElementsByTagName("card"); Uri[] results = new Uri[cardNodes.getLength()]; for (int i = 0; i < cardNodes.getLength(); i++) { results[i] = importCard(context, (Element) cardNodes.item(i)); } return results; }