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:nl.nn.adapterframework.extensions.bis.BisWrapperPipe.java

private String prepareReply(String rawReply, String messageHeader, String result, boolean resultInPayload)
        throws DomBuilderException, IOException, TransformerException {
    ArrayList messages = new ArrayList();
    if (messageHeader != null) {
        messages.add(messageHeader);/*from  w w  w . jav  a 2 s. c o m*/
    }
    messages.add(rawReply);

    String payload = null;
    if (result == null) {
        payload = Misc.listToString(messages);
    } else {
        if (resultInPayload) {
            String message = Misc.listToString(messages);
            Document messageDoc = XmlUtils.buildDomDocument(message);
            Node messageRootNode = messageDoc.getFirstChild();
            Node resultNode = messageDoc.importNode(XmlUtils.buildNode(result), true);
            messageRootNode.appendChild(resultNode);
            payload = XmlUtils.nodeToString(messageDoc);
        } else {
            messages.add(result);
            payload = Misc.listToString(messages);
        }
    }
    return payload;
}

From source file:nl.vumc.trait.oc.main.ImportODM.java

@Override
public void runCmd() throws ParserConfigurationException, DatatypeConfigurationException, ODMException,
        OCConnectorException, SAXException, IOException {
    OCWebServices connector = OCWebServices.getInstance(connectInfo, debug, false);
    InputStream reader;//from ww w. j a v a  2s .com
    if (file.equals("-")) {
        reader = System.in;
    } else {
        reader = new FileInputStream(file);
    }
    ClinicalODMResolver odm = new ClinicalODMResolver(documentBuilder.parse(reader), connector, true);
    odm.resolveOdmDocument();
    Document odmDoc = odm.getOdm();
    Node odmNode = odm.getOdm().getFirstChild();
    // bulk load -- chop up into ClinicaDatas...
    NodeList clinicalDatas = odm.xPath(odmNode, "//ClinicalData");
    for (int i = 0; i < clinicalDatas.getLength(); ++i) {
        odmNode.removeChild(clinicalDatas.item(i));
    }
    for (int i = 0; i < clinicalDatas.getLength(); ++i) {
        odmNode.appendChild(clinicalDatas.item(i));
        logger.debug("============================ setOdm start =================");
        odm.setOdm(odmDoc); // important!
        logger.debug("Current ODM:\n" + odm.extraClean().toString());
        logger.debug("============================ setOdm end ===================");
        connector.importODM(odm.extraClean().toString());
        odmNode.removeChild(clinicalDatas.item(i));
    }
}

From source file:org.adl.sequencer.ADLSeqUtilities.java

/**
 * Initializes one activity (<code>SeqActivity</code>) that will be added to
 * an activity tree.//w ww .  j av  a 2s .  com
 * 
 * @param iNode   A node from the DOM tree of an element containing
 *                sequencing information.
 * 
 * @param iColl   The collection of reusable sequencing information.
 * 
 * @return An initialized activity (<code>SeqActivity</code>), or <code>
 *         null</code> if there was an error initializing the activity.
 */
private static SeqActivity buildActivityNode(Node iNode, Node iColl) {

    if (_Debug) {
        System.out.println("  :: ADLSeqUtilities  --> BEGIN - " + "buildActivityNode");
    }

    SeqActivity act = new SeqActivity();

    boolean error = false;

    String tempVal = null;

    // Set the activity's ID -- this is a required attribute
    act.setID(ADLSeqUtilities.getAttribute(iNode, "identifier"));

    // Get the activity's resource ID -- if it exsits
    tempVal = ADLSeqUtilities.getAttribute(iNode, "identifierref");
    if (tempVal != null) {
        if (!isEmpty(tempVal)) {
            act.setResourceID(tempVal);
        }
    }

    // Check if the activity is visible
    tempVal = ADLSeqUtilities.getAttribute(iNode, "isvisible");
    if (tempVal != null) {
        if (!isEmpty(tempVal)) {
            act.setIsVisible((Boolean.valueOf(tempVal)).booleanValue());
        }
    }

    // Get the children elements of this activity 
    NodeList children = iNode.getChildNodes();

    // Initalize this activity from the information in the DOM  
    for (int i = 0; i < children.getLength(); i++) {
        Node curNode = children.item(i);

        // Check to see if this is an element node.
        if (curNode.getNodeType() == Node.ELEMENT_NODE) {
            if (curNode.getLocalName().equals("item")) {

                if (_Debug) {
                    System.out.println("  ::--> Found an <item> element");
                }

                // Initialize the nested activity
                SeqActivity nestedAct = ADLSeqUtilities.buildActivityNode(curNode, iColl);

                // Make sure this activity was created successfully
                if (nestedAct != null) {
                    if (_Debug) {
                        System.out.println("  ::--> Adding child");
                    }

                    act.addChild(nestedAct);

                } else {
                    error = true;
                }
            } else if (curNode.getLocalName().equals("title")) {

                if (_Debug) {
                    System.out.println("  ::--> Found the <title> element");
                }

                act.setTitle(ADLSeqUtilities.getElementText(curNode, null));
            } else if (curNode.getLocalName().equals("sequencing")) {

                if (_Debug) {
                    System.out.println("  ::--> Found the <sequencing> element");
                }

                Node seqInfo = curNode;

                // Check to see if the sequencing information is referenced in 
                // the <sequencingCollection>
                tempVal = ADLSeqUtilities.getAttribute(curNode, "IDRef");
                if (tempVal != null) {
                    // Combine local and global sequencing information
                    // Get the referenced Global sequencing information
                    String search = "imsss:sequencing[@ID='" + tempVal + "']";

                    if (_Debug) {
                        System.out.println("  ::--> Looking for XPATH --> " + search);
                    }

                    // Use the referenced set of sequencing information
                    Node seqGlobal = null;

                    XPathFactory pathFactory = XPathFactory.newInstance();
                    XPath path = pathFactory.newXPath();

                    try {
                        seqGlobal = (Node) path.evaluate(search, iColl, XPathConstants.NODE);
                        //XPathAPI.selectSingleNode(iColl, search);
                    } catch (Exception e) {
                        if (_Debug) {
                            System.out.println("  ::--> ERROR : In transform");
                            e.printStackTrace();
                        }
                    }

                    if (seqGlobal != null) {
                        if (_Debug) {
                            System.out.println("  ::--> FOUND");
                        }
                    } else {
                        if (_Debug) {
                            System.out.println("  ::--> ERROR: Not Found");
                        }

                        seqInfo = null;
                        error = true;
                    }

                    if (!error) {

                        // Clone the global node
                        seqInfo = seqGlobal.cloneNode(true);

                        // Loop through the local sequencing element
                        NodeList seqChildren = curNode.getChildNodes();
                        for (int j = 0; j < seqChildren.getLength(); j++) {

                            Node curChild = seqChildren.item(j);

                            // Check to see if this is an element node.
                            if (curChild.getNodeType() == Node.ELEMENT_NODE) {
                                if (_Debug) {
                                    System.out.println("  ::--> Local definition");
                                    System.out.println("  ::-->   " + j);
                                    System.out.println("  ::-->  <" + curChild.getLocalName() + ">");
                                }

                                // Add this to the global sequencing info
                                try {
                                    seqInfo.appendChild(curChild);
                                } catch (org.w3c.dom.DOMException e) {
                                    if (_Debug) {
                                        System.out.println("  ::--> ERROR: ");
                                        e.printStackTrace();
                                    }

                                    error = true;
                                    seqInfo = null;
                                }
                            }
                        }
                    }
                }

                // If we have an node to look at, extract its sequencing info
                if (seqInfo != null) {
                    // Record this activity's sequencing XML fragment
                    //                  XMLSerializer serializer = new XMLSerializer();

                    // -+- TODO -+-
                    //                  serializer.setNewLine("CR-LF");
                    //                  act.setXMLFragment(serializer.writeToString(seqInfo));

                    // Extract the sequencing information for this activity
                    error = !ADLSeqUtilities.extractSeqInfo(seqInfo, act);

                    if (_Debug) {
                        System.out.println("  ::--> Extracted Sequencing Info");
                    }
                }
            }
        }
    }

    // Make sure this activity either has an associated resource or children
    if (act.getResourceID() == null && !act.hasChildren(true)) {
        // This is not a vaild activity -- ignore it
        error = true;
    }

    // If the activity failed to initialize, clear the variable
    if (error) {
        act = null;
    }

    if (_Debug) {
        System.out.println("  ::--> error == " + error);
        System.out.println("  :: ADLSeqUtilities  --> END   - " + "buildActivityNode");
    }

    return act;
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

@SuppressWarnings("unchecked")
public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode,
        final Node newInstanceNode,

        final HashMap<String, String> schemaNamespaces) {
    final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode);
    prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);
    final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode);
    instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);

    for (final String prefix : schemaNamespaces.keySet()) {
        prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
        instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
    }//from   ww w .  j  ava2  s .  com

    // Evaluate non-recursive XPaths for all prototype elements at this level
    final Iterator<Pointer> it = prototypeContext.iteratePointers("*");
    while (it.hasNext()) {
        final Pointer p = it.next();
        Element proto = (Element) p.getNode();
        String path = p.asPath();
        // check if this is a prototype element with the attribute set
        boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")
                && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true");

        // We shouldn't locate a repeatable child with a fixed path
        if (isPrototype) {
            path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path);
            }
        }

        Document newInstanceDocument = newInstanceNode.getOwnerDocument();

        // Locate the corresponding nodes in the instance document
        List<Node> l = (List<Node>) instanceContext.selectNodes(path);

        // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node
        if (l.isEmpty()) {
            if (!isPrototype) {
                LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));

                // Clone the prototype node and all its children
                Element clone = (Element) proto.cloneNode(true);
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }
            }
        } else {
            // Otherwise, append the matches from the old instance document in order
            for (Node old : l) {
                Element oldEl = (Element) old;

                // Copy the old instance element rather than cloning it, so we don't copy over attributes
                Element clone = null;
                String nSUri = oldEl.getNamespaceURI();
                if (nSUri == null) {
                    clone = newInstanceDocument.createElement(oldEl.getTagName());
                } else {
                    clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName());
                }
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }

                // Copy over child text if this is not a complex type
                boolean isEmpty = true;
                for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) {
                    if (n instanceof Text) {
                        clone.appendChild(newInstanceDocument.importNode(n, false));
                        isEmpty = false;
                    } else if (n instanceof Element) {
                        break;
                    }
                }

                // Populate the nil attribute. It may be true or false
                if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) {
                    clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty));
                }

                // Copy over attributes present in the prototype
                NamedNodeMap attributes = proto.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attribute = (Attr) attributes.item(i);
                    String localName = attribute.getLocalName();
                    if (localName == null) {
                        String name = attribute.getName();
                        if (oldEl.hasAttribute(name)) {
                            clone.setAttributeNode(
                                    (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false));
                        } else {
                            LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                    + attribute.getNodeName() + " to "
                                    + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                            clone.setAttributeNode((Attr) attribute.cloneNode(false));
                        }
                    } else {
                        String namespace = attribute.getNamespaceURI();
                        if (!((!isEmpty
                                && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS)
                                        && localName.equals("nil"))
                                || (namespace.equals(NamespaceService.ALFRESCO_URI)
                                        && localName.equals("prototype"))))) {
                            if (oldEl.hasAttributeNS(namespace, localName)) {
                                clone.setAttributeNodeNS((Attr) newInstanceDocument
                                        .importNode(oldEl.getAttributeNodeNS(namespace, localName), false));
                            } else {
                                LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                        + attribute.getNodeName() + " to "
                                        + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                                clone.setAttributeNodeNS((Attr) attribute.cloneNode(false));
                            }
                        }
                    }
                }

                // recurse on children
                rebuildInstance(proto, oldEl, clone, schemaNamespaces);
            }
        }

        // Now add in a new copy of the prototype
        if (isPrototype) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));
            }
            newInstanceNode.appendChild(proto.cloneNode(true));
        }
    }
}

From source file:org.alternativevision.gpx.GPXParser.java

private void addGenericWaypointToGPXNode(String tagName, Waypoint wpt, Node gpxNode, Document doc) {
    Node wptNode = doc.createElement(tagName);
    NamedNodeMap attrs = wptNode.getAttributes();
    if (wpt.getLatitude() != null) {
        Node latNode = doc.createAttribute(GPXConstants.LAT_ATTR);
        latNode.setNodeValue(wpt.getLatitude().toString());
        attrs.setNamedItem(latNode);//ww w  .  j  a v a 2s. c  o m
    }
    if (wpt.getLongitude() != null) {
        Node longNode = doc.createAttribute(GPXConstants.LON_ATTR);
        longNode.setNodeValue(wpt.getLongitude().toString());
        attrs.setNamedItem(longNode);
    }
    if (wpt.getElevation() != null) {
        Node node = doc.createElement(GPXConstants.ELE_NODE);
        node.appendChild(doc.createTextNode(wpt.getElevation().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getTime() != null) {
        Node node = doc.createElement(GPXConstants.TIME_NODE);
        node.appendChild(doc.createTextNode(sdfZ.format(wpt.getTime())));
        wptNode.appendChild(node);
    }
    if (wpt.getMagneticDeclination() != null) {
        Node node = doc.createElement(GPXConstants.MAGVAR_NODE);
        node.appendChild(doc.createTextNode(wpt.getMagneticDeclination().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getGeoidHeight() != null) {
        Node node = doc.createElement(GPXConstants.GEOIDHEIGHT_NODE);
        node.appendChild(doc.createTextNode(wpt.getGeoidHeight().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getName() != null) {
        Node node = doc.createElement(GPXConstants.NAME_NODE);
        node.appendChild(doc.createTextNode(wpt.getName()));
        wptNode.appendChild(node);
    }
    if (wpt.getComment() != null) {
        Node node = doc.createElement(GPXConstants.CMT_NODE);
        node.appendChild(doc.createTextNode(wpt.getComment()));
        wptNode.appendChild(node);
    }
    if (wpt.getDescription() != null) {
        Node node = doc.createElement(GPXConstants.DESC_NODE);
        node.appendChild(doc.createTextNode(wpt.getDescription()));
        wptNode.appendChild(node);
    }
    if (wpt.getSrc() != null) {
        Node node = doc.createElement(GPXConstants.SRC_NODE);
        node.appendChild(doc.createTextNode(wpt.getSrc()));
        wptNode.appendChild(node);
    }
    //TODO: write link node
    if (wpt.getSym() != null) {
        Node node = doc.createElement(GPXConstants.SYM_NODE);
        node.appendChild(doc.createTextNode(wpt.getSym()));
        wptNode.appendChild(node);
    }
    if (wpt.getType() != null) {
        Node node = doc.createElement(GPXConstants.TYPE_NODE);
        node.appendChild(doc.createTextNode(wpt.getType()));
        wptNode.appendChild(node);
    }
    if (wpt.getFix() != null) {
        Node node = doc.createElement(GPXConstants.FIX_NODE);
        node.appendChild(doc.createTextNode(wpt.getFix().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getSat() != null) {
        Node node = doc.createElement(GPXConstants.SAT_NODE);
        node.appendChild(doc.createTextNode(wpt.getSat().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getHdop() != null) {
        Node node = doc.createElement(GPXConstants.HDOP_NODE);
        node.appendChild(doc.createTextNode(wpt.getHdop().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getVdop() != null) {
        Node node = doc.createElement(GPXConstants.VDOP_NODE);
        node.appendChild(doc.createTextNode(wpt.getVdop().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getPdop() != null) {
        Node node = doc.createElement(GPXConstants.PDOP_NODE);
        node.appendChild(doc.createTextNode(wpt.getPdop().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getAgeOfGPSData() != null) {
        Node node = doc.createElement(GPXConstants.AGEOFGPSDATA_NODE);
        node.appendChild(doc.createTextNode(wpt.getAgeOfGPSData().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getDgpsid() != null) {
        Node node = doc.createElement(GPXConstants.DGPSID_NODE);
        node.appendChild(doc.createTextNode(wpt.getDgpsid().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getExtensionsParsed() > 0) {
        Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
        Iterator<IExtensionParser> it = extensionParsers.iterator();
        while (it.hasNext()) {
            it.next().writeWaypointExtensionData(node, wpt, doc);
        }
        wptNode.appendChild(node);
    }
    gpxNode.appendChild(wptNode);
}

From source file:org.alternativevision.gpx.GPXParser.java

private void addTrackToGPXNode(Track trk, Node gpxNode, Document doc) {
    Node trkNode = doc.createElement(GPXConstants.TRK_NODE);

    if (trk.getName() != null) {
        Node node = doc.createElement(GPXConstants.NAME_NODE);
        node.appendChild(doc.createTextNode(trk.getName()));
        trkNode.appendChild(node);//from  w ww.  j  a  va 2s . co  m
    }
    if (trk.getComment() != null) {
        Node node = doc.createElement(GPXConstants.CMT_NODE);
        node.appendChild(doc.createTextNode(trk.getComment()));
        trkNode.appendChild(node);
    }
    if (trk.getDescription() != null) {
        Node node = doc.createElement(GPXConstants.DESC_NODE);
        node.appendChild(doc.createTextNode(trk.getDescription()));
        trkNode.appendChild(node);
    }
    if (trk.getSrc() != null) {
        Node node = doc.createElement(GPXConstants.SRC_NODE);
        node.appendChild(doc.createTextNode(trk.getSrc()));
        trkNode.appendChild(node);
    }
    //TODO: write link
    if (trk.getNumber() != null) {
        Node node = doc.createElement(GPXConstants.NUMBER_NODE);
        node.appendChild(doc.createTextNode(trk.getNumber().toString()));
        trkNode.appendChild(node);
    }
    if (trk.getType() != null) {
        Node node = doc.createElement(GPXConstants.TYPE_NODE);
        node.appendChild(doc.createTextNode(trk.getType()));
        trkNode.appendChild(node);
    }
    if (trk.getExtensionsParsed() > 0) {
        Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
        Iterator<IExtensionParser> it = extensionParsers.iterator();
        while (it.hasNext()) {
            it.next().writeTrackExtensionData(node, trk, doc);
        }
        trkNode.appendChild(node);
    }
    if (trk.getTrackPoints() != null) {
        Node trksegNode = doc.createElement(GPXConstants.TRKSEG_NODE);
        Iterator<Waypoint> it = trk.getTrackPoints().iterator();
        while (it.hasNext()) {
            addGenericWaypointToGPXNode(GPXConstants.TRKPT_NODE, it.next(), trksegNode, doc);
        }
        trkNode.appendChild(trksegNode);
    }
    gpxNode.appendChild(trkNode);
}

From source file:org.alternativevision.gpx.GPXParser.java

private void addRouteToGPXNode(Route rte, Node gpxNode, Document doc) {
    Node trkNode = doc.createElement(GPXConstants.TRK_NODE);

    if (rte.getName() != null) {
        Node node = doc.createElement(GPXConstants.NAME_NODE);
        node.appendChild(doc.createTextNode(rte.getName()));
        trkNode.appendChild(node);//from  w w w  .  j  a  v a  2s  .  c o m
    }
    if (rte.getComment() != null) {
        Node node = doc.createElement(GPXConstants.CMT_NODE);
        node.appendChild(doc.createTextNode(rte.getComment()));
        trkNode.appendChild(node);
    }
    if (rte.getDescription() != null) {
        Node node = doc.createElement(GPXConstants.DESC_NODE);
        node.appendChild(doc.createTextNode(rte.getDescription()));
        trkNode.appendChild(node);
    }
    if (rte.getSrc() != null) {
        Node node = doc.createElement(GPXConstants.SRC_NODE);
        node.appendChild(doc.createTextNode(rte.getSrc()));
        trkNode.appendChild(node);
    }
    //TODO: write link
    if (rte.getNumber() != null) {
        Node node = doc.createElement(GPXConstants.NUMBER_NODE);
        node.appendChild(doc.createTextNode(rte.getNumber().toString()));
        trkNode.appendChild(node);
    }
    if (rte.getType() != null) {
        Node node = doc.createElement(GPXConstants.TYPE_NODE);
        node.appendChild(doc.createTextNode(rte.getType()));
        trkNode.appendChild(node);
    }
    if (rte.getExtensionsParsed() > 0) {
        Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
        Iterator<IExtensionParser> it = extensionParsers.iterator();
        while (it.hasNext()) {
            it.next().writeRouteExtensionData(node, rte, doc);
        }
        trkNode.appendChild(node);
    }
    if (rte.getRoutePoints() != null) {
        Iterator<Waypoint> it = rte.getRoutePoints().iterator();
        while (it.hasNext()) {
            addGenericWaypointToGPXNode(GPXConstants.RTEPT_NODE, it.next(), trkNode, doc);
        }
    }
    gpxNode.appendChild(trkNode);
}

From source file:org.alternativevision.gpx.GPXParser.java

private void addBasicGPXInfoToNode(GPX gpx, Node gpxNode, Document doc) {
    NamedNodeMap attrs = gpxNode.getAttributes();
    if (gpx.getVersion() != null) {
        Node verNode = doc.createAttribute(GPXConstants.VERSION_ATTR);
        verNode.setNodeValue(gpx.getVersion());
        attrs.setNamedItem(verNode);/*from  ww  w .  j av a2 s.c  om*/
    }
    if (gpx.getCreator() != null) {
        Node creatorNode = doc.createAttribute(GPXConstants.CREATOR_ATTR);
        creatorNode.setNodeValue(gpx.getCreator());
        attrs.setNamedItem(creatorNode);
    }

    if (gpx.getExtensionsParsed() > 0) {
        Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
        Iterator<IExtensionParser> it = extensionParsers.iterator();
        while (it.hasNext()) {
            it.next().writeGPXExtensionData(node, gpx, doc);
        }
        gpxNode.appendChild(node);
    }
}

From source file:org.ambraproject.service.article.FetchArticleServiceImpl.java

/**
 * Decorates the citation elements of the XML DOM with extra information from the citedArticle table in the DB. An
 * extraCitationInfo element is appended to each citation element.  It will contain between one and two attributes
 * with the extra info: citedArticleID, the DB primary key, and doi, the DOI string, if it exists.
 *
 * @param doc           DOM of the XML//from w  w  w .j a v a2  s . co  m
 * @param citedArticles List of CitedArticle persistent objects
 * @return modified DOM
 * @throws ApplicationException
 */
private Document addExtraCitationInfo(Document doc, List<CitedArticle> citedArticles)
        throws ApplicationException {
    if (citedArticles.isEmpty()) {
        return doc; // This happens in some unit tests.
    }
    try {
        NodeList referenceList = getReferenceNodes(doc);

        // If sortOrder on citedArticle has duplicate value, you will get below error.Ideally it should not happen
        // but since sortOrder is not unique it may be possible to update that field from backend to have duplicate value
        // Now index is on sortOrder(article.hbm.xml), index will be only on one of those of duplicate value and
        // hence citedArticle will have less count then the xml.
        if (referenceList.getLength() != citedArticles.size()) {
            throw new ApplicationException(String.format("Article has %d citedArticles but %d references",
                    citedArticles.size(), referenceList.getLength()));
        }
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression citationExpr = xpath
                .compile("./citation|./nlm-citation|./element-citation|./mixed-citation");
        for (int i = 0; i < referenceList.getLength(); i++) {
            Node referenceNode = referenceList.item(i);
            Node citationNode = (Node) citationExpr.evaluate(referenceNode, XPathConstants.NODE);
            CitedArticle citedArticle = citedArticles.get(i);
            if (citationNode != null && "journal".equals(getCitationType(citationNode))
                    && citedArticleIsValid(citedArticle)) {
                Element extraInfo = doc.createElement("extraCitationInfo");
                setExtraCitationInfo(extraInfo, citedArticle);
                citationNode.appendChild(extraInfo);
            }
        }
    } catch (XPathExpressionException xpee) {
        throw new ApplicationException(xpee);
    }

    return doc;
}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog220.java

protected void updateKnoxTopology() throws AmbariException {
    AmbariManagementController ambariManagementController = injector
            .getInstance(AmbariManagementController.class);
    for (final Cluster cluster : getCheckedClusterMap(ambariManagementController.getClusters()).values()) {
        Config topology = cluster.getDesiredConfigByType(TOPOLOGY_CONFIG);
        if (topology != null) {
            String content = topology.getProperties().get(CONTENT_PROPERTY);
            if (content != null) {
                Document topologyXml = convertStringToDocument(content);
                if (topologyXml != null) {
                    Element root = topologyXml.getDocumentElement();
                    if (root != null) {
                        NodeList providerNodes = root.getElementsByTagName("provider");
                        boolean authorizationProviderExists = false;
                        try {
                            for (int i = 0; i < providerNodes.getLength(); i++) {
                                Node providerNode = providerNodes.item(i);
                                NodeList childNodes = providerNode.getChildNodes();
                                for (int k = 0; k < childNodes.getLength(); k++) {
                                    Node child = childNodes.item(k);
                                    child.normalize();
                                    String childTextContent = child.getTextContent();
                                    if (childTextContent != null
                                            && childTextContent.toLowerCase().equals("authorization")) {
                                        authorizationProviderExists = true;
                                        break;
                                    }/*  w ww . j a  va2 s .  c o  m*/
                                }
                                if (authorizationProviderExists) {
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LOG.error(
                                    "Error occurred during check 'authorization' provider already exists in topology."
                                            + e);
                            return;
                        }
                        if (!authorizationProviderExists) {
                            NodeList nodeList = root.getElementsByTagName("gateway");
                            if (nodeList != null && nodeList.getLength() > 0) {
                                boolean rangerPluginEnabled = isConfigEnabled(cluster,
                                        AbstractUpgradeCatalog.CONFIGURATION_TYPE_RANGER_KNOX_PLUGIN_PROPERTIES,
                                        AbstractUpgradeCatalog.PROPERTY_RANGER_KNOX_PLUGIN_ENABLED);

                                Node gatewayNode = nodeList.item(0);
                                Element newProvider = topologyXml.createElement("provider");

                                Element role = topologyXml.createElement("role");
                                role.appendChild(topologyXml.createTextNode("authorization"));
                                newProvider.appendChild(role);

                                Element name = topologyXml.createElement("name");
                                if (rangerPluginEnabled) {
                                    name.appendChild(topologyXml.createTextNode("XASecurePDPKnox"));
                                } else {
                                    name.appendChild(topologyXml.createTextNode("AclsAuthz"));
                                }
                                newProvider.appendChild(name);

                                Element enabled = topologyXml.createElement("enabled");
                                enabled.appendChild(topologyXml.createTextNode("true"));
                                newProvider.appendChild(enabled);

                                gatewayNode.appendChild(newProvider);

                                DOMSource topologyDomSource = new DOMSource(root);
                                StringWriter writer = new StringWriter();
                                try {
                                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                                    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                                            "5");
                                    transformer.transform(topologyDomSource, new StreamResult(writer));
                                } catch (TransformerConfigurationException e) {
                                    e.printStackTrace();
                                    LOG.error(
                                            "Unable to create transformer instance, to convert Document(XML) to String. "
                                                    + e);
                                    return;
                                } catch (TransformerException e) {
                                    e.printStackTrace();
                                    LOG.error("Unable to transform Document(XML) to StringWriter. " + e);
                                    return;
                                }

                                content = writer.toString();
                                Map<String, String> updates = Collections.singletonMap(CONTENT_PROPERTY,
                                        content);
                                updateConfigurationPropertiesForCluster(cluster, TOPOLOGY_CONFIG, updates, true,
                                        false);
                            }
                        }
                    }
                }
            }
        }
    }
}