Example usage for org.w3c.dom Document adoptNode

List of usage examples for org.w3c.dom Document adoptNode

Introduction

In this page you can find the example usage for org.w3c.dom Document adoptNode.

Prototype

public Node adoptNode(Node source) throws DOMException;

Source Link

Document

Attempts to adopt a node from another document to this document.

Usage

From source file:se.unlogic.hierarchy.core.servlets.CoreServlet.java

private void addBackgroundModuleResponses(List<BackgroundModuleResponse> backgroundModuleResponses,
        Document doc, User user, HttpServletRequest req) {

    if (backgroundModuleResponses != null) {

        Element backgroundsModuleResponsesElement = doc.createElement("backgroundsModuleResponses");
        doc.getFirstChild().appendChild(backgroundsModuleResponsesElement);

        Document debugDoc;//from   w  w w  . j a  v a2 s .  com

        // Write xml to file if debug enabled
        if (backgroundModuleXMLDebug && !StringUtils.isEmpty(this.backgroundModuleXMLDebugFile)) {

            debugDoc = XMLUtils.createDomDocument();
            debugDoc.appendChild(debugDoc.createElement("BackgroundModuleDebug"));

        } else {

            debugDoc = null;
        }

        for (BackgroundModuleResponse moduleResponse : backgroundModuleResponses) {

            if (isValidResponse(moduleResponse)) {

                if (moduleResponse.getResponseType() == ResponseType.HTML) {

                    // Append module html response
                    Element responseElement = doc.createElement("response");
                    backgroundsModuleResponsesElement.appendChild(responseElement);

                    Element htmlElement = doc.createElement("HTML");
                    responseElement.appendChild(htmlElement);

                    htmlElement.appendChild(doc.createCDATASection(moduleResponse.getHtml()));

                    this.appendSlots(moduleResponse, doc, responseElement);

                } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_CORE_TRANSFORMATION) {

                    // Append module response
                    Element responseElement = doc.createElement("response");
                    backgroundsModuleResponsesElement.appendChild(responseElement);

                    Element xmlElement = doc.createElement("XML");
                    responseElement.appendChild(xmlElement);

                    xmlElement.appendChild(doc.adoptNode(moduleResponse.getElement()));

                    this.appendSlots(moduleResponse, doc, responseElement);

                } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_SEPARATE_TRANSFORMATION) {

                    if (moduleResponse.getTransformer() != null) {

                        //Append XML to debug document
                        if (debugDoc != null) {

                            this.log.debug("Background XML debug mode enabled, appending XML from module "
                                    + moduleResponse.getModuleDescriptor() + " to XML debug document");

                            try {
                                Element documentElement = (Element) debugDoc
                                        .importNode(moduleResponse.getDocument().getDocumentElement(), true);

                                if (moduleResponse.getModuleDescriptor() != null) {

                                    documentElement.setAttribute("moduleID",
                                            moduleResponse.getModuleDescriptor().getModuleID() + "");
                                    documentElement.setAttribute("name",
                                            moduleResponse.getModuleDescriptor().getName());
                                }

                                debugDoc.getDocumentElement().appendChild(documentElement);

                            } catch (Exception e) {

                                this.log.error("Error appending XML from module "
                                        + moduleResponse.getModuleDescriptor() + " to  XML debug document", e);
                            }
                        }

                        // Transform output
                        try {
                            StringWriter stringWriter = new StringWriter();
                            this.log.debug("Background module XML transformation starting");

                            XMLTransformer.transformToWriter(moduleResponse.getTransformer(),
                                    moduleResponse.getDocument(), stringWriter, encoding);

                            this.log.debug(
                                    "Background module XML transformation finished, appending result...");

                            // Append module response

                            Element responseElement = doc.createElement("response");
                            backgroundsModuleResponsesElement.appendChild(responseElement);

                            Element htmlElement = doc.createElement("HTML");
                            responseElement.appendChild(htmlElement);

                            htmlElement.appendChild(doc.createCDATASection(stringWriter.toString()));

                            this.appendSlots(moduleResponse, doc, responseElement);

                            this.log.debug("Result appended");
                        } catch (Exception e) {
                            this.log.error("Tranformation of background module response from module"
                                    + moduleResponse.getModuleDescriptor()
                                    + " failed while processing request from user " + user + " accessing from "
                                    + req.getRemoteAddr(), e);
                        }
                    } else {
                        this.log.error(
                                "Background module response for separate transformation without attached stylesheet returned by module "
                                        + moduleResponse.getModuleDescriptor()
                                        + " while processing request from user " + user + " accessing from "
                                        + req.getRemoteAddr());
                    }
                }
            }
        }

        //Write background module XML debug to file
        if (debugDoc != null && debugDoc.getDocumentElement().hasChildNodes()) {

            log.debug("Writing background module XML debug to file " + backgroundModuleXMLDebugFile);

            try {
                XMLUtils.writeXMLFile(debugDoc,
                        this.applicationFileSystemPath + "WEB-INF/" + backgroundModuleXMLDebugFile, true,
                        encoding);

            } catch (Exception e) {

                log.error("Error writing background module XML debug to file " + backgroundModuleXMLDebugFile,
                        e);
            }
        }
    }
}

From source file:sf.net.experimaestro.utils.JSUtils.java

public static Object toDOM(Scriptable scope, Object object, OptionalDocument document) {
    // Unwrap if needed (if this is not a JSBaseObject)
    if (object instanceof Wrapper && !(object instanceof JSBaseObject))
        object = ((Wrapper) object).unwrap();

    // It is already a DOM node
    if (object instanceof Node)
        return object;

    if (object instanceof XMLObject) {
        final XMLObject xmlObject = (XMLObject) object;
        String className = xmlObject.getClassName();

        if (className.equals("XMLList")) {
            LOGGER.debug("Transforming from XMLList [%s]", object);
            final Object[] ids = xmlObject.getIds();
            if (ids.length == 1)
                return toDOM(scope, xmlObject.get((Integer) ids[0], xmlObject), document);

            Document doc = XMLUtils.newDocument();
            DocumentFragment fragment = doc.createDocumentFragment();

            for (int i = 0; i < ids.length; i++) {
                Node node = (Node) toDOM(scope, xmlObject.get((Integer) ids[i], xmlObject), document);
                if (node instanceof Document)
                    node = ((Document) node).getDocumentElement();
                fragment.appendChild(doc.adoptNode(node));
            }//from ww w .j ava 2  s . c o m

            return fragment;
        }

        // XML node
        if (className.equals("XML")) {
            // FIXME: this strips all whitespaces!
            Node node = XMLLibImpl.toDomNode(object);
            LOGGER.debug("Got node from JavaScript [%s / %s] from [%s]", node.getClass(),
                    XMLUtils.toStringObject(node), object.toString());

            if (node instanceof Document)
                node = ((Document) node).getDocumentElement();

            node = document.get().adoptNode(node.cloneNode(true));
            return node;
        }

        throw new RuntimeException(format("Not implemented: convert %s to XML", className));

    }

    if (object instanceof NativeArray) {
        NativeArray array = (NativeArray) object;
        ArrayNodeList list = new ArrayNodeList();
        for (Object x : array) {
            Object o = toDOM(scope, x, document);
            if (o instanceof Node)
                list.add(document.cloneAndAdopt((Node) o));
            else {
                for (Node node : XMLUtils.iterable((NodeList) o)) {
                    list.add(document.cloneAndAdopt(node));
                }
            }
        }
        return list;
    }

    if (object instanceof NativeObject) {
        // JSON case: each key of the JS object is an XML element
        NativeObject json = (NativeObject) object;
        ArrayNodeList list = new ArrayNodeList();

        for (Object _id : json.getIds()) {

            String jsQName = JSUtils.toString(_id);

            if (jsQName.length() == 0) {
                final Object seq = toDOM(scope, json.get(jsQName, json), document);
                for (Node node : XMLUtils.iterable(seq)) {
                    if (node instanceof Document)
                        node = ((Document) node).getDocumentElement();
                    list.add(document.cloneAndAdopt(node));
                }
            } else if (jsQName.charAt(0) == '@') {
                final QName qname = QName.parse(jsQName.substring(1), null, new JSNamespaceBinder(scope));
                Attr attribute = document.get().createAttributeNS(qname.getNamespaceURI(),
                        qname.getLocalPart());
                StringBuilder sb = new StringBuilder();
                for (Node node : XMLUtils.iterable(toDOM(scope, json.get(jsQName, json), document))) {
                    sb.append(node.getTextContent());
                }

                attribute.setTextContent(sb.toString());
                list.add(attribute);
            } else {
                final QName qname = QName.parse(jsQName, null, new JSNamespaceBinder(scope));
                Element element = qname.hasNamespace()
                        ? document.get().createElementNS(qname.getNamespaceURI(), qname.getLocalPart())
                        : document.get().createElement(qname.getLocalPart());

                list.add(element);

                final Object seq = toDOM(scope, json.get(jsQName, json), document);
                for (Node node : XMLUtils.iterable(seq)) {
                    if (node instanceof Document)
                        node = ((Document) node).getDocumentElement();
                    node = document.get().adoptNode(node.cloneNode(true));
                    if (node.getNodeType() == Node.ATTRIBUTE_NODE)
                        element.setAttributeNodeNS((Attr) node);
                    else
                        element.appendChild(node);
                }
            }
        }

        return list;
    }

    if (object instanceof Double) {
        // Wrap a double
        final Double x = (Double) object;
        if (x.longValue() == x.doubleValue())
            return document.get().createTextNode(Long.toString(x.longValue()));
        return document.get().createTextNode(Double.toString(x));
    }

    if (object instanceof Integer) {
        return document.get().createTextNode(Integer.toString((Integer) object));
    }

    if (object instanceof CharSequence) {
        return document.get().createTextNode(object.toString());
    }

    if (object instanceof UniqueTag)
        throw new XPMRuntimeException("Undefined cannot be converted to XML", object.getClass());

    if (object instanceof JSNode) {
        Node node = ((JSNode) object).getNode();
        if (document.has()) {
            if (node instanceof Document)
                node = ((Document) node).getDocumentElement();
            return document.get().adoptNode(node);
        }
        return node;
    }

    if (object instanceof JSNodeList) {
        return ((JSNodeList) object).getList();
    }

    if (object instanceof Scriptable) {
        ((Scriptable) object).getDefaultValue(String.class);
    }

    // By default, convert to string
    return document.get().createTextNode(object.toString());
}

From source file:sf.net.experimaestro.utils.JSUtils.java

/**
 * Converts a JavaScript object into an XML document
 *
 * @param srcObject The javascript object to convert
 * @param wrapName  If the object is not already a document and has more than one
 *                  element child (or zero), use this to wrap the elements
 * @return/*w w  w.ja va  2 s. c o m*/
 */
public static Document toDocument(Scriptable scope, Object srcObject, QName wrapName) {
    final Object object = toDOM(scope, srcObject);

    if (object instanceof Document)
        return (Document) object;

    Document document = XMLUtils.newDocument();

    // Add a new root element if needed
    NodeList childNodes;

    if (!(object instanceof Node)) {
        childNodes = (NodeList) object;
    } else {
        final Node dom = (Node) object;
        if (dom.getNodeType() == Node.ELEMENT_NODE) {
            childNodes = new NodeList() {
                @Override
                public Node item(int index) {
                    if (index == 0)
                        return dom;
                    throw new IndexOutOfBoundsException(Integer.toString(index) + " out of bounds");
                }

                @Override
                public int getLength() {
                    return 1;
                }
            };
        } else
            childNodes = dom.getChildNodes();
    }

    int elementCount = 0;
    for (int i = 0; i < childNodes.getLength(); i++)
        if (childNodes.item(i).getNodeType() == Node.ELEMENT_NODE)
            elementCount++;

    Node root = document;
    if (elementCount != 1) {
        root = document.createElementNS(wrapName.getNamespaceURI(), wrapName.getLocalPart());
        document.appendChild(root);
    }

    // Copy back in the DOM
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        node = node.cloneNode(true);
        document.adoptNode(node);
        root.appendChild(node);
    }

    return document;
}

From source file:xmlconverter.controller.logic.GetFileCount.java

/**
 * This method is/are going to update the site information. The statements
 * are based on flags that are passed. This method should detect if files
 * content has changed and also update thous changed if node count has
 * changed./*  w  w  w .  j a  va  2  s  .co m*/
 *
 * @param path
 * @param pathXml
 * @throws DOMException
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
private void updateSite(Document newDoc, File pathXml)
        throws TransformerException, DOMException, ParserConfigurationException, IOException, SAXException {
    //System.out.println("I updated: " + pathXml.getName());
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document oldDoc = docBuilder.parse(pathXml);

    //Old root & NodeList
    Node root = oldDoc.getFirstChild();
    NodeList staff = root.getChildNodes();
    ArrayList<Node> oldNodes = new ArrayList<>();

    for (int i = 0; i < staff.getLength(); i++) {
        oldNodes.add(staff.item(i));
    }

    //New root & NodeList
    Node rootNew = newDoc.getFirstChild();
    NodeList staffNew = rootNew.getChildNodes();
    ArrayList<Node> newNodes = new ArrayList<>();

    for (int i = 0; i < staffNew.getLength(); i++) {
        newNodes.add(staffNew.item(i));
    }
    //        * All extra nodes will be removed
    //        * All not maching "id's" will be replaced
    if (oldNodes.size() > newNodes.size()) {
        for (int i = 0; i < oldNodes.size(); i++) {
            if (i >= newNodes.size()) {
                root.removeChild(oldNodes.get(i));//remove extra old nodes
            } else if (!oldNodes.get(i).getAttributes().getNamedItem("id").getNodeValue()
                    .equals(newNodes.get(i).getAttributes().getNamedItem("id").getNodeValue())) {
                root.replaceChild(oldDoc.adoptNode(newNodes.get(i).cloneNode(true)), oldNodes.get(i)); //replace new node with old node
            } else {
                //System.out.println(i + "equal");
            }
        }
        //        * All not maching "id's" will be replaced
    } else if (oldNodes.size() == newNodes.size()) {
        for (int i = 0; i < oldNodes.size(); i++) {
            if (!oldNodes.get(i).getAttributes().getNamedItem("id").getNodeValue()
                    .equals(newNodes.get(i).getAttributes().getNamedItem("id").getNodeValue())) {
                root.replaceChild(oldDoc.adoptNode(newNodes.get(i).cloneNode(true)), oldNodes.get(i));// replace old with new node
            } else {
                //System.out.println(i + " equal");
            }
        }
        //        * All extra nodes will be apended
        //        * All not maching "id's" will be replaced
    } else if (oldNodes.size() < newNodes.size()) {
        for (int i = 0; i < newNodes.size(); ++i) {
            if (i >= oldNodes.size()) {
                root.appendChild(oldDoc.adoptNode(newNodes.get(i).cloneNode(true))); //append extra new node
            } else if (!newNodes.get(i).getAttributes().getNamedItem("id").getNodeValue()
                    .equals(oldNodes.get(i).getAttributes().getNamedItem("id").getNodeValue())) {
                root.replaceChild(oldDoc.adoptNode(newNodes.get(i).cloneNode(true)), oldNodes.get(i));//replace old with new node
            } else {
                //System.out.println(i + "equal");
            }
        }
    }
    writeDocument(oldDoc, pathXml);
}