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:jef.tools.XMLUtils.java

/**
 * ??Document?<br/>//from ww  w  .  ja  v a 2  s  . co  m
 * ???Document?
 * 
 * @param parent
 *            
 * @param nodes
 *            ???
 */
public static void appendChild(Node parent, Node... nodes) {
    Document doc = parent.getOwnerDocument();
    for (Node node : nodes) {
        if (node.getOwnerDocument() != doc) {
            parent.appendChild(doc.importNode(node, true));
        } else {
            parent.appendChild(node);
        }
    }
}

From source file:dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest.java

@Override
public void addRelations(String pid, String subject, String predicate, List<String> objects, boolean literal,
        String comment)/*from  ww  w  .  j a  v  a2  s  .co m*/
        throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException {
    if (comment == null || comment.isEmpty()) {
        comment = "No message supplied";
    }
    if (literal) {//cant handle literal yet
        for (String object : objects) {
            addRelation(pid, subject, predicate, object, literal, comment);
        }
    }
    if (objects.size() == 1) {//more efficient if only adding one relation
        addRelation(pid, subject, predicate, objects.get(0), literal, comment);
    }

    XPathSelector xpath = DOM.createXPathSelector("rdf", Constants.NAMESPACE_RDF);

    String datastream;
    if (subject == null || subject.isEmpty() || subject.equals(pid) || subject.equals("info:fedora/" + pid)) {
        subject = "info:fedora/" + pid;
        datastream = "RELS-EXT";
    } else {
        datastream = "RELS-INT";
    }

    String rels = getXMLDatastreamContents(pid, datastream, null);
    Document relsDoc = DOM.stringToDOM(rels, true);

    Node rdfDescriptionNode = xpath.selectNode(relsDoc,
            "/rdf:RDF/rdf:Description[@rdf:about='" + subject + "']");

    predicate = getAbsoluteURIAsString(predicate);

    String[] splits = predicate.split("#");

    for (String object : objects) {
        if (!object.startsWith("info:fedora/")) {
            object = "info:fedora/" + object;
        }

        Element relationsShipElement = relsDoc.createElementNS(splits[0] + "#", splits[1]);
        relationsShipElement.setAttributeNS(Constants.NAMESPACE_RDF, "rdf:resource", object);
        rdfDescriptionNode.appendChild(relationsShipElement);
    }

    byte[] bytes;
    try {
        bytes = DOM.domToString(relsDoc).getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        //TODO Not really a backend exception
        throw new BackendMethodFailedException("Failed to transform RELS-EXT", e);
    } catch (TransformerException e) {
        //TODO Not really a backend exception
        throw new BackendMethodFailedException("Failed to transform RELS-EXT", e);
    }
    modifyDatastreamByValue(pid, datastream, ChecksumType.MD5, null, bytes, null, "application/rdf+xml",
            comment, null);
}

From source file:XMLConfig.java

/** Create the node specified by the DOM path.
 * @param path DOM path//  www  .j  a  va  2  s. c  om
 * @param n node where the search should start, or null for the root
 * @param overwrite whether to overwrite (true) or add (false) -- only applies for last node!
 * @return the node that was created, or the parent node of the attribute if it was an attribute
 */
public Node createNode(String path, Node n, boolean overwrite) {
    if (isDelegated()) {
        return _parent.createNode(path, n, overwrite);
    }

    if (n == null) {
        n = _document;
    }
    while (path.indexOf('/') > -1) {
        Node child = null;
        String nodeName = path.substring(0, path.indexOf('/'));
        path = path.substring(path.indexOf('/') + 1);
        child = n.getFirstChild();
        while (child != null) {
            if (child.getNodeName().equals(nodeName)) {
                // found
                n = child;
                break;
            }
            child = child.getNextSibling();
        }
        if (child == null) {
            // not found
            child = _document.createElement(nodeName);
            n.appendChild(child);
            n = child;
        }
    }

    String nodeName;
    if (path.indexOf('.') > -1) {
        nodeName = path.substring(0, path.indexOf('.'));
    } else {
        if (path.length() == 0) {
            throw new XMLConfigException("Cannot set node with empty name");
        }
        nodeName = path;
    }
    Node child = null;
    if (nodeName.length() > 0) {
        if (overwrite) {
            child = n.getFirstChild();
            while (child != null) {
                if (child.getNodeName().equals(nodeName)) {
                    // found
                    n = child;
                    break;
                }
                child = child.getNextSibling();
            }
            if (child == null) {
                child = _document.createElement(nodeName);
                n.appendChild(child);
                n = child;
            }
        } else {
            child = _document.createElement(nodeName);
            n.appendChild(child);
            n = child;
        }
    }

    if (path.indexOf('.') > -1) {
        if (!(n instanceof Element)) {
            throw new XMLConfigException(
                    "Node " + n.getNodeName() + " should be an element so it can contain attributes");
        }
        return n;
    } else {
        if (overwrite) {
            child = n.getFirstChild();
            // remove all children
            while (child != null) {
                Node temp = child.getNextSibling();
                n.removeChild(child);
                child = temp;
            }
            return n;
        } else {
            return child;
        }
    }
}

From source file:ca.digitalface.jasperoo.JasperooOperationsImpl.java

/** {@inheritDoc} */
public void setup(String controllerPackage, String formats) {

    // Add all new dependencies to pom.xml
    projectOperations/* w  w w . j  av  a  2  s .c  o m*/
            .addDependency(new Dependency("org.springframework", "spring-context", "${spring.version}"));
    projectOperations.addDependency(new Dependency("jasperreports", "jasperreports", "3.5.3"));
    projectOperations.addDependency(new Dependency("org.apache.poi", "poi", "3.2-FINAL"));
    projectOperations.addDependency(new Dependency("org.springframework.roo.wrapping",
            "org.springframework.roo.wrapping.inflector", "0.7.0.0001"));

    String currentJasperooVersion = context.getBundleContext().getBundle().getHeaders().get("Bundle-Version")
            .toString();
    projectOperations
            .addDependency(new Dependency("ca.digitalface", "ca.digitalface.jasperoo", currentJasperooVersion));

    //add pluginNode to pom
    String pomPath = pathResolver.getIdentifier(Path.ROOT, "pom.xml");

    MutableFile mutablePomXml = null;
    Document pomDoc;
    try {
        if (fileManager.exists(pomPath)) {
            mutablePomXml = fileManager.updateFile(pomPath);
            pomDoc = XmlUtils.getDocumentBuilder().parse(mutablePomXml.getInputStream());
        } else {
            throw new IllegalStateException("Could not acquire " + pomPath);
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element pluginNode = new XmlElementBuilder("plugin", pomDoc)
            .addChild(new XmlElementBuilder("groupId", pomDoc).setText("org.codehaus.mojo").build())
            .addChild(new XmlElementBuilder("artifactId", pomDoc).setText("jasperreports-maven-plugin").build())
            .addChild(new XmlElementBuilder("configuration", pomDoc)
                    .addChild(new XmlElementBuilder("sourceDirectory", pomDoc)
                            .setText("src/main/webapp/WEB-INF/reports").build())
                    .addChild(new XmlElementBuilder("outputDirectory", pomDoc)
                            .setText("src/main/webapp/WEB-INF/reports").build())
                    .build())
            .addChild(new XmlElementBuilder("executions", pomDoc)
                    .addChild(new XmlElementBuilder("execution", pomDoc)
                            .addChild(new XmlElementBuilder("phase", pomDoc).setText("compile").build())
                            .addChild(new XmlElementBuilder("goals", pomDoc).addChild(
                                    new XmlElementBuilder("goal", pomDoc).setText("compile-reports").build())
                                    .build())
                            .build())
                    .build())
            .addChild(
                    new XmlElementBuilder("dependencies", pomDoc)
                            .addChild(new XmlElementBuilder("dependency", pomDoc)
                                    .addChild(new XmlElementBuilder("groupId", pomDoc).setText("jasperreports")
                                            .build())
                                    .addChild(new XmlElementBuilder("artifactId", pomDoc)
                                            .setText("jasperreports").build())
                                    .addChild(new XmlElementBuilder("version", pomDoc).setText("3.5.3").build())
                                    .build())
                            .addChild(new XmlElementBuilder("dependency", pomDoc)
                                    .addChild(new XmlElementBuilder("groupId", pomDoc)
                                            .setText("org.apache.log4j").build())
                                    .addChild(new XmlElementBuilder("artifactId", pomDoc)
                                            .setText("com.springsource.org.apache.log4j").build())
                                    .addChild(
                                            new XmlElementBuilder("version", pomDoc).setText("1.2.15").build())
                                    .build())
                            .build())
            .build();

    Node pluginsNode = pomDoc.getDocumentElement().getElementsByTagName("plugins").item(0);
    pluginsNode.appendChild(pluginNode);

    XmlUtils.writeXml(mutablePomXml.getOutputStream(), pomDoc);

    //add jasperReportsMultiFormatView to applicationContext
    String applicationContext = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES,
            "META-INF/spring/applicationContext.xml");

    MutableFile mutableConfigXml = null;
    Document webConfigDoc;
    try {
        if (fileManager.exists(applicationContext)) {
            mutableConfigXml = fileManager.updateFile(applicationContext);
            webConfigDoc = XmlUtils.getDocumentBuilder().parse(mutableConfigXml.getInputStream());
        } else {
            throw new IllegalStateException("Could not acquire " + applicationContext);
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element jasperReportsMultiFormatView = new XmlElementBuilder("bean", webConfigDoc)
            .addAttribute("id", "jasperReportsMultiFormatView")
            .addAttribute("name", "jasperReportsMultiFormatViewBean")
            .addAttribute("class", "ca.digitalface.jasperoo.reports.CustomJasperReportsMultiFormatView")
            .build();

    webConfigDoc.getDocumentElement().appendChild(jasperReportsMultiFormatView);

    XmlUtils.writeXml(mutableConfigXml.getOutputStream(), webConfigDoc);

    String webMVCConfig = pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES,
            "META-INF/spring/applicationContext.xml");

    MutableFile mutableWebMVCConfig = null;
    Document webMVCConfigDoc;
    try {
        if (fileManager.exists(webMVCConfig)) {
            mutableWebMVCConfig = fileManager.updateFile(webMVCConfig);
            webMVCConfigDoc = XmlUtils.getDocumentBuilder().parse(mutableWebMVCConfig.getInputStream());
        } else {
            throw new IllegalStateException("Could not acquire " + webMVCConfig);
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element viewResolver = new XmlElementBuilder("bean", webMVCConfigDoc).addAttribute("id", "viewResolver")
            .addAttribute("class", "org.springframework.web.servlet.view.ResourceBundleViewResolver")
            .addChild(new XmlElementBuilder("property", webMVCConfigDoc).addAttribute("name", "basename")
                    .addAttribute("value", "views").build())
            .build();

    webMVCConfigDoc.getDocumentElement().appendChild(viewResolver);

    XmlUtils.writeXml(mutableWebMVCConfig.getOutputStream(), webMVCConfigDoc);

    //create Report Controller
    shell.executeCommand("class --class ~.web.ReportController");

    //copy templates/files
    String classesFolder = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/classes");
    if (!fileManager.exists(classesFolder)) {
        fileManager.createDirectory(classesFolder);
    }

    String viewsProperties = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP,
            "WEB-INF/classes/views.properties");
    if (!fileManager.exists(viewsProperties)) {
        fileManager.createFile(viewsProperties);
    }

    String reportsFolder = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/reports");
    if (!fileManager.exists(reportsFolder)) {
        fileManager.createDirectory(reportsFolder);
    }

    copySetupFilesIntoProject(controllerPackage);

    setupListTagx();
    extend(formats);

}

From source file:com.fiorano.openesb.application.aps.ApplicationHeader.java

/**
 *  Returns the xml string equivalent of this object.
 *
 * @param document the input Document object
 * @return element node/*from w  ww  .  ja v a  2  s .  c om*/
 * @exception FioranoException if an error occurs while creating the element
 *      node.
 * @since Tifosi2.0
 */
Node toJXMLString(Document document) throws FioranoException {
    Node root0 = document.createElement("ApplicationHeader");

    ((Element) root0).setAttribute("isSubgraphable", "" + m_canBeSubGraphed);
    ((Element) root0).setAttribute("Scope", m_scope);

    Node node;

    node = XMLDmiUtil.getNodeObject("Name", m_appName, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("ApplicationGUID", m_appGUID, document);
    if (node != null)
        root0.appendChild(node);

    XMLDmiUtil.addVectorValues("Author", m_authorNames, document, root0);

    node = XMLDmiUtil.getNodeObject("CreationDate", m_creationDate, document);
    if (node != null)
        root0.appendChild(node);

    if (!StringUtils.isEmpty(m_iconName)) {
        node = XMLDmiUtil.getNodeObject("Icon", m_iconName, document);
        if (node != null)
            root0.appendChild(node);
    }
    Element child;

    if (m_version != null) {
        child = document.createElement("Version");
        child.setAttribute("isLocked", "" + m_isVersionLocked);

        Node pcData = document.createTextNode(m_version);

        child.appendChild(pcData);
        root0.appendChild(child);
    }

    //adding labels

    //create label object
    node = XMLDmiUtil.getNodeObject("Label", m_strProfile, document);
    if (node != null)
        root0.appendChild(node);

    //        node = XMLDmiUtil.getNodeObject("CompatibleWith", "" + m_compatibleWith, document);
    //        root0.appendChild(node);
    XMLDmiUtil.addVectorValues("CompatibleWith", m_compatibleWith, document, root0);

    node = XMLDmiUtil.getNodeObject("Category", m_category, document);
    if (node != null)
        root0.appendChild(node);

    if (m_maxInstLimit == -1 || m_maxInstLimit > 0) {
        child = document.createElement("MaximumInstances");

        Node pcData = document.createTextNode("" + m_maxInstLimit);

        child.appendChild(pcData);
        root0.appendChild(child);
    }
    if (!StringUtils.isEmpty(m_longDescription)) {
        node = XMLDmiUtil.getNodeObject("LongDescription", m_longDescription, document);
        if (node != null)
            root0.appendChild(node);
    }
    if (!StringUtils.isEmpty(m_shortDescription)) {
        node = XMLDmiUtil.getNodeObject("ShortDescription", m_shortDescription, document);
        if (node != null)
            root0.appendChild(node);
    }
    if (m_params != null && m_params.size() > 0) {
        Enumeration enums = m_params.elements();

        while (enums.hasMoreElements()) {
            Param param = (Param) enums.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue()))
                root0.appendChild(param.toJXMLString(document));
        }
    }

    //  Add the ApplicationHeader Node to it.
    if (m_appContext != null) {
        Node contextNode = m_appContext.toJXMLString(document);

        root0.appendChild(contextNode);
    }

    return root0;
}

From source file:com.icesoft.faces.context.DOMResponseWriter.java

/**
 * Copy the one generated stateSaving branch into all the marker (one per form)
 * node areas. <p>// ww  w  .java2s  . c  o m
 * This method shouldn't be called if state saving is not enabled
 */
public void copyStateNodesToMarkers() {

    Iterator i = markerNodes.iterator();
    while (i.hasNext()) {

        Node n = (Node) i.next();
        if ((n != null) && (savedJSFStateCursor != null)) {

            String nodeValue;

            // The View state consists of 4 sibling text nodes. We need to find the one
            // with the actual id, and preserve that ID in the PersistentFacesState object
            // so that server push operations can restore state as well.

            for (Node child = savedJSFStateCursor.getFirstChild(); child != null; child = child
                    .getNextSibling()) {

                nodeValue = child.getNodeValue();
                if (nodeValue != null && nodeValue.indexOf("j_id") > -1) {
                    PersistentFacesState.getInstance().setStateRestorationId(nodeValue);
                    if (log.isDebugEnabled()) {
                        log.debug("State id for server push state saving: " + nodeValue);
                    }
                }
                n.appendChild(child.cloneNode(true));
            }
        }
        //avoids unnecessary DOM diff due to normalization during
        //FastInfoset compression
        n.normalize();
    }
    markerNodes.clear();
}

From source file:jef.tools.XMLUtils.java

/**
 * ?//from w ww .j av a  2  s .c  o  m
 * 
 * @param node
 *            
 * @param comment
 *            
 * @return Comment
 */
public static Comment addComment(Node node, String comment) {
    Document doc = null;
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        doc = (Document) node;
    } else {
        doc = node.getOwnerDocument();
    }
    Comment e = doc.createComment(comment);
    node.appendChild(e);
    return e;
}

From source file:jef.tools.XMLUtils.java

/**
 * CDATA/* w w w  .  ja  v  a  2s.c om*/
 * 
 * @param node
 *            
 * @param data
 *            CDATA
 * @return ?CDATA
 */
public static CDATASection addCDataText(Node node, String data) {
    Document doc = null;
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        doc = (Document) node;
    } else {
        doc = node.getOwnerDocument();
    }
    CDATASection e = doc.createCDATASection(data);
    node.appendChild(e);
    return e;
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * modify scoEntryItem in scoEntryContent, move lom from scoEntryItem
 * /*  w w  w . j av  a 2s .  c o m*/
 * @param nodes
 * @throws Exception
 */
private static void walkingthrough(Node nodes, org.w3c.dom.Document document) throws Exception {

    changeScoEntry(nodes, document);

    int length = nodes.getChildNodes().getLength();
    for (int i = 0; i < length; i++) {
        Node node = nodes.getChildNodes().item(i);

        changeScoEntry(node, document);

        if (node.getNodeName().equals("scoEntryItem")) {
            // the lom children must linked to the parent child (scoEntry)
            int lengthlom = node.getChildNodes().getLength();
            for (int lom = 0; lom < lengthlom; lom++) {
                if (node.getChildNodes().item(lom) != null
                        && node.getChildNodes().item(lom).getNodeName().equals("lom:lom")) {
                    // clone the node..
                    Node cloneLom = node.getChildNodes().item(lom).cloneNode(true);
                    // first of all I remove it
                    Node lomnode = node.getChildNodes().item(lom);
                    Node father = lomnode.getParentNode();
                    Node grandf = father.getParentNode();
                    father.removeChild(lomnode);
                    // then I add it to the new parent..
                    grandf.insertBefore(cloneLom, father);
                }

                // for each dmRef open the DM and read the real data module
                // content to be show in the lesson
                if (node.getChildNodes().item(lom) != null
                        && node.getChildNodes().item(lom).getNodeName().equals("dmRef")) {
                    String filename = resourcepack + "\\" + gettingDmfilename(node.getChildNodes().item(lom))
                            + ".xml";
                    if (new File(filename).exists()) {
                        // if the data module is a scoContent will copy each
                        // dmref in the scoEntry
                        org.w3c.dom.Document dm41 = getDoc(new File(filename));

                        if (processXPathSingleNode("dmodule/content/scoContent", dm41) != null)
                            ;
                        {
                            NodeList dmre = processXPath("/dmodule/content/scoContent/trainingStep/dmRef",
                                    dm41);
                            Node father = node.getChildNodes().item(lom).getParentNode();
                            father.removeChild(node.getChildNodes().item(lom));
                            // remove the reference to Scocontent and
                            // replace it with the dm inside
                            for (int nodi = 0; nodi < dmre.getLength(); nodi++) {
                                Node cloneref = dmre.item(nodi).cloneNode(true);
                                document.adoptNode(cloneref);
                                father.appendChild(cloneref);
                            }

                        }
                    }

                }

            }

            // rename scoEntryItem in scoEntry
            node = changeNodename(node, document, "scoEntryContent");
        }
        walkingthrough(node, document);
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * ?//from   w  ww . j av a  2s . com
 * 
 * @param node
 *            
 * @param tagName
 *            ??
 * @param nodeText
 *            
 * @return Element
 */
public static Element addElement(Node node, String tagName, String... nodeText) {
    Document doc = null;
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        doc = (Document) node;
    } else {
        doc = node.getOwnerDocument();
    }
    Element e = doc.createElement(tagName);
    node.appendChild(e);
    if (nodeText.length == 1) {
        setText(e, nodeText[0]);
    } else if (nodeText.length > 1) {
        setText(e, StringUtils.join(nodeText, '\n'));
    }
    return e;
}