Java Code Examples for org.w3c.dom.Node#appendChild()

The following examples show how to use org.w3c.dom.Node#appendChild() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * This method invokes the abstract {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String prefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element dmElem = DOMUtils.createElement(ownerDoc, "DigestMethod",
                                            XMLSignature.XMLNS, prefix);
    DOMUtils.setAttribute(dmElem, "Algorithm", getAlgorithm());

    if (params != null) {
        marshalParams(dmElem, prefix);
    }

    parent.appendChild(dmElem);
}
 
Example 2
public void marshal(Node parent, String dsPrefix,
                    DOMCryptoContext context)
    throws MarshalException
{
    // create SignatureValue element
    sigValueElem = DOMUtils.createElement(ownerDoc, "SignatureValue",
                                          XMLSignature.XMLNS, dsPrefix);
    if (valueBase64 != null) {
        sigValueElem.appendChild(ownerDoc.createTextNode(valueBase64));
    }

    // append Id attribute, if specified
    DOMUtils.setAttributeID(sigValueElem, "Id", id);
    parent.appendChild(sigValueElem);
}
 
Example 3
Source Project: karate   File: Engine.java    License: MIT License 5 votes vote down vote up
public static File saveResultHtml(String targetDir, FeatureResult result, String fileName) {
    DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    formatter.applyPattern("0.######");
    String html = getClasspathResource("report-template.html");
    String img = getClasspathResource("karate-logo.svg");
    Node svg = XmlUtils.toXmlDoc(img);
    String js = getClasspathResource("report-template-js.txt");
    Document doc = XmlUtils.toXmlDoc(html);
    XmlUtils.setByPath(doc, "/html/body/img", svg);
    String baseName = result.getPackageQualifiedName();
    set(doc, "/html/head/title", baseName);
    set(doc, "/html/head/script", js);
    for (ScenarioResult sr : result.getScenarioResults()) {
        Node scenarioDiv = div(doc, "scenario");
        append(doc, "/html/body/div", scenarioDiv);
        Node scenarioHeadingDiv = div(doc, "scenario-heading",
                node(doc, "span", "scenario-keyword", sr.getScenario().getKeyword() + ": " + sr.getScenario().getDisplayMeta()),
                node(doc, "span", "scenario-name", sr.getScenario().getName()));
        scenarioDiv.appendChild(scenarioHeadingDiv);
        for (StepResult stepResult : sr.getStepResults()) {
            stepHtml(doc, formatter, stepResult, scenarioDiv);
        }
    }
    if (fileName == null) {
        fileName = baseName + ".html";
    }
    File file = new File(targetDir + File.separator + fileName);
    String xml = "<!DOCTYPE html>\n" + XmlUtils.toString(doc, false);
    try {
        FileUtils.writeToFile(file, xml);
        System.out.println("\nHTML report: (paste into browser to view) | Karate version: "
                + FileUtils.getKarateVersion() + "\n"
                + file.toURI()
                + "\n---------------------------------------------------------\n");
    } catch (Exception e) {
        System.out.println("html report output failed: " + e.getMessage());
    }
    return file;
}
 
Example 4
private static void writeTo(File f, ITXtTest t) {
    BufferedImage src = createBufferedImage();
    try (ImageOutputStream imageOutputStream =
            ImageIO.createImageOutputStream(f)) {

        ImageTypeSpecifier imageTypeSpecifier =
            new ImageTypeSpecifier(src);
        ImageWriter imageWriter =
            ImageIO.getImageWritersByFormatName("PNG").next();

        imageWriter.setOutput(imageOutputStream);

        IIOMetadata m =
            imageWriter.getDefaultImageMetadata(imageTypeSpecifier, null);

        String format = m.getNativeMetadataFormatName();
        Node root = m.getAsTree(format);

        IIOMetadataNode iTXt = t.getNode();
        root.appendChild(iTXt);
        m.setFromTree(format, root);

        imageWriter.write(new IIOImage(src, null, m));
        System.out.println("Writing done.");
    } catch (Throwable e) {
        throw new RuntimeException("Writing test failed.", e);
    }
}
 
Example 5
private void appendTextNode() {
    if (_textBuffer.length() > 0) {
        final Node last = (Node)_nodeStk.peek();
        if (last == _root && _nextSiblingCache != null) {
            _lastSibling = last.insertBefore(_document.createTextNode(_textBuffer.toString()), _nextSiblingCache);
        }
        else {
            _lastSibling = last.appendChild(_document.createTextNode(_textBuffer.toString()));
        }
        _textBuffer.setLength(0);
    }
}
 
Example 6
Source Project: JDKSourceCode1.8   File: SAX2DOM.java    License: MIT License 5 votes vote down vote up
/**
 * adds processing instruction node to DOM.
 */
public void processingInstruction(String target, String data) {
    appendTextNode();
    final Node last = (Node)_nodeStk.peek();
    ProcessingInstruction pi = _document.createProcessingInstruction(
            target, data);
    if (pi != null){
      if (last == _root && _nextSibling != null)
          last.insertBefore(pi, _nextSibling);
      else
          last.appendChild(pi);

      _lastSibling = pi;
    }
}
 
Example 7
Source Project: jdk8u_jdk   File: ITXtTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void writeTo(File f, ITXtTest t) {
    BufferedImage src = createBufferedImage();
    try {
        ImageOutputStream imageOutputStream =
            ImageIO.createImageOutputStream(f);

        ImageTypeSpecifier imageTypeSpecifier =
            new ImageTypeSpecifier(src);
        ImageWriter imageWriter =
            ImageIO.getImageWritersByFormatName("PNG").next();

        imageWriter.setOutput(imageOutputStream);

        IIOMetadata m =
            imageWriter.getDefaultImageMetadata(imageTypeSpecifier, null);

        String format = m.getNativeMetadataFormatName();
        Node root = m.getAsTree(format);

        IIOMetadataNode iTXt = t.getNode();
        root.appendChild(iTXt);
        m.setFromTree(format, root);

        imageWriter.write(new IIOImage(src, null, m));
        imageOutputStream.close();
        System.out.println("Writing done.");
    } catch (Throwable e) {
        throw new RuntimeException("Writing test failed.", e);
    }
}
 
Example 8
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);
    Element xdElem = DOMUtils.createElement(ownerDoc, "X509Data",
                                            XMLSignature.XMLNS, dsPrefix);

    // append children and preserve order
    for (int i = 0, size = content.size(); i < size; i++) {
        Object object = content.get(i);
        if (object instanceof X509Certificate) {
            marshalCert((X509Certificate)object,xdElem,ownerDoc,dsPrefix);
        } else if (object instanceof XMLStructure) {
            if (object instanceof X509IssuerSerial) {
                ((DOMX509IssuerSerial)object).marshal
                    (xdElem, dsPrefix, context);
            } else {
                javax.xml.crypto.dom.DOMStructure domContent =
                    (javax.xml.crypto.dom.DOMStructure)object;
                DOMUtils.appendChild(xdElem, domContent.getNode());
            }
        } else if (object instanceof byte[]) {
            marshalSKI((byte[])object, xdElem, ownerDoc, dsPrefix);
        } else if (object instanceof String) {
            marshalSubjectName((String)object, xdElem, ownerDoc,dsPrefix);
        } else if (object instanceof X509CRL) {
            marshalCRL((X509CRL)object, xdElem, ownerDoc, dsPrefix);
        }
    }

    parent.appendChild(xdElem);
}
 
Example 9
void marshalPublicKey(Node parent, Document doc, String dsPrefix,
                      DOMCryptoContext context)
    throws MarshalException
{
    parent.appendChild(externalPublicKey.getNode());
}
 
Example 10
Source Project: maven-framework-project   File: ModifyXMLFile.java    License: MIT License 4 votes vote down vote up
public static void main(String argv[]) {
 
   try {
	DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	Document doc = docBuilder.parse(ClassLoader.getSystemResourceAsStream("file.xml"));

	// Get the root element
	//Node company = doc.getFirstChild();

	// Get the staff element , it may not working if tag has spaces, or
	// whatever weird characters in front...it's better to use
	// getElementsByTagName() to get it directly.
	// Node staff = company.getFirstChild();

	// Get the staff element by tag name directly
	Node staff = doc.getElementsByTagName("staff").item(0);

	// update staff attribute
	NamedNodeMap attr = staff.getAttributes();
	Node nodeAttr = attr.getNamedItem("id");
	nodeAttr.setTextContent("2");

	// append a new node to staff
	Element age = doc.createElement("age");
	age.appendChild(doc.createTextNode("28"));
	staff.appendChild(age);

	// loop the staff child node
	NodeList list = staff.getChildNodes();

	for (int i = 0; i < list.getLength(); i++) {

          Node node = list.item(i);

	   // get the salary element, and update the value
	   if ("salary".equals(node.getNodeName())) {
		node.setTextContent("2000000");
	   }

                  //remove firstname
	   if ("firstname".equals(node.getNodeName())) {
		staff.removeChild(node);
	   }

	}

	// write the content into xml file
	TransformerFactory transformerFactory = TransformerFactory.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	DOMSource source = new DOMSource(doc);
	StreamResult result = new StreamResult(new File("target/file.xml"));
	transformer.transform(source, result);

	System.out.println("Done");

   } catch (ParserConfigurationException pce) {
	pce.printStackTrace();
   } catch (TransformerException tfe) {
	tfe.printStackTrace();
   } catch (IOException ioe) {
	ioe.printStackTrace();
   } catch (SAXException sae) {
	sae.printStackTrace();
   }
}
 
Example 11
Source Project: spring-analysis-note   File: DomContentHandler.java    License: MIT License 4 votes vote down vote up
@Override
public void processingInstruction(String target, String data) {
	Node parent = getParent();
	ProcessingInstruction pi = this.document.createProcessingInstruction(target, data);
	parent.appendChild(pi);
}
 
Example 12
Source Project: teamengine   File: ConfigFileCreator.java    License: Apache License 2.0 4 votes vote down vote up
private void processTestConfigFile(File configFile) {
	if (configFile != null) {
		Document docTest = getDocument(configFile);
		Node orgInTest = XMLUtils.getFirstNode(docTest,
				"/organization/name[1]");
		String org = orgInTest.getTextContent();
		String xpath = "/config/scripts/organization/name[text()='" + org
				+ "']";
		Node orgInMainConfig = XMLUtils.getFirstNode(docMain, xpath);
		// org doesn't exist
		if (orgInMainConfig == null) {
			// append to scripts
			Node orgInTestImported = docMain.importNode(
					orgInTest.getParentNode(), true);
			scripts.appendChild(orgInTestImported);
		} else {
			Node standardInTest = XMLUtils.getFirstNode(docTest,
					"/organization/standard[1]");
			String standardInTestName = XMLUtils.getFirstNode(docTest,
					"/organization/standard[1]/name").getTextContent();
			// check if a standard with this name already exists in main
			xpath = "/config/scripts/organization/standard/name[text()='"
					+ standardInTestName + "']";

			Node standardInMain = XMLUtils.getFirstNode(docMain, xpath);
			if (standardInMain == null) {
				// append to an existing organization
				Node orgInMain = orgInMainConfig.getParentNode();
				orgInMain.appendChild(docMain.importNode(standardInTest,
						true));

			} else {
				// standard already exists in main config, so append to
				// standard

				Node versionInTest = XMLUtils.getFirstNode(docTest,
						"/organization/standard/version[1]");

				standardInMain.getParentNode().appendChild(
						docMain.importNode(versionInTest, true));
			}
		}
		LOGR.config("Added " + configFile.getAbsolutePath()
				+ " to config file");
	} else {
		LOGR.config("No config file was found in dir "
				+ configFile.getAbsolutePath()
				+ ". It was not registered in the main config file.");
	}
}
 
Example 13
public void marshal(Node parent, String prefix, DOMCryptoContext context)
    throws MarshalException {
    parent.appendChild
        (DOMUtils.getOwnerDocument(parent).createTextNode(value));
}
 
Example 14
public void insertNode(Node newNode)
    throws DOMException, RangeException
{
    if ( newNode == null ) return; //throw exception?

    int type = newNode.getNodeType();

    if (fDocument.errorChecking) {
        if (fDetach) {
            throw new DOMException(
                    DOMException.INVALID_STATE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null));
        }
        if ( fDocument != newNode.getOwnerDocument() ) {
            throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null));
        }

        if (type == Node.ATTRIBUTE_NODE
                || type == Node.ENTITY_NODE
                || type == Node.NOTATION_NODE
                || type == Node.DOCUMENT_NODE)
        {
            throw new RangeExceptionImpl(
                    RangeException.INVALID_NODE_TYPE_ERR,
                    DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INVALID_NODE_TYPE_ERR", null));
        }
    }
    Node cloneCurrent;
    Node current;
    int currentChildren = 0;
    fInsertedFromRange = true;

    //boolean MULTIPLE_MODE = false;
    if (fStartContainer.getNodeType() == Node.TEXT_NODE) {

        Node parent = fStartContainer.getParentNode();
        currentChildren = parent.getChildNodes().getLength(); //holds number of kids before insertion
        // split text node: results is 3 nodes..
        cloneCurrent = fStartContainer.cloneNode(false);
        ((TextImpl)cloneCurrent).setNodeValueInternal(
                (cloneCurrent.getNodeValue()).substring(fStartOffset));
        ((TextImpl)fStartContainer).setNodeValueInternal(
                (fStartContainer.getNodeValue()).substring(0,fStartOffset));
        Node next = fStartContainer.getNextSibling();
        if (next != null) {
                if (parent !=  null) {
                    parent.insertBefore(newNode, next);
                    parent.insertBefore(cloneCurrent, next);
                }
        } else {
                if (parent != null) {
                    parent.appendChild(newNode);
                    parent.appendChild(cloneCurrent);
                }
        }
         //update ranges after the insertion
         if ( fEndContainer == fStartContainer) {
              fEndContainer = cloneCurrent; //endContainer is the new Node created
              fEndOffset -= fStartOffset;
         }
         else if ( fEndContainer == parent ) {    //endContainer was not a text Node.
              //endOffset + = number_of_children_added
               fEndOffset += (parent.getChildNodes().getLength() - currentChildren);
         }

         // signal other Ranges to update their start/end containers/offsets
         signalSplitData(fStartContainer, cloneCurrent, fStartOffset);


    } else { // ! TEXT_NODE
        if ( fEndContainer == fStartContainer )      //need to remember number of kids
            currentChildren= fEndContainer.getChildNodes().getLength();

        current = fStartContainer.getFirstChild();
        int i = 0;
        for(i = 0; i < fStartOffset && current != null; i++) {
            current=current.getNextSibling();
        }
        if (current != null) {
            fStartContainer.insertBefore(newNode, current);
        } else {
            fStartContainer.appendChild(newNode);
        }
        //update fEndOffset. ex:<body><p/></body>. Range(start;end): body,0; body,1
        // insert <h1>: <body></h1><p/></body>. Range(start;end): body,0; body,2
        if ( fEndContainer == fStartContainer && fEndOffset != 0 ) {     //update fEndOffset if not 0
            fEndOffset += (fEndContainer.getChildNodes().getLength() - currentChildren);
        }
    }
    fInsertedFromRange = false;
}
 
Example 15
Source Project: jdk1.8-source-analysis   File: DOMUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 16
void marshalPublicKey(Node parent, Document doc, String dsPrefix,
                      DOMCryptoContext context)
    throws MarshalException
{
    parent.appendChild(externalPublicKey.getNode());
}
 
Example 17
Source Project: Flashtool   File: Context.java    License: GNU General Public License v3.0 4 votes vote down vote up
public void addAsChildTo(Node node) {
	for (Node neighbour : neighbours) {
		node.appendChild(neighbour);
	}
	node.appendChild(element);
}
 
Example 18
public void processingInstruction(String target, String data) throws org.xml.sax.SAXException {
    Node parent = nodeStack.peek();
    Node n = document.createProcessingInstruction(target, data);
    parent.appendChild(n);
}
 
Example 19
Source Project: cosmo   File: DomReader.java    License: Apache License 2.0 4 votes vote down vote up
private static Node readNode(Document d, XMLStreamReader reader) throws XMLStreamException {
    Node root = null;
    Node current = null;

    while (reader.hasNext()) {
        reader.next();

        if (reader.isEndElement()) {
            
            if (current.getParentNode() == null) {
                break;
            }
            current = current.getParentNode();
        }

        if (reader.isStartElement()) {
            Element e = readElement(d, reader);
            if (root == null) {
                root = e;
            }

            if (current != null) {
                current.appendChild(e);
            }

            current = e;
            continue;
        }

        if (reader.isCharacters()) {
            CharacterData cd = d.createTextNode(reader.getText());
            if (root == null) {
                return cd;
            }
            if (current == null) {
                return cd;
            }
            current.appendChild(cd);

            continue;
        }
    }

    return root;
}
 
Example 20
Source Project: ats-framework   File: HttpClient.java    License: Apache License 2.0 4 votes vote down vote up
public Node readHeaders( Document dom, Node responseNode, int contentLength ) throws Exception {

        Map<String, List<String>> headersMap = getHeadersMap(urlConnection);

        // add headers
        for (Entry<String, List<String>> headerEntry : headersMap.entrySet()) {

            String headerValue = null;
            String headerName = headerEntry.getKey();
            List<String> headerValues = headerEntry.getValue();
            if (headerValues.size() > 1
                && HeaderMatcher.SET_COOKIE_HEADER_NAME.equalsIgnoreCase(headerName)) {

                // There are more than one "Set-Cookie" headers and we need to merge them in one, separated with ';'
                StringBuilder sb = new StringBuilder();
                for (String value : headerValues) {
                    if (value.endsWith(";")) {
                        sb.append(value);
                    } else {
                        sb.append(value + ';');
                    }
                }
                headerValue = sb.toString();
            } else {

                headerValue = headerValues.get(0);
            }

            if (headerName == null) {
                // this should be the response status header, something like 'HTTP/1.1 200 OK'
                String responseStatusString = headerValue;
                String responseStatus = responseStatusString.substring(responseStatusString.indexOf(' ')
                                                                       + 1, responseStatusString.length());

                // add response result
                Element actionResponseResult = dom.createElement(TOKEN_HTTP_RESPONSE_RESULT);
                actionResponseResult.appendChild(dom.createTextNode(responseStatus));
                responseNode.appendChild(actionResponseResult);
            } else {

                // we will skip "Transfer-Encoding" header because we have to verify the content length
                // and will replace it with "Content-Length" header, which is always expected in the recorded XML files
                if (headerName.equalsIgnoreCase(HeaderMatcher.TRANSFER_ENCODING_HEADER_NAME)
                    && contentLength > -1) {

                    headerName = HeaderMatcher.CONTENT_LENGTH_HEADER_NAME;
                    headerValue = String.valueOf(contentLength);
                }

                Element header = dom.createElement(TOKEN_HTTP_HEADER);
                header.setAttribute(TOKEN_HEADER_NAME_ATTRIBUTE, headerName);
                header.setAttribute(TOKEN_HEADER_VALUE_ATTRIBUTE, headerValue);

                responseNode.appendChild(header);
            }
        }

        return responseNode;
    }