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:com.portfolio.data.provider.MysqlAdminProvider.java

private void getLinearXml(String portfolioUuid, String rootuuid, Node portfolio, boolean withChildren,
        String withChildrenOfXsiType, int userId, int groupId)
        throws SQLException, SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
    DocumentBuilder parse = newInstance.newDocumentBuilder();

    /*/*from www . j a v a  2  s . c  o m*/
    long time0 = 0;
    long time1 = 0;
    long time2 = 0;
    long time3 = 0;
    //*/

    //      time0 = System.currentTimeMillis();

    ResultSet resNode = getMysqlStructure(portfolioUuid, userId, groupId);

    //     time1= System.currentTimeMillis();

    Document document = portfolio.getOwnerDocument();

    HashMap<String, Node> resolve = new HashMap<String, Node>();
    /// Node -> parent
    ArrayList<Object[]> entries = new ArrayList<Object[]>();

    processQuery(resNode, resolve, entries, document, parse);
    resNode.close();

    resNode = getSharedMysqlStructure(portfolioUuid, userId, groupId);
    if (resNode != null) {
        processQuery(resNode, resolve, entries, document, parse);
        resNode.close();
    }

    //     time2 = System.currentTimeMillis();

    /// Reconstruct tree
    for (int i = 0; i < entries.size(); ++i) {
        Object[] obj = entries.get(i);
        Node node = (Node) obj[0];
        String childsId = (String) obj[1];

        String[] tok = childsId.split(",");
        for (int j = 0; j < tok.length; ++j) {
            String id = tok[j];
            Node child = resolve.get(id);
            if (child != null)
                node.appendChild(child);

        }
    }

    //     time3 = System.currentTimeMillis();

    Node rootNode = resolve.get(rootuuid);
    portfolio.appendChild(rootNode);

    /*
    System.out.println("---- Portfolio ---");
    System.out.println("Time query: "+(time1-time0));
    System.out.println("Parsing: "+(time2-time1));
    System.out.println("Reconstruction: "+(time3-time2));
    System.out.println("------------------");
    //*/
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getNode(MimeType outMimeType, String nodeUuid, boolean withChildren, int userId, int groupId,
        String label) throws SQLException, TransformerFactoryConfigurationError, ParserConfigurationException,
        UnsupportedEncodingException, DOMException, SAXException, IOException, TransformerException {
    StringBuffer nodexml = new StringBuffer();

    NodeRight nodeRight = credential.getNodeRight(userId, groupId, nodeUuid, label);

    if (!nodeRight.read)
        return nodexml;

    if (outMimeType.getSubType().equals("xml")) {
        ResultSet result = getNodePerLevel(nodeUuid, userId, groupId);

        /// Prparation du XML que l'on va renvoyer
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document document = null;
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
        document.setXmlStandalone(true);

        HashMap<String, Node> resolve = new HashMap<String, Node>();
        /// Node -> parent
        ArrayList<Object[]> entries = new ArrayList<Object[]>();

        processQuery(result, resolve, entries, document, documentBuilder);
        result.close();//from   w  w w . j  a  va  2 s.co m

        for (int i = 0; i < entries.size(); ++i) {
            Object[] obj = entries.get(i);
            Node node = (Node) obj[0];
            String childsId = (String) obj[1];

            String[] tok = childsId.split(",");
            for (int j = 0; j < tok.length; ++j) {
                String id = tok[j];
                Node child = resolve.get(id);
                if (child != null)
                    node.appendChild(child);
            }
        }

        Node root = resolve.get(nodeUuid);
        Node node = document.createElement("node");
        node.appendChild(root);
        document.appendChild(node);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));
        nodexml.append(stw.toString());

        //        StringBuffer sb = getNodeXmlOutput(nodeUuid,withChildren,null,userId, groupId, label,true);
        //          StringBuffer sb = getLinearNodeXml(nodeUuid,withChildren,null,userId, groupId, label,true);

        //        sb.insert(0, "<node>");
        //        sb.append("</node>");
        return nodexml;
    } else if (outMimeType.getSubType().equals("json"))
        return "{" + getNodeJsonOutput(nodeUuid, withChildren, null, userId, groupId, label, true) + "}";
    else
        return null;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

private void getLinearXml(String portfolioUuid, String rootuuid, Node portfolio, boolean withChildren,
        String withChildrenOfXsiType, int userId, int groupId, String role)
        throws SQLException, SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
    DocumentBuilder parse = newInstance.newDocumentBuilder();

    /*//from ww  w  .  jav  a  2  s.c  o  m
    long time0 = 0;
    long time1 = 0;
    long time2 = 0;
    long time3 = 0;
    //*/

    //      time0 = System.currentTimeMillis();

    ResultSet resNode = getMysqlStructure(portfolioUuid, userId, groupId);

    //     time1= System.currentTimeMillis();

    Document document = portfolio.getOwnerDocument();

    HashMap<String, Node> resolve = new HashMap<String, Node>();
    /// Node -> parent
    ArrayList<Object[]> entries = new ArrayList<Object[]>();

    processQuery(resNode, resolve, entries, document, parse, role);
    resNode.close();

    resNode = getSharedMysqlStructure(portfolioUuid, userId, groupId);
    if (resNode != null) {
        processQuery(resNode, resolve, entries, document, parse, role);
        resNode.close();
    }

    //      time2 = System.currentTimeMillis();

    /// Reconstruct tree, using children list (node_children_uuid)
    for (int i = 0; i < entries.size(); ++i) {
        Object[] obj = entries.get(i);
        Node node = (Node) obj[0];
        String childsId = (String) obj[1];

        String[] tok = childsId.split(",");
        for (int j = 0; j < tok.length; ++j) {
            String id = tok[j];
            Node child = resolve.get(id);
            if (child != null)
                node.appendChild(child);

        }
    }

    //      time3 = System.currentTimeMillis();

    Node rootNode = resolve.get(rootuuid);
    if (rootNode != null)
        portfolio.appendChild(rootNode);

    /*
    System.out.println("---- Portfolio ---");
    System.out.println("Time query: "+(time1-time0));
    System.out.println("Parsing: "+(time2-time1));
    System.out.println("Reconstruction: "+(time3-time2));
    System.out.println("------------------");
    //*/
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object getNode(MimeType outMimeType, String nodeUuid, boolean withChildren, int userId, int groupId,
        String label) throws SQLException, TransformerFactoryConfigurationError, ParserConfigurationException,
        UnsupportedEncodingException, DOMException, SAXException, IOException, TransformerException {
    StringBuffer nodexml = new StringBuffer();

    NodeRight nodeRight = credential.getNodeRight(userId, groupId, nodeUuid, label);

    if (!nodeRight.read) {
        userId = credential.getPublicUid();
        /// Vrifie les droits avec le compte publique (dernire chance)
        credential.getPublicRight(userId, 123, nodeUuid, "dummy");

        if (!nodeRight.read)
            return nodexml;
    }/*from  ww w  .j av a 2  s  .  c  o m*/

    if (outMimeType.getSubType().equals("xml")) {
        ResultSet result = getNodePerLevel(nodeUuid, userId, nodeRight.groupId);

        /// Prparation du XML que l'on va renvoyer
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document document = null;
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
        document.setXmlStandalone(true);

        HashMap<String, Node> resolve = new HashMap<String, Node>();
        /// Node -> parent
        ArrayList<Object[]> entries = new ArrayList<Object[]>();

        processQuery(result, resolve, entries, document, documentBuilder, nodeRight.groupLabel);
        result.close();

        for (int i = 0; i < entries.size(); ++i) {
            Object[] obj = entries.get(i);
            Node node = (Node) obj[0];
            String childsId = (String) obj[1];

            String[] tok = childsId.split(",");
            for (int j = 0; j < tok.length; ++j) {
                String id = tok[j];
                Node child = resolve.get(id);
                if (child != null)
                    node.appendChild(child);

            }
        }

        Node root = resolve.get(nodeUuid);
        Node node = document.createElement("node");
        node.appendChild(root);
        document.appendChild(node);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));
        nodexml.append(stw.toString());

        //        StringBuffer sb = getNodeXmlOutput(nodeUuid,withChildren,null,userId, groupId, label,true);
        //          StringBuffer sb = getLinearNodeXml(nodeUuid,withChildren,null,userId, groupId, label,true);

        //        sb.insert(0, "<node>");
        //        sb.append("</node>");
        return nodexml;
    } else if (outMimeType.getSubType().equals("json"))
        return "{" + getNodeJsonOutput(nodeUuid, withChildren, null, userId, groupId, label, true) + "}";
    else
        return null;
}

From source file:net.sourceforge.pmd.lang.ast.AbstractNode.java

protected void appendElement(final org.w3c.dom.Node parentNode) {
    final DocumentNavigator docNav = new DocumentNavigator();
    Document ownerDocument = parentNode.getOwnerDocument();
    if (ownerDocument == null) {
        // If the parentNode is a Document itself, it's ownerDocument is
        // null/* w  ww  .j  a  va 2  s  .  c  o m*/
        ownerDocument = (Document) parentNode;
    }
    final String elementName = docNav.getElementName(this);
    final Element element = ownerDocument.createElement(elementName);
    parentNode.appendChild(element);
    for (final Iterator<Attribute> iter = docNav.getAttributeAxisIterator(this); iter.hasNext();) {
        final Attribute attr = iter.next();
        element.setAttribute(attr.getName(), attr.getStringValue());
    }
    for (final Iterator<Node> iter = docNav.getChildAxisIterator(this); iter.hasNext();) {
        final AbstractNode child = (AbstractNode) iter.next();
        child.appendElement(element);
    }
}

From source file:net.wastl.webmail.xml.XMLCommon.java

/**
 * Add a node as child to the node selected by the given xpath expression.
 *//*from  www  . j  av  a 2s. c o  m*/
public static void addNodeXPath(Element root, String path, Node child) {
    try {
        Node n = XPathAPI.selectSingleNode(root, path);
        n.appendChild(child);
    } catch (Exception ex) {
        log.error("Failed to add nod for path '" + path + "'.  Continuing, but should not.", ex);
        // TODO:  Throw here.
    }
}

From source file:net.wastl.webmail.xml.XMLData.java

/**
 * Add a node as child to the node selected by the given xpath expression.
 *//*from ww w  .  j a v a2  s.  co  m*/
public void addNodeXPath(String path, Node child) {
    try {
        Node n = xpath_api.selectSingleNode(data, path);
        n.appendChild(child);
        invalidateCache();
    } catch (Exception ex) {
        // We get here SOMETIMES if there is no Sent folder to add
        // sent mail to.
        log.error("XPath threw for path '" + path + "', or adding to it.  " + "'" + path
                + " is probably just missing though.  " + "Continuing without adding the child");
        // Log the Exception if there is more going on than missing Sent
        // folder.
        //XMLCommon.dumpXML(log, path, root);
        //TODO: throw
    }
}

From source file:net.wesjd.overcastmappacker.xml.DocumentHandler.java

public Element add(Class<? extends ParentXMLModule> parentClass, Class<? extends XMLModule> moduleClass,
        String moduleValue, ContinuingMap<String, String> attributeMapping) {
    final ParentXMLModule parentModule = getParentModule(parentClass, moduleClass);
    final XMLModule module = XMLModule.of(moduleClass);

    final Element moduleElement = document.createElement(module.getTag());
    moduleElement.setTextContent(moduleValue);

    Node parentNode = document.getElementsByTagName(parentModule.getTag()).item(0);
    if (parentNode == null) {
        set(null, parentModule.getClass());
        parentNode = document.getElementsByTagName(parentModule.getTag()).item(0);
    }//  www  . j ava 2 s .  com
    parentNode.appendChild(moduleElement);

    handleAttributes(module, moduleElement, attributeMapping);

    return moduleElement;
}

From source file:netinf.common.communication.MessageEncoderXML.java

private static void appendElementWithValue(Document xml, Node node, String name, String value) {
    Element element = xml.createElement(name);
    element.setTextContent(value);/*from  w w w.java 2s.  c o  m*/
    node.appendChild(element);
}

From source file:nl.b3p.viewer.stripes.SldActionBean.java

private void addFilterToExistingSld() throws Exception {
    Filter f = CQL.toFilter(filter);

    f = (Filter) f.accept(new ChangeMatchCase(false), null);

    if (featureTypeName == null) {
        featureTypeName = layer;/*from w w  w  .jav  a2 s .  co m*/
    }
    FeatureTypeConstraint ftc = sldFactory.createFeatureTypeConstraint(featureTypeName, f, new Extent[] {});

    if (newSld == null) {

        SLDTransformer sldTransformer = new SLDTransformer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        sldTransformer.transform(ftc, bos);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document sldXmlDoc = db.parse(new ByteArrayInputStream(sldXml));

        Document ftcDoc = db.parse(new ByteArrayInputStream(bos.toByteArray()));

        String sldVersion = sldXmlDoc.getDocumentElement().getAttribute("version");
        if ("1.1.0".equals(sldVersion)) {
            // replace sld:FeatureTypeName element generated by GeoTools
            // by se:FeatureTypeName
            NodeList sldFTNs = ftcDoc.getElementsByTagNameNS(NS_SLD, "FeatureTypeName");
            if (sldFTNs.getLength() == 1) {
                Node sldFTN = sldFTNs.item(0);
                Node seFTN = ftcDoc.createElementNS(NS_SE, "FeatureTypeName");
                seFTN.setTextContent(sldFTN.getTextContent());
                sldFTN.getParentNode().replaceChild(seFTN, sldFTN);
            }
        }

        // Ignore namespaces to tackle both SLD 1.0.0 and SLD 1.1.0
        // Add constraint to all NamedLayers, not only to the layer specified
        // in layers parameter

        NodeList namedLayers = sldXmlDoc.getElementsByTagNameNS(NS_SLD, "NamedLayer");
        for (int i = 0; i < namedLayers.getLength(); i++) {
            Node namedLayer = namedLayers.item(i);

            // Search where to insert the FeatureTypeConstraint from our ftcDoc

            // Insert LayerFeatureConstraints after sld:Name, se:Name or se:Description
            // and before sld:NamedStyle or sld:UserStyle so search backwards.
            // If we find an existing LayerFeatureConstraints, use that
            NodeList childs = namedLayer.getChildNodes();
            Node insertBefore = null;
            Node layerFeatureConstraints = null;
            int j = childs.getLength() - 1;
            do {
                Node child = childs.item(j);

                if ("LayerFeatureConstraints".equals(child.getLocalName())) {
                    layerFeatureConstraints = child;
                    break;
                }
                if ("Description".equals(child.getLocalName()) || "Name".equals(child.getLocalName())) {
                    break;
                }
                insertBefore = child;
                j--;
            } while (j >= 0);
            Node featureTypeConstraint = sldXmlDoc.adoptNode(ftcDoc.getDocumentElement().cloneNode(true));
            if (layerFeatureConstraints == null) {
                layerFeatureConstraints = sldXmlDoc.createElementNS(NS_SLD, "LayerFeatureConstraints");
                layerFeatureConstraints.appendChild(featureTypeConstraint);
                namedLayer.insertBefore(layerFeatureConstraints, insertBefore);
            } else {
                layerFeatureConstraints.appendChild(featureTypeConstraint);
            }
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        DOMSource source = new DOMSource(sldXmlDoc);
        bos = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(bos);
        t.transform(source, result);
        sldXml = bos.toByteArray();
    }
}