Example usage for org.w3c.dom Node appendChild

List of usage examples for org.w3c.dom Node appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Node appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:fi.csc.kapaVirtaAS.MessageTransformer.java

public String transform(String message, MessageDirection direction) throws Exception {
    try {/*  w w w .j  a va  2 s.c  o m*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = dBuilder
                .parse(new InputSource(new ByteArrayInputStream(stripXmlDefinition(message).getBytes())));
        doc.setXmlVersion("1.0");
        doc.normalizeDocument();
        Element root = doc.getDocumentElement();

        if (direction == MessageDirection.XRoadToVirta) {
            // Save XRoad schema prefix for response message
            xroadSchemaPrefix = namedNodeMapToStream(root.getAttributes())
                    .filter(node -> node
                            .getNodeValue().toLowerCase().contains(conf.getXroadSchema().toLowerCase()))
                    .findFirst()
                    .orElseThrow(
                            () -> new DOMException(DOMException.NOT_FOUND_ERR, "Xroad schema prefix not found"))
                    .getNodeName();

            xroadIdSchemaPrefix = namedNodeMapToStream(root.getAttributes())
                    .filter(node -> node.getNodeValue().toLowerCase()
                            .contains(conf.getXroadIdSchema().toLowerCase()))
                    .findFirst().orElseThrow(() -> new DOMException(DOMException.NOT_FOUND_ERR,
                            "XroadId schema prefix not found"))
                    .getNodeName();

            // Change tns schema
            getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getAdapterServiceSchema())
                    .map(attribute -> setNodeValueToNode(attribute, conf.getVirtaServiceSchema()));

            //There should be two children under the root node: header and body
            for (int i = 0; i < root.getChildNodes().getLength(); ++i) {
                Node child = root.getChildNodes().item(i);
                // Save soap-headers for reply message and remove child elements under soap-headers
                if (child.getNodeName().toLowerCase().contains("header")) {
                    this.xroadHeaderElement = child.cloneNode(true);
                    root.replaceChild(child.cloneNode(false), child);
                }
                // Change SOAP-body
                else if (child.getNodeName().toLowerCase().contains("body")) {
                    for (int j = 0; j < child.getChildNodes().getLength(); ++j) {
                        if (child.getChildNodes().item(j).getNodeType() == Node.ELEMENT_NODE) {
                            doc.renameNode(child.getChildNodes().item(j), conf.getVirtaServiceSchema(),
                                    child.getChildNodes().item(j).getNodeName() + "Request");
                            break;
                        }
                    }

                }
            }
        }
        if (direction == MessageDirection.VirtaToXRoad) {
            // Add XRoad schemas with saved prefix to response message
            root.setAttribute(xroadSchemaPrefix, conf.getXroadSchema());
            root.setAttribute(xroadIdSchemaPrefix, conf.getXroadIdSchema());

            // Change tns schema
            getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getVirtaServiceSchema())
                    .map(attribute -> setNodeValueToNode(attribute, conf.getAdapterServiceSchema()));

            // Change SOAP-headers
            Node headerNode = getNodeByKeyword(nodeListToStream(root.getChildNodes()), "header").get();
            for (int i = 0; i < this.xroadHeaderElement.getChildNodes().getLength(); ++i) {
                headerNode.appendChild(doc.importNode(this.xroadHeaderElement.getChildNodes().item(i), true));
            }

            // Change SOAP-body
            getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body")
                    .map(bodyNode -> removeAttribureFromElement(nodeToElement(bodyNode), virtaServicePrefix))
                    .map(bodyNode -> setAttributeToElement(nodeToElement(bodyNode), virtaServicePrefix,
                            conf.getAdapterServiceSchema()));

            //Virta gives malformed soap fault message. Need to parse it correct.
            getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body")
                    .map(bodyNode -> nodeListToStream(bodyNode.getChildNodes())).map(
                            nodesInBodyStream -> getNodeByKeyword(nodesInBodyStream, "fault")
                                    .map(faultNode -> removeAttribureFromElement(
                                            nodeToElement(nodeToElement(faultNode)
                                                    .getElementsByTagName("faultstring").item(0)),
                                            "xml:lang")));
        }

        doc.normalizeDocument();
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(domSource, result);
        message = writer.toString();

        return stripXmlDefinition(message);
    } catch (Exception e) {
        if (direction == MessageDirection.XRoadToVirta) {
            log.error("Error in parsing request message.");
            throw e;
        } else {
            log.error("Error in parsing response message");
            log.error(e.toString());
            return stripXmlDefinition(faultMessageService.generateSOAPFault(message,
                    faultMessageService.getResValidFail(), this.xroadHeaderElement));
        }
    }
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrProjectWizardIterator.java

private void pomConfigMvnPlugin(Document doc) throws DOMException, SAXException, IOException {
    // modify pom.xml content and add cfg to spring maven plugin
    NodeList nl = doc.getElementsByTagName("plugin");
    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element el = (Element) nl.item(i);
            NodeList grpId = el.getElementsByTagName("groupId");
            NodeList artId = el.getElementsByTagName("artifactId");
            if (grpId.getLength() > 0 && artId.getLength() > 0
                    && "org.springframework.boot".equals(grpId.item(0).getTextContent())
                    && "spring-boot-maven-plugin".equals(artId.item(0).getTextContent())) {
                Node cfg = doc.createElement("configuration");
                Node frk = doc.createElement("fork");
                frk.setTextContent("true");
                cfg.appendChild(frk);
                el.appendChild(cfg);//from   www  .ja  v  a  2 s. c o m
            }
        }
    }
}

From source file:ca.uqac.info.trace.generation.AmazonEcsGenerator.java

/**
 * Creates an cart clear request-response pair.
 * @param trace The trace to which the events will be added
 * @param carts The current set of shopping carts
 * @param items The current set of catalog items
 *///from ww  w  . j  a v  a 2 s  . c o  m
private void createCartClear(EventTrace trace, Vector<Cart> carts, Vector<Item> items) {
    // Pick a cart to clear
    Vector<Cart> eligible_carts = new Vector<Cart>(carts);
    RandomPicker<Cart> cart_picker = new RandomPicker<Cart>(m_random);
    Cart chosen_cart = cart_picker.pick(eligible_carts);
    { // Create the cart clear message
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartClear"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        trace.add(new Event(n));
    }
    { // Create the cart clear response message
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartClearResponse"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        trace.add(new Event(n));
    }
}

From source file:ca.uqac.info.trace.generation.AmazonEcsGenerator.java

/**
 * Creates an Item Search request-response pair.
 * @param trace The trace to which the events will be added
 * @param carts The current set of shopping carts
 * @param items The current set of catalog items
 *//*from   w  w  w  . j  ava 2 s . c  o m*/
private void createItemSearch(EventTrace trace, Vector<Cart> carts, Vector<Item> items) {
    { // Create the search request
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "ItemSearch"));
        n.appendChild(createKeyValue(trace, "Keyword", "dummy"));
        trace.add(new Event(n));
    }
    { // Create the search response
        int num_items = m_random.nextInt(m_maxCartSize);
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "ItemSearchResponse"));
        Node n_items = trace.createElement("Items");
        for (int i = 0; i < num_items; i++) {
            RandomPicker<Item> item_picker = new RandomPicker<Item>(m_random);
            Item cart_i = item_picker.pick(items);
            n_items.appendChild(cart_i.toNode(trace));
        }
        n.appendChild(n_items);
        trace.add(new Event(n));
    }
}

From source file:ca.uqac.info.trace.generation.AmazonEcsGenerator.java

/**
 * Creates an cart remove request-response pair.
 * @param trace The trace to which the events will be added
 * @param carts The current set of shopping carts
 * @param items The current set of catalog items
 *//*from w w w .  j a v  a 2  s.c o  m*/
private void createCartRemove(EventTrace trace, Vector<Cart> carts, Vector<Item> items) {
    // Pick a cart to remove from
    Vector<Cart> eligible_carts = new Vector<Cart>();
    for (Cart c : carts)
        if (c.size() > 0)
            eligible_carts.add(c);
    RandomPicker<Cart> cart_picker = new RandomPicker<Cart>(m_random);
    Cart chosen_cart = cart_picker.pick(eligible_carts);
    // From that cart, pick an item to remove
    RandomPicker<Item> item_picker = new RandomPicker<Item>(m_random);
    Item chosen_item = item_picker.pick(items);
    { // Create the cart remove message
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartRemove"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        Node n_items = trace.createElement("Items");
        Node n_item = trace.createElement("Item");
        n_item.appendChild(createKeyValue(trace, "ItemId", chosen_item.getId()));
        n_items.appendChild(n_item);
        n.appendChild(n_items);
        trace.add(new Event(n));
    }
    // Remove item from cart
    chosen_cart.remove(chosen_item);
    { // Create the cart remove response message
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartRemoveResponse"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        n.appendChild(chosen_cart.toNode(trace));
        trace.add(new Event(n));
    }
}

From source file:ca.uqac.info.trace.generation.AmazonEcsGenerator.java

/**
 * Creates an cart edit request-response pair.
 * @param trace The trace to which the events will be added
 * @param carts The current set of shopping carts
 * @param items The current set of catalog items
 *//*from w  w  w.  j a va2s  .co  m*/
private void createCartEdit(EventTrace trace, Vector<Cart> carts, Vector<Item> items) {
    // Pick a cart to edit
    Vector<Cart> eligible_carts = new Vector<Cart>();
    for (Cart c : carts)
        if (c.size() > 0)
            eligible_carts.add(c);
    RandomPicker<Cart> cart_picker = new RandomPicker<Cart>(m_random);
    Cart chosen_cart = cart_picker.pick(eligible_carts);
    // From that cart, pick an item to edit
    Item chosen_item = chosen_cart.pickItem();
    Integer new_qty = new Integer(m_random.nextInt(MAX_QTY));
    { // Create the cart edit message
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartEdit"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        Node n_items = trace.createElement("Items");
        Node n_item = trace.createElement("Item");
        n_item.appendChild(createKeyValue(trace, "ItemId", chosen_item.getId()));
        n_item.appendChild(createKeyValue(trace, "Quantity", new_qty));
        n_items.appendChild(n_item);
        n.appendChild(n_items);
        trace.add(new Event(n));
    }
    // Edit item in cart
    chosen_cart.put(chosen_item, new_qty);
    { // Create the cart edit response message
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartEditResponse"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        n.appendChild(chosen_cart.toNode(trace));
        trace.add(new Event(n));
    }
}

From source file:ca.uqac.info.trace.generation.AmazonEcsGenerator.java

/**
 * Creates a Cart create request-response pair.
 * @param trace The trace to which the events will be added
 * @param carts The current set of shopping carts
 * @param items The current set of catalog items
 *///from  w  w w.  ja  v  a2  s.  c o m
private void createCartCreate(EventTrace trace, Vector<Cart> carts, Vector<Item> items) {
    Cart chosen_cart = new Cart();
    Vector<Item> items_to_add = new Vector<Item>();
    // Pick items to add to the cart
    RandomPicker<Item> item_picker = new RandomPicker<Item>(m_random);
    for (int i = 0; i < m_itemsPerOperation; i++) {
        int qty = 1;
        Item it = item_picker.pick(items);
        chosen_cart.put(it, qty);
        items_to_add.add(it);
    }
    // Add cart to list of carts
    carts.add(chosen_cart);
    { // Create the cart create request
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartCreate"));
        Node n_items = trace.createElement("Items");
        for (Item it : items_to_add) {
            Node n_item = trace.createElement("Item");
            n_item.appendChild(createKeyValue(trace, "ItemId", it.getId()));
            n_item.appendChild(createKeyValue(trace, "Quantity", 1));
            n_items.appendChild(n_item);
        }
        /*for (Item it : items_to_add)
        {
           n_items.appendChild(it.toNode(trace));
        }*/
        n.appendChild(n_items);
        trace.add(new Event(n));
    }
    { // Create the cart create response message
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartCreateResponse"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        n.appendChild(chosen_cart.toNode(trace));
        trace.add(new Event(n));
    }
}

From source file:ca.uqac.info.trace.generation.AmazonEcsGenerator.java

/**
 * Creates a Cart add request-response pair.
 * @param trace The trace to which the events will be added
 * @param carts The current set of shopping carts
 * @param items The current set of catalog items
 *///from  www  .j  ava 2 s  . c  o  m
private void createCartAdd(EventTrace trace, Vector<Cart> carts, Vector<Item> items) {
    // Pick a cart to add to
    Vector<Cart> eligible_carts = new Vector<Cart>(carts);
    for (Cart c : carts)
        if (c.size() < m_maxCartSize)
            eligible_carts.add(c);
    RandomPicker<Cart> cart_picker = new RandomPicker<Cart>(m_random);
    Cart chosen_cart = cart_picker.pick(eligible_carts);
    // From that cart, pick an item to add
    Vector<Item> eligible_items = new Vector<Item>();
    for (Item it : items)
        if (!chosen_cart.containsKey(it))
            eligible_items.add(it);
    RandomPicker<Item> item_picker = new RandomPicker<Item>(m_random);
    Vector<Item> items_to_add = new Vector<Item>();
    for (int i = 0; i < m_itemsPerOperation; i++) {
        int qty = 1;
        Item it = item_picker.pick(eligible_items);
        chosen_cart.put(it, qty);
        items_to_add.add(it);
    }
    { // Create the cart add request
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartAdd"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        Node n_items = trace.createElement("Items");
        for (Item it : items_to_add) {
            Node n_item = trace.createElement("Item");
            n_item.appendChild(createKeyValue(trace, "ItemId", it.getId()));
            n_item.appendChild(createKeyValue(trace, "Quantity", 1));
            n_items.appendChild(n_item);
        }
        n.appendChild(n_items);
        trace.add(new Event(n));
    }
    { // Create the cart add response message
        Node n = trace.getNode();
        n.appendChild(createKeyValue(trace, "SessionKey", "0"));
        n.appendChild(createKeyValue(trace, "Action", "CartAddResponse"));
        n.appendChild(createKeyValue(trace, "CartId", chosen_cart.getId()));
        n.appendChild(chosen_cart.toNode(trace));
        trace.add(new Event(n));
    }
}

From source file:de.juwimm.cms.util.SmallSiteConfigReader.java

public Node buildXmlPathToLeaf(String xmlPath) {
    String fullXmlPath = getRelativeNodePath() + "/" + xmlPath;
    String[] pathComponents = fullXmlPath.split("/");
    try {//from   w w  w .  j av a 2  s  .  c  o m
        Document document = this.getConfdoc();
        Node prevNode = document;
        Node nextNode;
        for (int i = 0; i < pathComponents.length - 1; i++) {
            nextNode = XercesHelper.findNode(prevNode, pathComponents[i]);
            if (nextNode == null) {
                nextNode = document.createElement(pathComponents[i]);
                prevNode.appendChild(nextNode);
            }
            prevNode = nextNode;
        }

        return prevNode;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Could not read from site config path:" + fullXmlPath);
        }
        return null;
    }
}

From source file:com.gargoylesoftware.htmlunit.html.impl.SimpleRange.java

/**
 * {@inheritDoc}/*from ww  w  .  j a v  a 2 s. co m*/
 */
@Override
public void surroundContents(final Node newParent) throws DOMException, RangeException {
    newParent.appendChild(extractContents());
    insertNode(newParent);
    setStart(newParent, 0);
    setEnd(newParent, getMaxOffset(newParent));
}