org.w3c.dom.Document

Here are the examples of the java api class org.w3c.dom.Document taken from open source projects.

1. JAXPTestUtilities#compareDocumentWithGold()

Project: openjdk
Source File: JAXPTestUtilities.java
View license
/**
     * Compare contents of golden file with test output file by their document
     * representation.
     * Here we ignore the white space and comments. return true if they're
     * lexical identical.
     * @param goldfile Golden output file name.
     * @param resultFile Test output file name.
     * @return true if two file's document representation are identical.
     *         false if two file's document representation are not identical.
     * @throws javax.xml.parsers.ParserConfigurationException if the
     *         implementation is not available or cannot be instantiated.
     * @throws SAXException If any parse errors occur.
     * @throws IOException if an I/O error occurs reading from the file or a
     *         malformed or unmappable byte sequence is read .
     */
public static boolean compareDocumentWithGold(String goldfile, String resultFile) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setCoalescing(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setIgnoringComments(true);
    DocumentBuilder db = factory.newDocumentBuilder();
    Document goldD = db.parse(Paths.get(goldfile).toFile());
    goldD.normalizeDocument();
    Document resultD = db.parse(Paths.get(resultFile).toFile());
    resultD.normalizeDocument();
    return goldD.isEqualNode(resultD);
}

2. SAMLUtilsTest#equals()

Project: rampart
Source File: SAMLUtilsTest.java
View license
private static boolean equals(String element1, String element2) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setCoalescing(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setIgnoringComments(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc1 = db.parse(new ByteArrayInputStream(element1.getBytes("UTF-8")));
    doc1.normalizeDocument();
    Document doc2 = db.parse(new ByteArrayInputStream(element1.getBytes("UTF-8")));
    doc2.normalizeDocument();
    return doc1.isEqualNode(doc2);
}

3. DOMBuilderStreamerTestCase#testTestFacility()

View license
public void testTestFacility() throws Exception {
    Document document = XMLUnit.getControlParser().newDocument();
    Element elemA = document.createElement("root");
    document.appendChild(elemA);
    Document oneElementDocument = XMLUnit.buildControlDocument("<root/>");
    assertXMLEqual(oneElementDocument, document);
    document = XMLUnit.getControlParser().newDocument();
    elemA = document.createElement("node");
    document.appendChild(elemA);
    oneElementDocument = XMLUnit.buildControlDocument("<root/>");
    assertXMLNotEqual(oneElementDocument, document);
}

4. ConfigurationObjectFactoryTest#testEquipmentUnitRemove()

View license
@Test
public void testEquipmentUnitRemove() throws NoSuchFieldException, IllegalAccessException, ParserConfigurationException, SAXException, IOException, NoSimpleValueParseException, InstantiationException {
    Document document = getDocument(TEST_EQUIPMENT_UNIT_REM_XML);
    Element eqUnitRemElement = (Element) document.getElementsByTagName("EquipmentUnitRemove").item(0);
    EquipmentUnitRemove eqUnitRem = objectFactory.createEquipmentUnitRemove(eqUnitRemElement);
    assertEquals(1, eqUnitRem.getChangeId());
    assertEquals(2, eqUnitRem.getEquipmentId());
    // now try to recreate DOM from the EquipmentUnitRemove event object
    DOMFactory factory = new DOMFactory();
    Document document2 = factory.createDocument();
    Element element = factory.generateSimpleElement(document2, eqUnitRem, new String[0]);
    document2.appendChild(element);
    Element eqUnitRemElement2 = (Element) document2.getElementsByTagName("EquipmentUnitRemove").item(0);
    EquipmentUnitRemove eqUnitRem2 = objectFactory.createEquipmentUnitRemove(eqUnitRemElement2);
    // both ids should be the same
    assertEquals(eqUnitRem.getChangeId(), eqUnitRem2.getChangeId());
    // both equipment xmls should be the same
    assertEquals(eqUnitRem.getEquipmentId(), eqUnitRem2.getEquipmentId());
}

5. DOMBuilderStreamerTestCase#testStreamer()

View license
public void testStreamer() throws Exception {
    Document document = XMLUnit.getControlParser().newDocument();
    Element elemA = document.createElement("root");
    document.appendChild(elemA);
    Element elemB = document.createElement("node");
    elemA.appendChild(elemB);
    elemB = document.createElement("node");
    elemA.appendChild(elemB);
    DOMBuilder builder = new DOMBuilder();
    DOMStreamer streamer = new DOMStreamer(builder);
    streamer.stream(document);
    document = builder.getDocument();
    Document moreElementDocument = XMLUnit.buildControlDocument("<root><node/><node/></root>");
    assertXMLEqual(moreElementDocument, document);
}

6. XmlRequestEntityTest#testXmlSerialization()

View license
public void testXmlSerialization() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    doc.appendChild(doc.createElementNS("DAV:", "propfind"));
    XmlRequestEntity xmlent = new XmlRequestEntity(doc);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    xmlent.writeRequest(bos);
    Document doc2 = db.parse(new ByteArrayInputStream(bos.toByteArray()));
    Element docelem = doc2.getDocumentElement();
    assertEquals("DAV:", docelem.getNamespaceURI());
}

7. BaseSAML2BindingBuilder#signAssertion()

View license
public void signAssertion(Document samlDocument) throws ProcessingException {
    Element originalAssertionElement = org.keycloak.saml.common.util.DocumentUtil.getChildElement(samlDocument.getDocumentElement(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
    if (originalAssertionElement == null)
        return;
    Node clonedAssertionElement = originalAssertionElement.cloneNode(true);
    Document temporaryDocument;
    try {
        temporaryDocument = org.keycloak.saml.common.util.DocumentUtil.createDocument();
    } catch (ConfigurationException e) {
        throw new ProcessingException(e);
    }
    temporaryDocument.adoptNode(clonedAssertionElement);
    temporaryDocument.appendChild(clonedAssertionElement);
    signDocument(temporaryDocument);
    samlDocument.adoptNode(clonedAssertionElement);
    Element parentNode = (Element) originalAssertionElement.getParentNode();
    parentNode.replaceChild(clonedAssertionElement, originalAssertionElement);
}

8. WSDL20Endpoint#fromMap()

Project: ode
Source File: WSDL20Endpoint.java
View license
public void fromMap(Map eprMap) {
    Document doc = DOMUtils.newDocument();
    Element serviceRef = doc.createElementNS(SERVICE_REF_QNAME.getNamespaceURI(), SERVICE_REF_QNAME.getLocalPart());
    doc.appendChild(serviceRef);
    _serviceElmt = doc.createElementNS(Namespaces.WSDL_20, "service");
    _serviceElmt.setAttribute("name", "");
    _serviceElmt.setAttribute("interface", "");
    serviceRef.appendChild(_serviceElmt);
    Element endpoint = doc.createElementNS(Namespaces.WSDL_20, "endpoint");
    endpoint.setAttribute("name", "");
    endpoint.setAttribute("binding", "");
    if (eprMap.get(ADDRESS) != null)
        endpoint.setAttribute("address", (String) eprMap.get(ADDRESS));
    if (eprMap.get(SESSION) != null) {
        Element session = doc.createElementNS(Namespaces.ODE_SESSION_NS, "session");
        session.setTextContent((String) eprMap.get(SESSION));
        endpoint.appendChild(session);
        // plus the deprecated intalio header
        session = doc.createElementNS(Namespaces.INTALIO_SESSION_NS, "session");
        session.setTextContent((String) eprMap.get(SESSION));
        endpoint.appendChild(session);
    }
    _serviceElmt.appendChild(endpoint);
    doc.appendChild(_serviceElmt);
}

9. SchemaAnalyzerTest#testGetExpandedAnalyzingDocument()

Project: WS-Attacker
Source File: SchemaAnalyzerTest.java
View license
/**
     * Test of getExpandedAnalyzingDocument method, of class SchemaAnalyzerImpl.
     */
@Test
public void testGetExpandedAnalyzingDocument() throws Exception {
    SchemaAnalyzerImpl instance = new SchemaAnalyzerImpl();
    instance.appendSchema(DOC_SOAP11);
    Document expResult = DomUtilities.readDocument(SOAP11_PATH_TO_EXPANDED_XML);
    Document toTest = DomUtilities.readDocument(SOAP11_PATH_TO_ENVELOPE_ELEMENT_XML);
    String toTestAsString = DomUtilities.domToString(toTest);
    instance.findExpansionPoint(toTest.getDocumentElement());
    Document result = instance.getExpandedAnalyzingDocument();
    assertEquals("Did not get expected expanded document", DomUtilities.domToString(expResult, false), DomUtilities.domToString(result, false));
    assertEquals("Analysing Document should not be touched", toTestAsString, DomUtilities.domToString(toTest, false));
}

10. CryptoProviderTest#testSignatureEmailAddress()

Project: wss4j
Source File: CryptoProviderTest.java
View license
/**
     * Like before but substitute in an "EMAILADDRESS" instead of the OID
     * @throws Exception
     */
@Test
public void testSignatureEmailAddress() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecSignature sign = new WSSecSignature();
    sign.setUserInfo("wss86", "security");
    sign.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
    WSSecHeader secHeader = new WSSecHeader(doc);
    secHeader.insertSecurityHeader();
    Document signedDoc = sign.build(doc, crypto, secHeader);
    String outputString = XMLUtils.prettyDocumentToString(signedDoc);
    outputString = outputString.replace("1.2.840.113549.1.9.1=#16125765726e6572406578616d706c652e636f6d", "[email protected]");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    InputStream is = new ByteArrayInputStream(outputString.getBytes());
    Document parsedDoc = dbf.newDocumentBuilder().parse(is);
    verify(parsedDoc);
}

11. CryptoProviderTest#testSignatureOtherEmailAddress()

Project: wss4j
Source File: CryptoProviderTest.java
View license
/**
     * Like before but substitute in an "E" instead of the OID
     * @throws Exception
     */
@Test
public void testSignatureOtherEmailAddress() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecSignature sign = new WSSecSignature();
    sign.setUserInfo("wss86", "security");
    sign.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
    WSSecHeader secHeader = new WSSecHeader(doc);
    secHeader.insertSecurityHeader();
    Document signedDoc = sign.build(doc, crypto, secHeader);
    String outputString = XMLUtils.prettyDocumentToString(signedDoc);
    outputString = outputString.replace("1.2.840.113549.1.9.1=#16125765726e6572406578616d706c652e636f6d", "[email protected]");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    InputStream is = new ByteArrayInputStream(outputString.getBytes());
    Document parsedDoc = dbf.newDocumentBuilder().parse(is);
    verify(parsedDoc);
}

12. SignatureEncryptionTest#testSigningEncryption()

Project: wss4j
Source File: SignatureEncryptionTest.java
View license
/**
     * Test that signs and then encrypts a WS-Security envelope, then performs
     * decryption and verification <p/>
     *
     * @throws Exception
     *             Thrown when there is any problem in signing, encryption,
     *             decryption, or verification
     */
@Test
public void testSigningEncryption() throws Exception {
    WSSecEncrypt encrypt = new WSSecEncrypt();
    WSSecSignature sign = new WSSecSignature();
    encrypt.setUserInfo("wss40");
    sign.setUserInfo("wss40", "security");
    LOG.info("Before Encryption....");
    Document doc = SOAPUtil.toSOAPPart(SOAPMSG);
    WSSecHeader secHeader = new WSSecHeader(doc);
    secHeader.insertSecurityHeader();
    Document signedDoc = sign.build(doc, crypto, secHeader);
    Document encryptedSignedDoc = encrypt.build(signedDoc, crypto, secHeader);
    LOG.info("After Encryption....");
    verify(encryptedSignedDoc);
}

13. SignatureEncryptionTest#testSigningEncryptionSOAP12Fault()

Project: wss4j
Source File: SignatureEncryptionTest.java
View license
@Test
public void testSigningEncryptionSOAP12Fault() throws Exception {
    WSSecEncrypt encrypt = new WSSecEncrypt();
    WSSecSignature sign = new WSSecSignature();
    encrypt.setUserInfo("wss40");
    sign.setUserInfo("wss40", "security");
    LOG.info("Before Encryption....");
    Document doc = SOAPUtil.toSOAPPart(SAMPLE_SOAP12_FAULT_MSG);
    WSSecHeader secHeader = new WSSecHeader(doc);
    secHeader.insertSecurityHeader();
    Document signedDoc = sign.build(doc, crypto, secHeader);
    Document encryptedSignedDoc = encrypt.build(signedDoc, crypto, secHeader);
    LOG.info("After Encryption....");
    verify(encryptedSignedDoc);
}

14. SignatureTest#testDoubleX509SignatureThumb()

Project: wss4j
Source File: SignatureTest.java
View license
/**
     * Test that signs (twice) and verifies a WS-Security envelope.
     * The test uses the ThumbprintSHA1 key identifier type.
     * <p/>
     *
     * @throws java.lang.Exception Thrown when there is any problem in signing or verification
     */
@Test
public void testDoubleX509SignatureThumb() throws Exception {
    WSSecSignature builder = new WSSecSignature();
    builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
    builder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader(doc);
    secHeader.insertSecurityHeader();
    Document signedDoc = builder.build(doc, crypto, secHeader);
    Document signedDoc1 = builder.build(signedDoc, crypto, secHeader);
    verify(signedDoc1);
}

15. XMLUtil#readerToElement()

Project: activemq-artemis
Source File: XMLUtil.java
View license
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();
}

16. RepositoryDescriptorGenerator#generateRepositoryDescriptor()

View license
public static Document generateRepositoryDescriptor(String name, Collection<org.osgi.resource.Resource> resources) throws ParserConfigurationException {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element rootElement = document.createElement("repository");
    rootElement.setAttribute("name", name);
    document.appendChild(rootElement);
    for (org.osgi.resource.Resource resource : resources) {
        Element element = document.createElement("resource");
        String version = String.valueOf(ResourceHelper.getVersionAttribute(resource));
        element.setAttribute(Resource.VERSION, version);
        element.setAttribute("uri", ResourceHelper.getContentAttribute(resource));
        String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource);
        element.setAttribute(Resource.SYMBOLIC_NAME, symbolicName);
        element.setAttribute(Resource.PRESENTATION_NAME, symbolicName);
        element.setAttribute(Resource.ID, symbolicName + "/" + version);
        rootElement.appendChild(element);
        addRequirements(document, element, resource);
    }
    return document;
}

17. DTConfiguration#loadFile()

Project: apex-core
Source File: DTConfiguration.java
View license
public void loadFile(File file, Scope defaultScope) throws IOException, ParserConfigurationException, SAXException, ConfigException {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
    Element documentElement = doc.getDocumentElement();
    if (!documentElement.getNodeName().equals("configuration")) {
        throw new ConfigException("Root element needs to be \"configuration\"");
    }
    if (doc.hasChildNodes()) {
        NodeList propertyNodes = documentElement.getChildNodes();
        for (int i = 0; i < propertyNodes.getLength(); i++) {
            Node propertyNode = propertyNodes.item(i);
            if (propertyNode.getNodeType() == Node.ELEMENT_NODE) {
                if (propertyNode.getNodeName().equals("property")) {
                    processPropertyNode((Element) propertyNode, defaultScope);
                } else {
                    LOG.warn("Ignoring unknown element {}", propertyNode.getNodeName());
                }
            }
        }
    }
}

18. RepositoryDescriptorGenerator#generateRepositoryDescriptor()

View license
public static Document generateRepositoryDescriptor(String name, Collection<org.osgi.resource.Resource> resources) throws ParserConfigurationException {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element rootElement = document.createElement("repository");
    rootElement.setAttribute("name", name);
    document.appendChild(rootElement);
    for (org.osgi.resource.Resource resource : resources) {
        Element element = document.createElement("resource");
        String version = String.valueOf(ResourceHelper.getVersionAttribute(resource));
        element.setAttribute(Resource.VERSION, version);
        element.setAttribute("uri", ResourceHelper.getContentAttribute(resource));
        String symbolicName = ResourceHelper.getSymbolicNameAttribute(resource);
        element.setAttribute(Resource.SYMBOLIC_NAME, symbolicName);
        element.setAttribute(Resource.PRESENTATION_NAME, symbolicName);
        element.setAttribute(Resource.ID, symbolicName + "/" + version);
        rootElement.appendChild(element);
        addRequirements(document, element, resource);
    }
    return document;
}

19. TestImport#testImports()

Project: axis1-java
Source File: TestImport.java
View license
public void testImports() throws Exception {
    //DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    //DocumentBuilder db = dbf.newDocumentBuilder();
    //Document doc1 = db.parse(new ByteArrayInputStream(SAMPLE_1.getBytes()));
    Document doc2 = testImportFromSaajToDom();
    Document body = testImportFromDomToSaaj(doc2);
    XMLUtils.PrettyDocumentToStream(body, System.out);
//assertXMLEqual(doc1, body);
//assertXMLEqual(doc2, body);
//assertXMLEqual(doc1, doc2);
}

20. SOAPMonitor#getNewDocumentAsNode()

Project: axis1-java
Source File: SOAPMonitor.java
View license
/**
     * Get a new document which has the specified node as the document root
     * 
     * @param target 
     * @return 
     */
private Document getNewDocumentAsNode(Node target) {
    Document doc = null;
    Node node = null;
    try {
        doc = XMLUtils.newDocument();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    node = doc.importNode(target, true);
    doc.appendChild(node);
    return doc;
}

21. ADBXMLStreamReaderTest#testNullableAttribute()

View license
/** Test a completely null element */
public void testNullableAttribute() throws Exception {
    /*
        This is what I expect :

        */
    String exptectedXML = "<Person xmlns=\"\"><Name xmlns=\"\">FooOne</Name><DependentOne xmlns=\"\" " + "xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>" + "</Person>";
    ArrayList propertyList = new ArrayList();
    propertyList.add("Name");
    propertyList.add("FooOne");
    propertyList.add(new QName("DependentOne"));
    propertyList.add(null);
    QName projectQName = new QName("Person");
    XMLStreamReader pullParser = new ADBXMLStreamReaderImpl(projectQName, propertyList.toArray(), null);
    Document actualDom = newDocument(getStringXML(pullParser));
    Document expectedDocument = newDocument(exptectedXML);
    assertXMLEqual(actualDom, expectedDocument);
}

22. AxisServiceBasedMultiLanguageEmitter#createDOMDocumentForException()

View license
/**
     * Generates the model for the callbacks.
     */
protected Document createDOMDocumentForException() {
    Document doc = getEmptyDocument();
    Element rootElement = doc.createElement("callback");
    addAttribute(doc, "package", codeGenConfiguration.getPackageName(), rootElement);
    addAttribute(doc, "name", makeJavaClassName(axisService.getName()) + CALL_BACK_HANDLER_SUFFIX, rootElement);
    // TODO JAXRPC mapping support should be considered here ??
    this.loadOperations(doc, rootElement, null);
    doc.appendChild(rootElement);
    return doc;
}

23. AxisServiceBasedMultiLanguageEmitter#createDOMDocumentForCallbackHandler()

View license
/**
     * Generates the model for the callbacks.
     */
protected Document createDOMDocumentForCallbackHandler() {
    Document doc = getEmptyDocument();
    Element rootElement = doc.createElement("callback");
    addAttribute(doc, "package", codeGenConfiguration.getPackageName(), rootElement);
    if (codeGenConfiguration.isPackClasses() && this.axisService.getEndpoints().size() > 1) {
        addAttribute(doc, "name", makeJavaClassName(axisService.getName() + axisService.getEndpointName()) + CALL_BACK_HANDLER_SUFFIX, rootElement);
    } else {
        addAttribute(doc, "name", makeJavaClassName(axisService.getName()) + CALL_BACK_HANDLER_SUFFIX, rootElement);
    }
    // TODO JAXRPC mapping support should be considered here ??
    this.loadOperations(doc, rootElement, null);
    doc.appendChild(rootElement);
    return doc;
}

24. AxisServiceBasedMultiLanguageEmitter#createDOMDocumentForServiceXML()

View license
protected Document createDOMDocumentForServiceXML() {
    Document doc = getEmptyDocument();
    String className = null;
    String serviceName = null;
    Element rootElement = doc.createElement("interfaces");
    doc.appendChild(rootElement);
    for (Iterator iter = this.axisServices.iterator(); iter.hasNext(); ) {
        this.axisService = (AxisService) iter.next();
        this.axisBinding = axisService.getEndpoint(axisService.getEndpointName()).getBinding();
        serviceName = axisService.getName();
        if (this.codeGenConfiguration.isBackwordCompatibilityMode()) {
            className = makeJavaClassName(axisService.getBindingName());
        } else {
            className = makeJavaClassName(serviceName);
        }
        rootElement.appendChild(getServiceElement(serviceName, className, doc));
    }
    return doc;
}

25. JAXWSEmitter#createDOMDocumentForServiceXML()

Project: axis2-java
Source File: JAXWSEmitter.java
View license
protected Document createDOMDocumentForServiceXML() {
    Document doc = getEmptyDocument();
    String className = null;
    String serviceName = null;
    Element rootElement = doc.createElement("interfaces");
    doc.appendChild(rootElement);
    for (Iterator iter = this.axisServices.iterator(); iter.hasNext(); ) {
        this.axisService = (AxisService) iter.next();
        this.axisBinding = axisService.getEndpoint(axisService.getEndpointName()).getBinding();
        serviceName = axisService.getName();
        className = (String) axisService.getParameter(JAXWS_PORT_TYPE_NAME).getValue() + JAXWS_IMPL_SUFFIX;
        rootElement.appendChild(getServiceElement(serviceName, className, doc));
    }
    return doc;
}

26. SOAPEnvelopeTest#createDocument()

Project: axis2-java
Source File: SOAPEnvelopeTest.java
View license
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;
}

27. ServiceFileCreator#getServiceModel()

Project: axis2-java
Source File: ServiceFileCreator.java
View license
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;
}

28. ServiceFileCreator#getServiceModel()

Project: axis2-java
Source File: ServiceFileCreator.java
View license
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;
}

29. EventTargetAddEventListenerNSTest#runImplBasic()

View license
public boolean runImplBasic() throws Exception {
    Listener1 l1 = new Listener1();
    Listener2 l2 = new Listener2();
    Document doc = newDoc();
    Element e = doc.createElementNS(null, "test");
    AbstractNode et = (AbstractNode) e;
    doc.appendChild(e);
    et.addEventListenerNS(XML_EVENTS_NAMESPACE_URI, "DOMAttrModified", l1, false, null);
    et.addEventListenerNS(null, "DOMAttrModified", l1, false, null);
    e.setAttributeNS(null, "test", "abc");
    boolean pass = l1.getCount() == 2;
    et.addEventListenerNS(XML_EVENTS_NAMESPACE_URI, "DOMAttrModified", l2, false, "g1");
    et.addEventListenerNS(null, "DOMAttrModified", l2, false, "g1");
    e.setAttributeNS(null, "test", "def");
    pass = pass && l2.getCount() == 2;
    return pass;
}

30. OMEXMLServiceImpl#isEqual()

Project: bioformats
Source File: OMEXMLServiceImpl.java
View license
/** @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);
}

31. ConfigurationRequestConverter#toXML()

View license
/**
   * 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();
}

32. ConfigurationDOMFactoryTest#testDataTagAddNode()

View license
@Test
public void testDataTagAddNode() throws ParserConfigurationException, IllegalAccessException, InstantiationException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException, SAXException, IOException {
    DataTagAdd dataTagAdd = createDataTagAdd();
    DataTagAdd anotherDataTagAdd = createDataTagAdd();
    Document document = xmlFactory.createDocument();
    Element configurationElement = xmlFactory.createConfigurationChangeEventElement(document);
    document.appendChild(configurationElement);
    Element dataTagAddElement = xmlFactory.createDataTagAddElement(document, dataTagAdd);
    Element anotherDataTagAddElement = xmlFactory.createDataTagAddElement(document, anotherDataTagAdd);
    configurationElement.appendChild(dataTagAddElement);
    configurationElement.appendChild(anotherDataTagAddElement);
}

33. ConfigurationDOMFactoryTest#testRemoveElement()

View license
@Test
public void testRemoveElement() throws ParserConfigurationException, IllegalAccessException, InstantiationException, TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException, SAXException, IOException {
    CommandTagRemove commandTagRemove = new CommandTagRemove(25L, 23L, 234L);
    DataTagRemove dataTagRemove = new DataTagRemove(24L, 22L, 324L);
    Document document = xmlFactory.createDocument();
    Element configElement = xmlFactory.createConfigurationChangeEventElement(document);
    document.appendChild(configElement);
    Element commandTagRemoveElement = xmlFactory.createCommandTagRemoveElement(document, commandTagRemove);
    Element dataTagRemoveElement = xmlFactory.createDataTagRemoveElement(document, dataTagRemove);
    configElement.appendChild(commandTagRemoveElement);
    configElement.appendChild(dataTagRemoveElement);
}

34. BeanProxyNoBindingTest#testBeanProxyDocumentReturnDocument()

Project: camel
Source File: BeanProxyNoBindingTest.java
View license
public void testBeanProxyDocumentReturnDocument() throws Exception {
    // START SNIPPET: e3
    Endpoint endpoint = context.getEndpoint("direct:start");
    OrderService service = ProxyHelper.createProxy(endpoint, false, OrderService.class);
    Document doc = context.getTypeConverter().convertTo(Document.class, "<order type=\"book\">Camel in action</order>");
    Document reply = service.submitOrderDocumentReturnDocument(doc);
    assertNotNull(reply);
    String s = context.getTypeConverter().convertTo(String.class, reply);
    assertEquals("<order id=\"123\">OK</order>", s);
// END SNIPPET: e3
}

35. BeanProxyTest#testBeanProxyDocumentReturnDocument()

Project: camel
Source File: BeanProxyTest.java
View license
public void testBeanProxyDocumentReturnDocument() throws Exception {
    // START SNIPPET: e3
    Endpoint endpoint = context.getEndpoint("direct:start");
    OrderService service = ProxyHelper.createProxy(endpoint, OrderService.class);
    Document doc = context.getTypeConverter().convertTo(Document.class, "<order type=\"book\">Camel in action</order>");
    Document reply = service.submitOrderDocumentReturnDocument(doc);
    assertNotNull(reply);
    String s = context.getTypeConverter().convertTo(String.class, reply);
    assertEquals("<order id=\"123\">OK</order>", s);
// END SNIPPET: e3
}

36. TestHelper#testDecryption()

Project: camel
Source File: TestHelper.java
View license
protected void testDecryption(String fragment, CamelContext context) throws Exception {
    MockEndpoint resultEndpoint = context.getEndpoint("mock:decrypted", MockEndpoint.class);
    resultEndpoint.setExpectedMessageCount(1);
    // verify that the message was encrypted before checking that it is decrypted
    testEncryption(fragment, context);
    resultEndpoint.assertIsSatisfied(100);
    Exchange exchange = resultEndpoint.getExchanges().get(0);
    Document inDoc = getDocumentForInMessage(exchange);
    if (log.isDebugEnabled()) {
        logMessage(exchange, inDoc);
    }
    Assert.assertFalse("The XML message has encrypted data.", hasEncryptedData(inDoc));
    // verify that the decrypted message matches what was sent
    Document fragmentDoc = createDocumentfromInputStream(new ByteArrayInputStream(fragment.getBytes()), context);
    Diff xmlDiff = XMLUnit.compareXML(fragmentDoc, inDoc);
    Assert.assertTrue("The decrypted document does not match the control document.", xmlDiff.identical());
}

37. Launching#getLibraryInfoAsXML()

Project: che
Source File: Launching.java
View license
/**
     * Return the VM definitions contained in this object as a String of XML.  The String
     * is suitable for storing in the workbench preferences.
     * <p>
     * The resulting XML is compatible with the static method <code>parseXMLIntoContainer</code>.
     * </p>
     * @return String the results of flattening this object into XML
     * @throws CoreException if this method fails. Reasons include:<ul>
     * <li>serialization of the XML document failed</li>
     * </ul>
     */
private static String getLibraryInfoAsXML() throws CoreException {
    Document doc = newDocument();
    //$NON-NLS-1$
    Element config = doc.createElement("libraryInfos");
    doc.appendChild(config);
    // Create a node for each info in the table
    Iterator<String> locations = fgLibraryInfoMap.keySet().iterator();
    while (locations.hasNext()) {
        String home = locations.next();
        LibraryInfo info = fgLibraryInfoMap.get(home);
        Element locationElemnet = infoAsElement(doc, info);
        //$NON-NLS-1$
        locationElemnet.setAttribute("home", home);
        config.appendChild(locationElemnet);
    }
    // Serialize the Document and return the resulting String
    return serializeDocument(doc);
}

38. WebDavUtils#createResponseDoc()

Project: clerezza
Source File: WebDavUtils.java
View license
/*------------------------------------------*
     * Putting the properties in a DOM Document *
     *------------------------------------------*/
static Document createResponseDoc(Map<IRI, PropertyMap> resultMap) throws ParserConfigurationException {
    Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Set<IRI> nodeNameSet = resultMap.keySet();
    Element multistatElement = responseDoc.createElementNS(davUri, "D:" + multistat);
    // add multistat element to response
    responseDoc.appendChild(multistatElement);
    for (IRI nodeName : nodeNameSet) {
        Element responseElement = responseDoc.createElementNS(davUri, "D:" + response);
        // add response element to response Document
        multistatElement.appendChild(responseElement);
        PropertyMap propertyMap = resultMap.get(nodeName);
        addElementsToResponse(propertyMap, responseElement, responseDoc, nodeName);
    }
    return responseDoc;
}

39. DynamicSelectionListTestCase#testGenerateSaxFragment()

View license
/**
     * Test the generateSaxFragment method.
     * @throws MalformedURLException
     * @throws ParserConfigurationException
     */
public void testGenerateSaxFragment() throws Exception {
    DOMBuilder dest = new DOMBuilder();
    ResourceSource source = new ResourceSource("resource://org/apache/cocoon/forms/datatype/DynamicSelectionListTestCase.source.xml");
    Document sourceDoc = this.parser.parse(source.getInputStream());
    Element datatypeElement = (Element) sourceDoc.getElementsByTagNameNS(FormsConstants.DEFINITION_NS, "convertor").item(0);
    Datatype datatype = this.datatypeManager.createDatatype(datatypeElement, false);
    DynamicSelectionList list = new DynamicSelectionList(datatype, null, this.getManager());
    list.generateSaxFragment(dest, Locale.ENGLISH, source);
    ResourceSource expectedSource = new ResourceSource("resource://org/apache/cocoon/forms/datatype/DynamicSelectionListTestCase.dest.xml");
    Document expected = this.parser.parse(expectedSource.getInputStream());
    assertEqual("Test if output is what is expected", expected, dest.getDocument());
}

40. EnumSelectionListTestCase#testGenerateSaxFragment()

View license
/**
     * Test the generateSaxFragment method.
     * @throws MalformedURLException
     * @throws ParserConfigurationException
     */
public void testGenerateSaxFragment() throws Exception {
    DOMBuilder dest = new DOMBuilder();
    EnumSelectionList list = new EnumSelectionList(Sex.class.getName(), new EnumType(), false);
    list.generateSaxFragment(dest, Locale.ENGLISH);
    ResourceSource expectedSource = new ResourceSource("resource://org/apache/cocoon/forms/datatype/EnumSelectionListTestCase.dest-no-null.xml");
    Document expected = this.parser.parse(expectedSource.getInputStream());
    Document destDocument = dest.getDocument();
    assertEqual("Test if output is what is expected", expected, destDocument);
}

41. EnumSelectionListTestCase#testGenerateSaxFragmentNullable()

View license
/**
     * Test the generateSaxFragment method with a nullable selection list
     * @throws MalformedURLException
     * @throws ParserConfigurationException
     */
public void testGenerateSaxFragmentNullable() throws Exception {
    DOMBuilder dest = new DOMBuilder();
    EnumSelectionList list = new EnumSelectionList(Sex.class.getName(), new EnumType(), true);
    list.generateSaxFragment(dest, Locale.ENGLISH);
    ResourceSource expectedSource = new ResourceSource("resource://org/apache/cocoon/forms/datatype/EnumSelectionListTestCase.dest.xml");
    Document expected = this.parser.parse(expectedSource.getInputStream());
    Document destDocument = dest.getDocument();
    assertEqual("Test if output is what is expected", expected, destDocument);
}

42. DynamicSelectionListTestCase#testGenerateSaxFragment()

View license
/**
     * Test the generateSaxFragment method.
     * @throws MalformedURLException
     * @throws ParserConfigurationException
     */
public void testGenerateSaxFragment() throws Exception {
    DOMBuilder dest = new DOMBuilder();
    ResourceSource source = new ResourceSource("resource://org/apache/cocoon/woody/datatype/DynamicSelectionListTestCase.source.xml");
    Document sourceDoc = parser.parse(source.getInputStream());
    Element datatypeElement = (Element) sourceDoc.getElementsByTagNameNS(Constants.WD_NS, "convertor").item(0);
    Datatype datatype = datatypeManager.createDatatype(datatypeElement, false);
    DynamicSelectionList list = new DynamicSelectionList(datatype, null, this.getManager());
    list.generateSaxFragment(dest, Locale.ENGLISH, source);
    ResourceSource expectedSource = new ResourceSource("resource://org/apache/cocoon/woody/datatype/DynamicSelectionListTestCase.dest.xml");
    Document expected = parser.parse(expectedSource.getInputStream());
    assertEqual("Test if output is what is expected", expected, dest.getDocument());
}

43. CodeSwarmEventsSerializer#serialize()

View license
/**
     * actually serializes the list to the file denoted by pathToFile
     * @param pathToFile the path to the xml file to serialize to.
     *          It gets created if it doesn't exist.
     * @throws javax.xml.parsers.ParserConfigurationException
     *          When the serialization failed
     * @throws javax.xml.transform.TransformerConfigurationException
     *          When the serialization failed
     * @throws java.io.IOException
     *          When the serialization failed
     * @throws javax.xml.transform.TransformerException
     *          When the serialization failed
     */
public void serialize(String pathToFile) throws ParserConfigurationException, TransformerConfigurationException, IOException, TransformerException {
    Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element events = d.createElement("file_events");
    for (Event e : list.getEvents()) {
        Element event = d.createElement("event");
        event.setAttribute("filename", e.getFilename());
        event.setAttribute("date", String.valueOf(e.getDate()));
        event.setAttribute("author", e.getAuthor());
        events.appendChild(event);
    }
    d.appendChild(events);
    Transformer t = TransformerFactory.newInstance().newTransformer();
    File f = new File(pathToFile);
    if (!f.exists()) {
        f.createNewFile();
    }
    FileOutputStream out = new FileOutputStream(f);
    StreamResult result = new StreamResult(out);
    t.transform(new DOMSource(d), result);
    out.close();
}

44. mxDomUtils#createSvgDocument()

Project: consulo
Source File: mxDomUtils.java
View license
/**
   * Creates a new SVG document for the given width and height.
   */
public static Document createSvgDocument(int width, int height) {
    Document document = createDocument();
    Element root = document.createElement("svg");
    String w = String.valueOf(width);
    String h = String.valueOf(height);
    root.setAttribute("width", w);
    root.setAttribute("height", h);
    root.setAttribute("viewBox", "0 0 " + w + " " + h);
    root.setAttribute("version", "1.1");
    root.setAttribute("xmlns", mxConstants.NS_SVG);
    root.setAttribute("xmlns:xlink", mxConstants.NS_XLINK);
    document.appendChild(root);
    return document;
}

45. mxDomUtils#createVmlDocument()

Project: consulo
Source File: mxDomUtils.java
View license
/**
   *
   */
public static Document createVmlDocument() {
    Document document = createDocument();
    Element root = document.createElement("html");
    root.setAttribute("xmlns:v", "urn:schemas-microsoft-com:vml");
    root.setAttribute("xmlns:o", "urn:schemas-microsoft-com:office:office");
    document.appendChild(root);
    Element head = document.createElement("head");
    Element style = document.createElement("style");
    style.setAttribute("type", "text/css");
    style.appendChild(document.createTextNode("<!-- v\\:* {behavior: url(#default#VML);} -->"));
    head.appendChild(style);
    root.appendChild(head);
    Element body = document.createElement("body");
    root.appendChild(body);
    return document;
}

46. mxDomUtils#createHtmlDocument()

Project: consulo
Source File: mxDomUtils.java
View license
/**
   * Returns a document with a HTML node containing a HEAD and BODY node.
   */
public static Document createHtmlDocument() {
    Document document = createDocument();
    Element root = document.createElement("html");
    document.appendChild(root);
    Element head = document.createElement("head");
    root.appendChild(head);
    Element body = document.createElement("body");
    root.appendChild(body);
    return document;
}

47. XmlUtilTest#testCreateElement()

Project: controller
Source File: XmlUtilTest.java
View license
@Test
public void testCreateElement() throws Exception {
    final Document document = XmlUtil.newDocument();
    final Element top = XmlUtil.createElement(document, "top", Optional.of("namespace"));
    top.appendChild(XmlUtil.createTextElement(document, "innerText", "value", Optional.of("namespace")));
    top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref", "prefixNamespace", "value", Optional.of("namespace")));
    top.appendChild(XmlUtil.createTextElementWithNamespacedContent(document, "innerPrefixedText", "pref", "prefixNamespace", "value", Optional.of("randomNamespace")));
    document.appendChild(top);
    assertEquals("top", XmlUtil.createDocumentCopy(document).getDocumentElement().getTagName());
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreWhitespace(true);
    final Diff diff = XMLUnit.compareXML(XMLUnit.buildControlDocument(xml), document);
    assertTrue(diff.toString(), diff.similar());
}

48. SUTimeMain#annotationToXmlDocument()

Project: CoreNLP
Source File: SUTimeMain.java
View license
public static Document annotationToXmlDocument(Annotation annotation) {
    Element dateElem = XMLUtils.createElement("DATE");
    dateElem.setTextContent(annotation.get(CoreAnnotations.DocDateAnnotation.class));
    Element textElem = annotationToTmlTextElement(annotation);
    Element docElem = XMLUtils.createElement("DOC");
    docElem.appendChild(dateElem);
    docElem.appendChild(textElem);
    // Create document and import elements into this document....
    Document doc = XMLUtils.createDocument();
    doc.appendChild(doc.importNode(docElem, true));
    return doc;
}

49. DOMComparerTest#compareNoDifference()

Project: crawljax
Source File: DOMComparerTest.java
View license
@Test
public void compareNoDifference() throws IOException {
    String html = "<html><body><p>No difference</p></body></html>";
    Document control = DomUtils.asDocument(html);
    assertNotNull(control);
    Document test = DomUtils.asDocument(html);
    assertNotNull(test);
    DOMComparer dc = new DOMComparer(control, test);
    List<Difference> differences = dc.compare();
    assertThat(differences, is(IsEmptyCollection.empty()));
}

50. DOMComparerTest#comparePartialDifference()

Project: crawljax
Source File: DOMComparerTest.java
View license
@Test
public void comparePartialDifference() throws IOException {
    String controlHTML = "<html><body><header>Crawljax</header><p>There are differences</p></body></html>";
    String testHTML = "<html><head><title>Crawljax</title></head><body><p>There are differences.</body></html>";
    final int EXPECTED_DIFF = 7;
    Document control = DomUtils.asDocument(controlHTML);
    assertNotNull(control);
    Document test = DomUtils.asDocument(testHTML);
    assertNotNull(test);
    DOMComparer dc = new DOMComparer(control, test);
    List<Difference> differences = dc.compare();
    assertEquals("Error: Did not find 5 differences", differences.size(), EXPECTED_DIFF);
}

51. NewOptimizerOverridesTest#getLastQueryPlan()

View license
/** Get an xml-based picture of the plan chosen for the last query. The query is identified by its JDBC ResultSet */
public static Document getLastQueryPlan(Connection conn, ResultSet rs) throws Exception {
    LanguageConnectionContext lcc = ConstraintCharacteristicsTest.getLCC(conn);
    org.apache.derby.iapi.sql.ResultSet derbyRS = lcc.getLastActivation().getResultSet();
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = doc.createElement("planTrace");
    doc.appendChild(root);
    derbyRS.toXML(root, "top");
    return doc;
}

52. Utils#parseXMLDocument()

Project: Doradus
Source File: Utils.java
View license
// parseURI
/**
     * Parse the given XML document, creating a DOM tree whose root Document object is
     * returned. An IllegalArgumentException is thrown if the XML is malformed.
     *
     * @param   xmlDoc      XML document as a String.
     * @return              Root document element of the parsed DOM tree.
     * @throws IllegalArgumentException  If the XML is malformed.
     */
public static Element parseXMLDocument(String xmlDoc) throws IllegalArgumentException {
    // Parse the given XML document returning its root document Element if it parses.
    // Wrap the document payload as an InputSource.
    Reader stringReader = new StringReader(xmlDoc);
    InputSource inputSource = new InputSource(stringReader);
    // Parse the document into a DOM tree.
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = null;
    Document doc = null;
    try {
        parser = dbf.newDocumentBuilder();
        doc = parser.parse(inputSource);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Error parsing XML document: " + ex.getMessage());
    }
    return doc.getDocumentElement();
}

53. Utils#parseXMLDocument()

Project: Doradus
Source File: Utils.java
View license
// parseXMLDocument
/**
     * Parse an XML document from the given Reader, creating a DOM tree whose root
     * Document object is returned. An IllegalArgumentException is thrown if the XML is
     * malformed.
     *
     * @param  reader       Reader from which XML text is read.
     * @return              Root document element of the parsed DOM tree.
     * @throws IllegalArgumentException  If the XML is malformed.
     */
public static Element parseXMLDocument(Reader reader) throws IllegalArgumentException {
    // Wrap the document payload as an InputSource.
    InputSource inputSource = new InputSource(reader);
    // Parse the document into a DOM tree.
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = null;
    Document doc = null;
    try {
        parser = dbf.newDocumentBuilder();
        doc = parser.parse(inputSource);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Error parsing XML document: " + ex.getMessage());
    }
    return doc.getDocumentElement();
}

54. StsTestUtil#canocalizeXml()

View license
public static String canocalizeXml(String originalServerXml) throws Exception {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setExpandEntityReferences(false);
    DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(originalServerXml)));
    document.normalize();
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    StringWriter writer = new StringWriter();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(new DOMSource(document.getDocumentElement()), new StreamResult(writer));
    return writer.toString().replace("\\s+\\n", "\\n");
}

55. AttributesTest#testAddXml()

Project: empire-db
Source File: AttributesTest.java
View license
/**
	 * Test method for {@link org.apache.empire.commons.Attributes#addXml(org.w3c.dom.Element, long)}.
	 * @throws ParserConfigurationException 
	 */
@Test
public void testAddXml() throws ParserConfigurationException {
    Attributes attributes = new Attributes();
    attributes.set("test", "testvalue");
    attributes.set("test2", "testvalue2");
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.newDocument();
    Element root = doc.createElement("root");
    doc.appendChild(root);
    // value should be ignored
    Random random = new Random();
    attributes.addXml(root, random.nextInt());
    root.getAttribute("test").equals("testvalue");
    root.getAttribute("test2").equals("testvalue2");
}

56. XUpdateTest#xupdate()

Project: exist
Source File: XUpdateTest.java
View license
@Test
public void xupdate() throws Exception {
    //skip tests from Geoff Shuetrim (see above!)
    Assume.assumeThat(testName, not(anyOf(equalTo("rename_root_element"), equalTo("rename_including_namespace"))));
    addDocument(sourceFile);
    //update input xml file
    Document xupdateResult = updateDocument(MODIFICATION_DIR + "/" + testName + ".xml");
    removeWhiteSpace(xupdateResult);
    //Read reference xml file
    DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
    parserFactory.setNamespaceAware(true);
    DocumentBuilder builder = parserFactory.newDocumentBuilder();
    Document referenceXML = builder.parse(RESTULT_DIR + "/" + testName + ".xml");
    removeWhiteSpace(referenceXML);
    //compare
    new CompareDocuments().compare(referenceXML, xupdateResult, "", false);
    removeDocument();
}

57. PageXmlizer#xmlize()

Project: fitnesse
Source File: PageXmlizer.java
View license
public Document xmlize(PageData data) {
    Document document = XmlUtil.newDocument();
    Element dataElement = document.createElement("data");
    XmlUtil.addCdataNode(dataElement, "content", data.getContent());
    Element propertiesElement = data.getProperties().makeRootElement(document);
    dataElement.appendChild(propertiesElement);
    document.appendChild(dataElement);
    return document;
}

58. XmlUtilTest#testAddCdataElement()

Project: fitnesse
Source File: XmlUtilTest.java
View license
@Test
public void testAddCdataElement() throws Exception {
    Document doc = XmlUtil.newDocument();
    Element root = doc.createElement("root");
    doc.appendChild(root);
    XmlUtil.addCdataNode(root, "mydata", "<>&#;");
    Element myDataElement = XmlUtil.getElementByTagName(root, "mydata");
    assertNotNull(myDataElement);
    Node childNode = myDataElement.getChildNodes().item(0);
    assertTrue(childNode instanceof CDATASection);
    CDATASection cData = (CDATASection) childNode;
    assertEquals("<>&#;", cData.getNodeValue());
}

59. Echo#getDocument()

Project: flex-blazeds
Source File: Echo.java
View license
/**
     *
     * @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;
}

60. Main#createSVGDocument()

Project: fop
Source File: Main.java
View license
/**
     * Helper method to create the SVG document from the plan InputStream.
     * @param is InputStream
     * @return Document a DOM containing the SVG
     */
public Document createSVGDocument(InputStream is) {
    Document doc = null;
    Element root = null;
    try {
        doc = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
        root = doc.getDocumentElement();
    } catch (Exception e) {
        e.printStackTrace();
    }
    PlanRenderer gr = new PlanRenderer();
    gr.setFontInfo("sansserif", 12);
    Document svgdoc = gr.createSVGDocument(doc);
    return svgdoc;
}

61. NokogiriDomParser#parse()

Project: gocd
Source File: NokogiriDomParser.java
View license
@Override
public void parse(InputSource source) throws SAXException, IOException {
    dtd.reset();
    if (xInclude) {
        setEntityResolver(new NokogiriXInlcudeEntityResolver(source));
    }
    super.parse(source);
    Document doc = getDocument();
    if (doc == null)
        throw new RuntimeException("null document");
    doc.setUserData(XmlDocument.DTD_RAW_DOCUMENT, dtd.getDocument(), null);
}

62. EmptyPoolsConfigDocumentGenerator#generatePoolsDocument()

View license
@Override
public Document generatePoolsDocument() {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    Document document;
    try {
        document = documentBuilderFactory.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("generatePoolConfig: Failed to create a new document");
    }
    Element root = document.createElement(ConfigManager.CONFIGURATION_TAG_NAME);
    document.appendChild(root);
    root.setAttribute("version", Integer.toString(documentVersion));
    LOG.info("generatePoolsDocument: Creating version " + documentVersion);
    ++documentVersion;
    return document;
}

63. ChukwaMetricsList#toXml()

Project: HiTune
Source File: ChukwaMetricsList.java
View license
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();
}

64. XmlUtil#createXml()

Project: hutool
Source File: XmlUtil.java
View license
// -------------------------------------------------------------------------------------- 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;
}

65. mxDomUtils#createSvgDocument()

Project: jgraphx
Source File: mxDomUtils.java
View license
/**
	 * Creates a new SVG document for the given width and height.
	 */
public static Document createSvgDocument(int width, int height) {
    Document document = createDocument();
    Element root = document.createElement("svg");
    String w = String.valueOf(width);
    String h = String.valueOf(height);
    root.setAttribute("width", w);
    root.setAttribute("height", h);
    root.setAttribute("viewBox", "0 0 " + w + " " + h);
    root.setAttribute("version", "1.1");
    root.setAttribute("xmlns", mxConstants.NS_SVG);
    root.setAttribute("xmlns:xlink", mxConstants.NS_XLINK);
    document.appendChild(root);
    return document;
}

66. mxDomUtils#createVmlDocument()

Project: jgraphx
Source File: mxDomUtils.java
View license
/**
	 * 
	 */
public static Document createVmlDocument() {
    Document document = createDocument();
    Element root = document.createElement("html");
    root.setAttribute("xmlns:v", "urn:schemas-microsoft-com:vml");
    root.setAttribute("xmlns:o", "urn:schemas-microsoft-com:office:office");
    document.appendChild(root);
    Element head = document.createElement("head");
    Element style = document.createElement("style");
    style.setAttribute("type", "text/css");
    style.appendChild(document.createTextNode("<!-- v\\:* {behavior: url(#default#VML);} -->"));
    head.appendChild(style);
    root.appendChild(head);
    Element body = document.createElement("body");
    root.appendChild(body);
    return document;
}

67. mxDomUtils#createHtmlDocument()

Project: jgraphx
Source File: mxDomUtils.java
View license
/**
	 * Returns a document with a HTML node containing a HEAD and BODY node.
	 */
public static Document createHtmlDocument() {
    Document document = createDocument();
    Element root = document.createElement("html");
    document.appendChild(root);
    Element head = document.createElement("head");
    root.appendChild(head);
    Element body = document.createElement("body");
    root.appendChild(body);
    return document;
}

68. TckValidator#checkKeyInfo()

Project: juddi
Source File: TckValidator.java
View license
public static void checkKeyInfo(KeyInfoType kit1, KeyInfoType kit2) {
    if (kit1 == null || kit2 == null) {
        assertEquals(kit1, kit2);
        return;
    }
    assertEquals(kit1.getId(), kit2.getId());
    DOMResult domResult1 = new DOMResult();
    DOMResult domResult2 = new DOMResult();
    JAXB.marshal(kit1, domResult1);
    JAXB.marshal(kit2, domResult2);
    Document doc1 = (Document) domResult1.getNode();
    DOMSource domSource1 = new DOMSource(doc1.getDocumentElement());
    Document doc2 = (Document) domResult2.getNode();
    DOMSource domSource2 = new DOMSource(doc2.getDocumentElement());
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);
    Diff diff = new Diff(domSource1, domSource2);
    assertTrue("Key info elements should match", diff.similar());
}

69. XPointerFactory#employees()

Project: lenya
Source File: XPointerFactory.java
View license
/**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
public Document employees() {
    DOMParserFactory dpf = new DOMParserFactory();
    Document doc = dpf.getDocument();
    Element michi = dpf.newElementNode(doc, "Employee");
    michi.setAttribute("Id", "0");
    michi.appendChild(dpf.newTextNode(doc, "Michi"));
    Element levi = dpf.newElementNode(doc, "Employee");
    levi.setAttribute("Id", "1");
    levi.appendChild(dpf.newTextNode(doc, "Levi"));
    Element employees = dpf.newElementNode(doc, "Employees");
    employees.appendChild(dpf.newTextNode(doc, "\n"));
    employees.appendChild(michi);
    employees.appendChild(dpf.newTextNode(doc, "\n"));
    employees.appendChild(levi);
    employees.appendChild(dpf.newTextNode(doc, "\n"));
    doc.appendChild(employees);
    return doc;
}

70. XPSAssembler#assemble()

Project: lenya
Source File: XPSAssembler.java
View license
/**
     * DOCUMENT ME!
     *
     * @param document DOCUMENT ME!
     * @param reference DOCUMENT ME!
     * @param cocoon DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
public Document assemble(Document document, String reference, String cocoon) {
    //return document;
    Element root = document.getDocumentElement();
    Document assembledDocument = dpf.getDocument();
    Element assembledRoot = (Element) dpf.cloneNode(assembledDocument, root, false);
    assembledDocument.appendChild(assembledRoot);
    File workingDirectory = new File(System.getProperty("user.dir"));
    XPSSourceInformation sourceInfo = new XPSSourceInformation("file:" + workingDirectory + "/dummy.xml", cocoon);
    XPSSourceInformation currentInfo = new XPSSourceInformation(reference, sourceInfo, cocoon);
    NodeList nl = root.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        traverse(assembledRoot, nl.item(i), sourceInfo, currentInfo);
    }
    return assembledDocument;
}

71. XmlWorkbookGeneratorStrategy#createDocument()

View license
/**
     * SpreadsheetML?????????????????.
     * @return DOM Document??????
     * @throws ParserConfigurationException ?????
     */
private Document createDocument() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    Document doc = factory.newDocumentBuilder().newDocument();
    Map<String, String> param = new HashMap<String, String>();
    param.put("progid", "Excel.Sheet");
    ProcessingInstruction pi = doc.createProcessingInstruction("mso-application", "progid=\"Excel.Sheet\"");
    doc.appendChild(pi);
    return doc;
}

72. WSDL11Endpoint#fromMap()

Project: ode
Source File: WSDL11Endpoint.java
View license
public void fromMap(Map eprMap) {
    Document doc = DOMUtils.newDocument();
    Element serviceRef = doc.createElementNS(SERVICE_REF_QNAME.getNamespaceURI(), SERVICE_REF_QNAME.getLocalPart());
    doc.appendChild(serviceRef);
    _serviceElmt = doc.createElementNS(Namespaces.WSDL_11, "service");
    serviceRef.appendChild(_serviceElmt);
    if (eprMap.get(SERVICE_QNAME) != null) {
        QName serviceQName = ((QName) eprMap.get(SERVICE_QNAME));
        _serviceElmt.setAttribute("name", serviceQName.getLocalPart());
        _serviceElmt.setAttribute("targetNamespace", serviceQName.getNamespaceURI());
    }
    Element port = doc.createElementNS(Namespaces.WSDL_11, "port");
    if (eprMap.get(PORT_NAME) != null) {
        port.setAttribute("name", (String) eprMap.get(PORT_NAME));
    }
    port.setAttribute("binding", "");
    Element address = doc.createElementNS(Namespaces.SOAP_NS, "address");
    if (eprMap.get(ADDRESS) != null)
        address.setAttribute("location", (String) eprMap.get(ADDRESS));
    _serviceElmt.appendChild(port);
    port.appendChild(address);
}

73. DbExternalVariable#renderXmlRow()

Project: ode
Source File: DbExternalVariable.java
View license
<T extends RowSubset> Element renderXmlRow(Locator locator, QName varType, T value) throws ExternalVariableModuleException {
    Document doc = DOMUtils.newDocument();
    Element el = doc.createElementNS(varType.getNamespaceURI(), varType.getLocalPart());
    doc.appendChild(el);
    if (value != null) {
        for (Column c : value._columns) {
            Object data = value.get(c.idx);
            addElement(el, varType, c, data);
        }
    } else {
        // initialize variable with default/generated values
        RowKey keys = keyFromLocator(locator);
        for (Column c : _columns) {
            Object data = c.getValue(c.name, keys, new RowVal(), locator.iid);
            addElement(el, varType, c, data);
        }
    }
    return el;
}

74. XmlDataDaoImpl#set()

Project: ode
Source File: XmlDataDaoImpl.java
View license
/**
     * @see XmlDataDAO#set(org.w3c.dom.Node)
     */
public void set(Node val) {
    if (val == null || !(val instanceof Element)) {
        _data = val;
        return;
    }
    // For some reason we're getting some weird DOM trees from ServiceMix. Until we
    // spot where it exactly comes from, this fixes it.
    // The weirdness lies in elements being in xmlns="" when printed with a DOMWriter
    // but having a ns when the elements are queried directly.
    Document doc = DOMUtils.newDocument();
    _data = doc.importNode(val, true);
    doc.appendChild(_data);
}

75. BindingContextImpl#activateMyRoleEndpoint()

Project: ode
Source File: BindingContextImpl.java
View license
public EndpointReference activateMyRoleEndpoint(QName processId, Endpoint myRoleEndpoint) {
    final Document doc = DOMUtils.newDocument();
    Element serviceref = doc.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(), EndpointReference.SERVICE_REF_QNAME.getLocalPart());
    serviceref.setNodeValue(myRoleEndpoint.serviceName + ":" + myRoleEndpoint.portName);
    doc.appendChild(serviceref);
    return new EndpointReference() {

        public Document toXML() {
            return doc;
        }
    };
}

76. JbiEndpointReference#toXML()

Project: ode
Source File: JbiEndpointReference.java
View license
public Document toXML() {
    Document doc = DOMUtils.newDocument();
    Element root = doc.createElementNS(SERVICE_REF_QNAME.getNamespaceURI(), SERVICE_REF_QNAME.getLocalPart());
    try {
        DocumentFragment fragment = getServiceEndpoint().getAsReference(_type);
        if (fragment != null) {
            root.appendChild(doc.importNode(fragment, true));
        }
    } catch (Throwable t) {
    }
    doc.appendChild(root);
    return doc;
}

77. MyEndpointReference#toXML()

Project: ode
Source File: MyEndpointReference.java
View license
public Document toXML() {
    Document xml = DOMUtils.newDocument();
    // Prefer to use the external endpoint as our EPR,
    // but if we dont find one, use the internal endpoint.
    ServiceEndpoint se = _service.getExternalServiceEndpoint();
    if (se == null)
        se = _service.getInternalServiceEndpoint();
    Element root = xml.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(), EndpointReference.SERVICE_REF_QNAME.getLocalPart());
    xml.appendChild(root);
    // TODO: handle the operation name problem.
    DocumentFragment fragment = se.getAsReference(null);
    root.appendChild(xml.importNode(fragment, true));
    return xml;
}

78. XMLRPC#createMethodCall()

Project: oodt
Source File: XMLRPC.java
View license
/** Build an XML-RPC method call.
	 *
	 * This may throw {@link IllegalArgumentException} if the <var>params</var>
	 * contains an object that's incompatible with XML-RPC.
	 *
	 * @param name Name of the method to call.
	 * @param params Parameters to pass to the call.
	 * @return An XML string encapsulationg the call.
	 * @throws DOMException If we can't construct the call.
	 */
public static byte[] createMethodCall(String name, Collection params) throws DOMException {
    Document doc = XML.createDocument();
    Element methodCallElement = doc.createElement("methodCall");
    doc.appendChild(methodCallElement);
    XML.add(methodCallElement, "methodName", name);
    if (params != null && !params.isEmpty()) {
        Element paramsElement = doc.createElement("params");
        methodCallElement.appendChild(paramsElement);
        for (Object param : params) {
            paramsElement.appendChild(createValueElement(doc, param));
        }
    }
    return XML.serialize(doc).getBytes();
}

79. NodeTest#testImportNode()

Project: openjdk
Source File: NodeTest.java
View license
/*
     * Test importing node from one document to another.
     */
@Test
public void testImportNode() throws Exception {
    Document document = createDOMWithNS("Node02.xml");
    Document otherDocument = createDOMWithNS("ElementSample01.xml");
    NodeList otherNodeList = otherDocument.getElementsByTagName("body");
    Node importedNode = otherNodeList.item(0);
    Node clone = importedNode.cloneNode(true);
    Node retNode = document.importNode(importedNode, true);
    //verify importedNode is not changed
    assertTrue(clone.isEqualNode(importedNode));
    assertNotEquals(retNode, importedNode);
    assertTrue(importedNode.isEqualNode(retNode));
    retNode = document.importNode(importedNode, false);
    //verify importedNode is not changed
    assertTrue(clone.isEqualNode(importedNode));
    assertEquals(retNode.getNodeName(), importedNode.getNodeName());
    assertFalse(importedNode.isEqualNode(retNode));
}

80. TypeInfoTest#getRoot()

Project: openjdk
Source File: TypeInfoTest.java
View license
private Element getRoot(String schemaText, String docText) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    InputSource inSchema = new InputSource(new StringReader(schemaText));
    inSchema.setSystemId("schema.xsd");
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    dbf.setAttribute(SCHEMA_SOURCE, inSchema);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    InputSource inSource = new InputSource(new StringReader(docText));
    inSource.setSystemId("doc.xml");
    Document document = parser.parse(inSource);
    return document.getDocumentElement();
}

81. AuctionController#testCreateNewItem2SellRetry()

Project: openjdk
Source File: AuctionController.java
View license
/**
     * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
     * test throws DOM Level 1 node error.
     *
     * @throws Exception If any errors occur.
     */
@Test(groups = { "readLocalFiles" })
public void testCreateNewItem2SellRetry() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document document = dbf.newDocumentBuilder().parse(xmlFile);
    DOMConfiguration domConfig = document.getDomConfig();
    MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
    domConfig.setParameter("error-handler", errHandler);
    DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    MyDOMOutput domoutput = new MyDOMOutput();
    domoutput.setByteStream(System.out);
    writer.write(document, domoutput);
    document.normalizeDocument();
    writer.write(document, domoutput);
    assertFalse(errHandler.isError());
}

82. Bug6531160#testDOMLevel1Validation()

Project: openjdk
Source File: Bug6531160.java
View license
@Test
public void testDOMLevel1Validation() throws Exception {
    SchemaFactory fact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = fact.newSchema(new StreamSource(new StringReader(XSD)));
    DocumentBuilderFactory docfact = DocumentBuilderFactory.newInstance();
    docfact.setNamespaceAware(true);
    Document doc = docfact.newDocumentBuilder().newDocument();
    doc.appendChild(doc.createElement("root"));
    try {
        schema.newValidator().validate(new DOMSource(doc));
    } catch (SAXParseException e) {
        Assert.fail("Validation failed: " + e.getMessage());
    }
}

83. WebModuleUtilTest#buildModuleConfig()

Project: openmrs-core
Source File: WebModuleUtilTest.java
View license
private Document buildModuleConfig() throws ParserConfigurationException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("module");
    doc.appendChild(rootElement);
    Element dwr = doc.createElement("dwr");
    dwr.appendChild(doc.createTextNode(""));
    rootElement.appendChild(dwr);
    Element allow = doc.createElement("allow");
    allow.appendChild(doc.createTextNode(""));
    dwr.appendChild(allow);
    Attr attr = doc.createAttribute("moduleId");
    attr.setValue("mymodule");
    allow.setAttributeNode(attr);
    Element create = doc.createElement("create");
    allow.appendChild(create);
    return doc;
}

84. RestContentProvider#createErrorDocument()

Project: sakai
Source File: RestContentProvider.java
View license
/**
   * Given any error condition, create an error document including css
   * @return Document
   */
public static Document createErrorDocument() {
    Document errorDocument = createDocument();
    Element html = errorDocument.createElement("html");
    Element head = errorDocument.createElement("head");
    Element body = errorDocument.createElement("body");
    Element p = errorDocument.createElement("p");
    Text textNode = errorDocument.createTextNode("An error retrieving document from knowledge base has occurred.");
    p.appendChild(textNode);
    body.appendChild(p);
    html.appendChild(head);
    html.appendChild(body);
    errorDocument.appendChild(html);
    return errorDocument;
}

85. AuthoringHelper#getItemBank()

Project: sakai
Source File: AuthoringHelper.java
View license
/**
   * Get an object bank of items in Document form.
   *
   * @param itemIds array of the the item ids
   * @return the Document with the item bank data
   */
public Document getItemBank(String[] itemIds) {
    Document objectBank = XmlUtil.createDocument();
    Element root = objectBank.createElement("questestinterop");
    Element ob = objectBank.createElement("objectbank");
    String objectBankIdent = "object" + Math.random();
    ob.setAttribute("ident", objectBankIdent);
    for (int i = 0; i < itemIds.length; i++) {
        Document itemDoc = getItem(itemIds[i]);
        Element itemElement = itemDoc.getDocumentElement();
        Node itemImport = objectBank.importNode(itemElement, true);
        ob.appendChild(itemImport);
    }
    root.appendChild(ob);
    objectBank.appendChild(root);
    return objectBank;
}

86. AuthoringHelper#getAssessmentBank()

Project: sakai
Source File: AuthoringHelper.java
View license
/**
   * Get an object bank of assessments (asi) in Document form.
   *
   * @param assessmentIds array of the the assessment ids
   * @return the Document with the item bank data
   */
public Document getAssessmentBank(String[] assessmentIds) {
    Document objectBank = XmlUtil.createDocument();
    Element root = objectBank.createElement("questestinterop");
    Element ob = objectBank.createElement("objectbank");
    String objectBankIdent = "object" + Math.random();
    ob.setAttribute("ident", objectBankIdent);
    for (int i = 0; i < assessmentIds.length; i++) {
        Document itemDoc = getAssessment(assessmentIds[i]);
        Element itemElement = itemDoc.getDocumentElement();
        Node itemImport = objectBank.importNode(itemElement, true);
        ob.appendChild(itemImport);
    }
    root.appendChild(ob);
    objectBank.appendChild(root);
    return objectBank;
}

87. SakaiConfiguration#getXML()

Project: sakai
Source File: SakaiConfiguration.java
View license
private String getXML(String rootNodeName, Map<String, String> propertyMap) {
    Document doc = Xml.createDocument();
    Node results = doc.createElement(rootNodeName);
    doc.appendChild(results);
    for (String key : propertyMap.keySet()) {
        Node itemChild = doc.createElement(key);
        itemChild.appendChild(doc.createTextNode(propertyMap.get(key)));
        results.appendChild(itemChild);
    }
    return Xml.writeDocumentToString(doc);
}

88. SakaiScript#getSiteListXml()

Project: sakai
Source File: SakaiScript.java
View license
/**
     * Renders a list of sites as XML to ensure consistency amongst webservice requests
     * 
     * @param sites List of sites
     * @return XML string
     */
private String getSiteListXml(List<Site> sites) {
    Document dom = Xml.createDocument();
    Node list = dom.createElement("list");
    dom.appendChild(list);
    for (Site site : sites) {
        Node item = dom.createElement("item");
        Node siteId = dom.createElement("siteId");
        siteId.appendChild(dom.createTextNode(site.getId()));
        Node siteTitle = dom.createElement("siteTitle");
        siteTitle.appendChild(dom.createTextNode(site.getTitle()));
        item.appendChild(siteId);
        item.appendChild(siteTitle);
        list.appendChild(item);
    }
    return Xml.writeDocumentToString(dom);
}

89. AttrCompareTest#createDoc()

Project: santuario-java
Source File: AttrCompareTest.java
View license
/**
     * Method createDoc
     *
     * @param documentElement
     * @return
     * @throws ParserConfigurationException
     */
private static Document createDoc(String documentElement) throws ParserConfigurationException {
    DocumentBuilder documentBuilder = XMLUtils.createDocumentBuilder(false);
    Document doc = documentBuilder.newDocument();
    Element root = doc.createElementNS(null, documentElement);
    doc.appendChild(root);
    return doc;
}

90. Canonicalizer20010315ExclusiveTest#test24Aexcl()

View license
/**
     * Method test24Aexcl - a testcase for SANTUARIO-263
     * "Canonicalizer can't handle dynamical created DOM correctly"
     * https://issues.apache.org/jira/browse/SANTUARIO-263
     */
@org.junit.Test
public void test24Aexcl() throws Exception {
    Document doc = XMLUtils.createDocumentBuilder(false).newDocument();
    Element local = doc.createElementNS("foo:bar", "dsig:local");
    Element test = doc.createElementNS("http://example.net", "etsi:test");
    Element elem2 = doc.createElementNS("http://example.net", "etsi:elem2");
    Element stuff = doc.createElementNS("foo:bar", "dsig:stuff");
    elem2.appendChild(stuff);
    test.appendChild(elem2);
    local.appendChild(test);
    doc.appendChild(local);
    Node root = doc.getElementsByTagNameNS("http://example.net", "elem2").item(0);
    Canonicalizer20010315Excl c = new Canonicalizer20010315ExclWithComments();
    byte[] reference = JavaUtils.getBytesFromFile(getAbsolutePath("src/test/resources/org/apache/xml/security/c14n/inExcl/example2_4_c14nized.xml"));
    byte[] result = c.engineCanonicalizeSubTree(root);
    boolean equals = java.security.MessageDigest.isEqual(reference, result);
    assertTrue(equals);
}

91. XMLCipherTest#testEecryptToByteArray()

Project: santuario-java
Source File: XMLCipherTest.java
View license
@org.junit.Test
public void testEecryptToByteArray() throws Exception {
    if (!bcInstalled) {
        return;
    }
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);
    Key key = keygen.generateKey();
    Document document = document();
    XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_128_GCM);
    cipher.init(XMLCipher.ENCRYPT_MODE, key);
    cipher.getEncryptedData();
    Document encrypted = cipher.doFinal(document, document);
    XMLCipher xmlCipher = XMLCipher.getInstance();
    xmlCipher.init(XMLCipher.DECRYPT_MODE, key);
    Element encryptedData = (Element) encrypted.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA).item(0);
    xmlCipher.decryptToByteArray(encryptedData);
}

92. TransformBase64DecodeTest#test1()

View license
@org.junit.Test
public void test1() throws Exception {
    // base64 encoded
    String s1 = "VGhlIFVSSSBvZiB0aGUgdHJhbnNmb3JtIGlzIGh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1s\n" + "ZHNpZyNiYXNlNjQ=";
    Document doc = TransformBase64DecodeTest.createDocument();
    Transforms t = new Transforms(doc);
    doc.appendChild(t.getElement());
    t.addTransform(TransformBase64Decode.implementedTransformURI);
    XMLSignatureInput in = new XMLSignatureInput(new ByteArrayInputStream(s1.getBytes()));
    XMLSignatureInput out = t.performTransforms(in);
    String result = new String(out.getBytes());
    assertTrue(result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64"));
}

93. TransformBase64DecodeTest#test2()

View license
@org.junit.Test
public void test2() throws Exception {
    // base64 encoded twice
    String s2 = "VkdobElGVlNTU0J2WmlCMGFHVWdkSEpoYm5ObWIzSnRJR2x6SUdoMGRIQTZMeTkzZDNjdWR6TXVi\n" + "M0puTHpJd01EQXZNRGt2ZUcxcwpaSE5wWnlOaVlYTmxOalE9";
    Document doc = TransformBase64DecodeTest.createDocument();
    Transforms t = new Transforms(doc);
    doc.appendChild(t.getElement());
    t.addTransform(TransformBase64Decode.implementedTransformURI);
    XMLSignatureInput in = new XMLSignatureInput(new ByteArrayInputStream(s2.getBytes()));
    XMLSignatureInput out = t.performTransforms(t.performTransforms(in));
    String result = new String(out.getBytes());
    assertTrue(result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64"));
}

94. ViewHierarchy#deflateToDocument()

View license
private Document deflateToDocument(View view) {
    Document doc;
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    doc.appendChild(deflateRelative(view, new Point(-view.getLeft(), -view.getTop()), doc));
    return doc;
}

95. JsonXmlUtil#buildXmlDocument()

Project: selendroid
Source File: JsonXmlUtil.java
View license
public static Document buildXmlDocument(JSONObject tree) {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        SelendroidLogger.error("Failed to create documentBuilder", e);
        throw new RuntimeException(e);
    }
    Document document = builder.newDocument();
    // document.setXMLEncoding("UTF-8");
    Element root = document.createElement("views");
    document.appendChild(root);
    buildXmlNode(tree, root, document);
    return document;
}

96. W3CDOMStreamReaderTest#testSingleElement()

View license
public void testSingleElement() throws Exception {
    Document doc = getDocument();
    Element e = doc.createElementNS("urn:test", "root");
    e.setAttribute("xmlns", "urn:test");
    doc.appendChild(e);
    assertEquals(1, e.getAttributes().getLength());
    LOG.info("start: " + XMLStreamReader.START_ELEMENT);
    LOG.info("attr: " + XMLStreamReader.ATTRIBUTE);
    LOG.info("ns: " + XMLStreamReader.NAMESPACE);
    LOG.info("chars: " + XMLStreamReader.CHARACTERS);
    LOG.info("end: " + XMLStreamReader.END_ELEMENT);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writeXml(doc, baos);
    LOG.info(baos.toString());
    W3CDOMStreamReader reader = new W3CDOMStreamReader(doc.getDocumentElement());
    testSingleElement(reader);
}

97. W3CDOMStreamReaderTest#testTextChild()

View license
public void testTextChild() throws Exception {
    Document doc = getDocument();
    Element e = doc.createElementNS("urn:test", "root");
    e.setAttribute("xmlns", "urn:test");
    doc.appendChild(e);
    Node text = doc.createTextNode("Hello World");
    e.appendChild(text);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writeXml(doc, baos);
    LOG.info(baos.toString());
    W3CDOMStreamReader reader = new W3CDOMStreamReader(e);
    testTextChild(reader);
}

98. W3CDOMStreamReaderTest#testMixedContent()

View license
public void testMixedContent() throws Exception {
    Document doc = getDocument();
    Element e = doc.createElementNS("urn:test", "test:root");
    e.setAttribute("xmlns", "urn:test");
    doc.appendChild(e);
    Node text = doc.createTextNode("Hello World");
    e.appendChild(text);
    Element child = doc.createElement("element");
    e.appendChild(child);
    text = doc.createTextNode(" more text");
    e.appendChild(text);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writeXml(doc, baos);
    LOG.info(baos.toString());
    W3CDOMStreamReader reader = new W3CDOMStreamReader(e);
    testMixedContent(reader);
}

99. W3CDOMStreamReaderTest#testAttributes()

View license
public void testAttributes() throws Exception {
    Document doc = getDocument();
    Element e = doc.createElementNS("urn:test", "root");
    e.setAttribute("xmlns", "urn:test");
    doc.appendChild(e);
    e.setAttribute("att1", "value1");
    Attr attr = doc.createAttributeNS("urn:test2", "att2");
    attr.setValue("value2");
    attr.setPrefix("p");
    e.setAttribute("xmlns:p", "urn:test2");
    e.setAttributeNode(attr);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writeXml(doc, baos);
    LOG.info(baos.toString());
    W3CDOMStreamReader reader = new W3CDOMStreamReader(doc.getDocumentElement());
    testAttributes(reader);
}

100. W3CDOMStreamReaderTest#testElementChild()

View license
public void testElementChild() throws Exception {
    Document doc = getDocument();
    Element e = doc.createElementNS("urn:test", "root");
    e.setAttribute("xmlns", "urn:test");
    Element child = doc.createElementNS("urn:test2", "child");
    child.setAttribute("xmlns:a", "urn:test2");
    child.setPrefix("a");
    e.appendChild(child);
    doc.appendChild(e);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writeXml(doc, baos);
    LOG.info(baos.toString());
    W3CDOMStreamReader reader = new W3CDOMStreamReader(e);
    testElementChild(reader);
}