Example usage for org.w3c.dom Document getFirstChild

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

Introduction

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

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * replace elements in originalDom with modifiedDom according to listed
 * xPaths, if the originalDom has elements not listed in the xPath, it will
 * be kept untouched. in the HashMap<String, String> xPathPairs, the key is
 * the path in the source xml, and the value is the xpath for the final
 * note*: the if the xpath has attributes, it's not going to work... need to
 * do a custom implementation when that use case happened...
 * //from   ww w.  j  a v a2  s  .  c o m
 * @param originalDom
 * @param modifiedDom
 * @param xPaths
 * @return
 * @throws XPathExpressionException
 */
private Document replaceByXPaths(final Document originalDom, final Document modifiedDom,
        Map<String, String> xPathPairs) throws XPathExpressionException {

    Document finalDom = originalDom;
    Element finalDomRoot = (Element) finalDom.getFirstChild();

    Element lastChild = null;

    for (Entry<String, String> xPathPair : xPathPairs.entrySet()) {

        /**
         * basically, this is to copy the element specified in srcXPath, and
         * replace/add it to the position pointed by destXPath...
         */
        String srcXPath = xPathPair.getKey();

        logger.debug("srcXPath: " + srcXPath);

        String destXPath = xPathPair.getValue();

        logger.debug("destXPath: " + destXPath);

        XPath xPath = getXPathInstance();
        // find all the nodes specified by destXPath in the originalDom, and
        // delete them all
        NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET));

        int el = existingNodeList.getLength();

        logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath);

        for (int i = 0; i < el; i++) {
            Node c = existingNodeList.item(i);
            // remove this node from its parent...
            c.getParentNode().removeChild(c);
        }

        // create the node structure first. and return the last child of the
        // path... the right most node...
        lastChild = createElementStructureByPath(finalDomRoot, destXPath);

        List<String> nodeNameList = getNodeList(destXPath);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);

        xPath.reset();
        // find all the nodes specified by srcXPath in the modifiedDom
        NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET));

        int l = nodeList.getLength();

        logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            // the name of the last node in srcXPath might not be the same
            // as the name of the last node in destXPath
            Element lastElement = finalDom.createElement(lastNodeName);

            // NodeList currentNodeChildNodes = currentNode.getChildNodes();
            // int s = currentNodeChildNodes.getLength();
            // for(int j = 0; j < s; j++){
            // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j),
            // true));
            // }
            if (currentNode.hasAttributes()) {
                NamedNodeMap attributes = currentNode.getAttributes();

                for (int j = 0; j < attributes.getLength(); j++) {
                    String attribute_name = attributes.item(j).getNodeName();
                    String attribute_value = attributes.item(j).getNodeValue();

                    lastElement.setAttribute(attribute_name, attribute_value);
                }
            }

            while (currentNode.hasChildNodes()) {
                Node kid = currentNode.getFirstChild();
                currentNode.removeChild(kid);
                lastElement.appendChild(finalDom.importNode(kid, true));
            }

            lastChild.appendChild(lastElement);

        }

    }

    return finalDom;

}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * If the xpath identifies multiple elements, it will only add to the first
 * element, if there is no such parent element, it will just add it...
 */// w  w  w  .j  a  v  a2  s  .c o  m
@Override
public synchronized Map<String, Object> addSubElementToElementIdentifiedByXPath(final String parentElementXPath,
        final String originalXml, final String elementXml, boolean generateId)
        throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(parentElementXPath);
    Assert.hasText(originalXml);
    Assert.hasText(elementXml);

    Document originalDom = parse(originalXml);

    Document finalDom = originalDom;

    Document elementDom = parse(elementXml);

    Element elementRoot = (Element) elementDom.getFirstChild();

    XPath xPath = getXPathInstance();

    // find all the nodes specified by xPathString in the finalDom, and
    // delete them all
    NodeList existingNodeList = (NodeList) (xPath.evaluate(parentElementXPath, finalDom,
            XPathConstants.NODESET));

    int el = existingNodeList.getLength();

    String id = "";

    Element currentNode = finalDom.getDocumentElement();
    if (el == 0) { // doesn't exist, create the parent...
        List<String> nodeList = getNodeList(parentElementXPath);

        // remove first one, should be protocol
        nodeList.remove(0);

        int c = 0;
        for (String n : nodeList) {
            NodeList cur = currentNode.getElementsByTagName(n);
            String curName = currentNode.getNodeName();
            c = cur.getLength();

            if (c > 1) {
                throw new RuntimeException("illeagl xml structure; find " + c + " elements with name " + n);
            }

            if (c == 0) {
                logger.debug("empty node...; " + n + " doesn't exist under " + curName);

                Element newN = finalDom.createElement(n);
                currentNode.appendChild(newN);

                currentNode = newN;
                continue;
            }

            currentNode = (Element) cur.item(0);

        }
    } else if (el > 0) {
        currentNode = (Element) existingNodeList.item(0); // only the first
        // one
    }

    if (generateId) {
        // using jdk UUID as uuid generator...
        id = UUID.randomUUID().toString();

        elementRoot.setAttribute("id", id);
    }

    currentNode.appendChild(finalDom.importNode(elementRoot, true));
    /*
     * for(int i = 0; i < el; i++){ Node c = existingNodeList.item(i);
     * 
     * if (generateId) { // using jdk UUID as uuid generator... String id =
     * UUID.randomUUID().toString();
     * 
     * elementRoot.setAttribute("id", id); }
     * 
     * c.appendChild(finalDom.importNode(elementRoot, true));
     * 
     * }
     */
    logger.trace(DomUtils.elementToString(finalDom));

    Map<String, Object> resultMap = new HashMap<String, Object>(3);
    resultMap.put("finalXml", DomUtils.elementToString(finalDom));
    resultMap.put("elementXml", DomUtils.elementToString(elementDom));
    resultMap.put("elementId", id);
    return resultMap;

}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

private Document replaceIfExistingByXPaths(final Document originalDom, final Document modifiedDom,
        Map<String, String> xPathPairs) throws XPathExpressionException {

    Document finalDom = originalDom;
    Element finalDomRoot = (Element) finalDom.getFirstChild();

    //Element modifiedDomRoot = (Element) modifiedDom.getFirstChild();

    Element lastChild = null;//www .  jav  a 2  s  .  c o m

    for (Entry<String, String> xPathPair : xPathPairs.entrySet()) {

        /**
         * basically, this is to copy the element specified in srcXPath, and
         * replace/add it to the position pointed by destXPath...
         */
        String srcXPath = xPathPair.getKey();

        logger.debug("srcXPath: " + srcXPath);

        String destXPath = xPathPair.getValue();

        logger.debug("destXPath: " + destXPath);

        XPath xPath = getXPathInstance();
        // find all the nodes specified by destXPath in the originalDom, and
        // delete them all
        NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET));

        xPath.reset();
        // find all the nodes specified by srcXPath in the modifiedDom
        NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET));

        int el = existingNodeList.getLength();

        logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath);

        int l = nodeList.getLength();

        logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath);

        for (int i = 0; i < el; i++) {
            Node c = existingNodeList.item(i);

            //xPathExpression = xPath.compile(srcXPath);
            //NodeList srcNodeLst = (NodeList) (xPathExpression.evaluate(
            //modifiedDom, XPathConstants.NODESET));
            //NodeList srcNodeLst = modifiedDomRoot.getElementsByTagName(c.getNodeName());

            if (l > 0) {
                // remove this node from its parent...

                c.getParentNode().removeChild(c);
                logger.debug("Node:" + c.getNodeName() + " is removed!");
            }

        }

        // create the node structure first. and return the last child of the
        // path... the right most node...
        lastChild = createElementStructureByPath(finalDomRoot, destXPath);

        List<String> nodeNameList = getNodeList(destXPath);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            // the name of the last node in srcXPath might not be the same
            // as the name of the last node in destXPath
            Element lastElement = finalDom.createElement(lastNodeName);

            // NodeList currentNodeChildNodes = currentNode.getChildNodes();
            // int s = currentNodeChildNodes.getLength();
            // for(int j = 0; j < s; j++){
            // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j),
            // true));
            // }
            if (currentNode.hasAttributes()) {
                NamedNodeMap attributes = currentNode.getAttributes();

                for (int j = 0; j < attributes.getLength(); j++) {
                    String attribute_name = attributes.item(j).getNodeName();
                    String attribute_value = attributes.item(j).getNodeValue();

                    lastElement.setAttribute(attribute_name, attribute_value);
                }
            }

            while (currentNode.hasChildNodes()) {
                Node kid = currentNode.getFirstChild();
                currentNode.removeChild(kid);
                lastElement.appendChild(finalDom.importNode(kid, true));
            }

            lastChild.appendChild(lastElement);

        }

    }

    return finalDom;

}

From source file:com.janoz.usenet.searchers.impl.NzbsOrgConnectorImpl.java

private List<NZB> fetchFeed(Collection<NameValuePair> params) throws SearchException, DOMException {
    THROTTLER.throttle();//www . j av  a 2  s . co m
    Document document = null;
    try {
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.addAll(params);
        qparams.add(new BasicNameValuePair("dl", "1"));
        URI uri = getUri("rss.php", qparams);
        synchronized (builderSemaphore) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            int attempts = RETRY_ATTEMPTS;
            boolean retry;
            do
                try {
                    retry = false;
                    document = builder.parse(uri.toString());
                } catch (IOException ioe) {
                    if (attempts == 0
                            || !ioe.getMessage().startsWith("Server returned HTTP response code: 503")) {
                        throw ioe;
                    } else {
                        attempts--;
                        retry = true;
                        THROTTLER.throttleBig();
                    }
                }
            while (retry);
        }
    } catch (IOException ioe) {
        throw new SearchException("Error connecting to Nzbs.org.", ioe);
    } catch (SAXException se) {
        throw new SearchException("Error parsing rss from Nzbs.org.", se);
    } catch (ParserConfigurationException pce) {
        throw new SearchException("Error configuring XML parser.", pce);
    } catch (URISyntaxException e) {
        throw new SearchException("Error parsing URI.", e);
    }
    Node rss = document.getFirstChild();
    if (!"rss".equalsIgnoreCase(rss.getNodeName())) {
        throw new SearchException("Result was not RSS but " + rss.getNodeName());
    }
    Node channel = rss.getFirstChild();
    while (channel != null && "#text".equals(channel.getNodeName())) {
        channel = channel.getNextSibling();
    }
    NodeList list = channel.getChildNodes();
    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.CANADA);
    List<NZB> result = new ArrayList<NZB>();
    UrlBasedSupplier supplier = new UrlBasedSupplier();
    supplier.setThrottler(THROTTLER);
    for (int i = 0; i < list.getLength(); i++) {
        Node n = list.item(i);
        if ("item".equals(n.getNodeName())) {
            LazyNZB nzb = new LazyNZB("tmpName", supplier);
            try {
                for (int j = 0; j < n.getChildNodes().getLength(); j++) {
                    Node n2 = n.getChildNodes().item(j);
                    if ("title".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setName(n2.getTextContent());
                        nzb.setFilename(Util.saveFileName(n2.getTextContent()) + ".nzb");
                    }
                    if ("pubdate".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setPostDate(df.parse(n2.getTextContent()));
                    }
                    if ("link".equalsIgnoreCase(n2.getNodeName())) {
                        nzb.setUrl(n2.getTextContent());
                    }
                }
                result.add(nzb);
            } catch (ParseException e) {
                LOG.info("Skipping " + nzb.getName() + " because of date error.", e);
            }
        }
    }
    THROTTLER.setThrottleForNextAction();
    return result;
}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java

/**
 * {@inheritDoc}//  w w  w . j  a v  a  2s. c  o m
 * <p>
 * Update the entry ID could change entry type because category entry starts
 * with 'c_' prefix, item entry starts with 'i_' prefix, so to change a
 * category entry to item entry you have to set a new ID that starts with
 * 'i_'.
 */
public void updateEntry(JavaSymbolName pageId, JavaSymbolName nid, String label, String messageCode,
        String destination, String roles, Boolean hidden, boolean writeProps) {
    Document document = getMenuDocument();

    // Properties to be writen
    Map<String, String> properties = new HashMap<String, String>();

    // make the root element of the menu the one with the menu identifier
    // allowing for different decorations of menu
    Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP, (Element) document.getFirstChild());

    if (!rootElement.getNodeName().equals(GVNIX_MENU)) {
        throw new IllegalArgumentException(INVALID_XML);
    }

    // check for existence of menu category by looking for the identifier
    // provided
    Element pageElement = XmlUtils.findFirstElement(ID_EXP.concat(pageId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(pageElement, "Menu entry '".concat(pageId.getSymbolName()).concat(NOT_FOUND));

    if (nid != null) {
        pageElement.setAttribute("id", nid.getSymbolName());

        // TODO: if Element has children, children IDs should be
        // recalculated too
        // TODO: label code should change too (as addMenuItem does)
    }

    if (StringUtils.isNotBlank(label)) {
        String itemLabelCode = pageElement.getAttribute(LABEL_CODE);
        properties.put(itemLabelCode, label);
    }

    if (writeProps) {
        propFileOperations.addProperties(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
                "/WEB-INF/i18n/application.properties", properties, true, true);
    }

    if (StringUtils.isNotBlank(messageCode)) {
        pageElement.setAttribute(MESSAGE_CODE, messageCode);
    }

    if (StringUtils.isNotBlank(destination)) {
        pageElement.setAttribute(URL, destination);
    }

    if (StringUtils.isNotBlank(roles)) {
        pageElement.setAttribute("roles", roles);
    }

    if (hidden != null) {
        pageElement.setAttribute(HIDDEN, hidden.toString());
    }

    writeXMLConfigIfNeeded(document);
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * inList para force to create a <list></list> wrap the result
 *//* ww  w . j a  va 2  s  . c  om*/
@Override
public synchronized String listElementsByPaths(Set<String> paths, final String xmlData, boolean inList,
        boolean includeChildren) throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(xmlData);

    Document originalDom = parse(xmlData);

    Document finalDom = documentBuilder.newDocument();

    Element root = null;
    if (inList) {
        root = finalDom.createElement("list");
    } else {
        root = finalDom.createElement(originalDom.getFirstChild().getNodeName());
    }

    // Element lastChild = null;

    for (String path : paths) {

        // create the node structure first. and return the last child of the
        // path... the right most node...
        // lastChild = createElementStructureByPath(root, path);
        XPath xPath = getXPathInstance();
        NodeList nodeList = (NodeList) (xPath.evaluate(path, originalDom, XPathConstants.NODESET));

        int l = nodeList.getLength();
        logger.trace("find: " + l);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            root.appendChild(finalDom.importNode(currentNode, includeChildren));

        }

    }

    return DomUtils.elementToString(root);

}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

@Override
public String replaceOrAddNodeValueByPath(final String path, final String xmlData, final String nodeValue)
        throws SAXException, IOException, XPathExpressionException {

    Document finalDom = parse(xmlData);

    XPath xPath = getXPathInstance();
    NodeList nodeList = (NodeList) (xPath.evaluate(path, finalDom, XPathConstants.NODESET));

    int l = nodeList.getLength();

    if (l == 0) {
        Element elementStructure = createElementStructureByPath((Element) finalDom.getFirstChild(), path);

        List<String> nodeNameList = getNodeList(path);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);
        Element lastElement = finalDom.createElement(lastNodeName);
        lastElement.setTextContent(nodeValue);

        elementStructure.appendChild(lastElement);

    } else {//from   ww  w.  j  a v  a  2 s . c o  m
        Element currentElement = null;
        for (int i = 0; i < l; i++) {
            if (nodeList.item(i) == null)
                continue;
            currentElement = (Element) nodeList.item(i);

            currentElement.setTextContent(nodeValue);
        }
    }

    return DomUtils.elementToString(finalDom.getFirstChild());
}

From source file:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java

private InputStream addLabelToAmdSec(InputStream is, MetsContext metsContext) throws MetsExportException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {//ww  w  .  j  a  v a 2s  .c o  m
        MetsUtils.copyStream(is, bos);
        bos.close();
    } catch (IOException ex) {
        throw new MetsExportException("Unable to copy stream", false, ex);
    }
    Document TECHDoc = MetsUtils.getDocumentFromBytes(bos.toByteArray());
    Element element = (Element) TECHDoc.getFirstChild();
    element.setAttribute("LABEL", mets.getLabel1());
    element.setAttribute("TYPE", mets.getTYPE());
    DOMSource domSource = new DOMSource(TECHDoc);
    StringWriter xmlAsWriter = new StringWriter();
    StreamResult result = new StreamResult(xmlAsWriter);
    try {
        TransformerFactory.newInstance().newTransformer().transform(domSource, result);
        InputStream resultIS = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8"));
        is.close();
        return resultIS;
    } catch (Exception ex) {
        throw new MetsExportException("Unable to transform Tech metadata to XML", false, ex);
    }
}

From source file:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java

/**
 *
 * Parses an ALTO stream and returns a list of internal elements
 *
 * @param document//from   www  . j a  v a 2 s . c  o  m
 * @return
 */
private List<IntPartInfo> parseAltoInfo(Document document) {
    List<IntPartInfo> intPartInfoList = new ArrayList<IntPartInfo>();
    Node partElement = document.getFirstChild();
    NodeList partsList = partElement.getChildNodes();
    for (int a = 0; a < partsList.getLength(); a++) {
        Node node = partsList.item(a);
        if ((node instanceof Element) && (node.hasAttributes())) {
            String type = node.getAttributes().getNamedItem("type").getNodeValue();
            String alto = node.getAttributes().getNamedItem("alto").getNodeValue();
            String begin = node.getAttributes().getNamedItem("begin").getNodeValue();
            String order = node.getAttributes().getNamedItem("order").getNodeValue();
            IntPartInfo info = new IntPartInfo(type, alto.substring(0, alto.indexOf("/")), begin, order);
            intPartInfoList.add(info);
        }
    }
    return intPartInfoList;
}

From source file:com.rapid.core.Application.java

public static Application load(ServletContext servletContext, File file, boolean initialise)
        throws JAXBException, JSONException, InstantiationException, IllegalAccessException,
        ClassNotFoundException, IllegalArgumentException, SecurityException, InvocationTargetException,
        NoSuchMethodException, IOException, ParserConfigurationException, SAXException,
        TransformerFactoryConfigurationError, TransformerException, RapidLoadingException,
        XPathExpressionException {

    // get the logger
    Logger logger = (Logger) servletContext.getAttribute("logger");

    // trace log that we're about to load a page
    logger.trace("Loading application from " + file);

    // open the xml file into a document
    Document appDocument = XML.openDocument(file);

    // specify the version as -1
    int xmlVersion = -1;

    // look for a version node
    Node xmlVersionNode = XML.getChildElement(appDocument.getFirstChild(), "XMLVersion");

    // if we got one update the version
    if (xmlVersionNode != null)
        xmlVersion = Integer.parseInt(xmlVersionNode.getTextContent());

    // if the version of this xml isn't the same as this class we have some work to do!
    if (xmlVersion != XML_VERSION) {

        // get the page name
        String name = XML.getChildElementValue(appDocument.getFirstChild(), "name");

        // log the difference
        logger.debug("Application " + name + " with xml version " + xmlVersion + ", current xml version is "
                + XML_VERSION);//from  w  w  w.j a  v  a 2 s.  co m

        //
        // Here we would have code to update from known versions of the file to the current version
        //

        // check whether there was a version node in the file to start with
        if (xmlVersionNode == null) {
            // create the version node
            xmlVersionNode = appDocument.createElement("XMLVersion");
            // add it to the root of the document
            appDocument.getFirstChild().appendChild(xmlVersionNode);
        }

        // set the xml to the latest version
        xmlVersionNode.setTextContent(Integer.toString(XML_VERSION));

        // save it
        XML.saveDocument(appDocument, file);

        logger.debug("Updated " + name + " application xml version to " + XML_VERSION);

    }

    // get the unmarshaller 
    Unmarshaller unmarshaller = RapidHttpServlet.getUnmarshaller();

    try {

        // unmarshall the application
        Application application = (Application) unmarshaller.unmarshal(file);

        // if we don't want pages loaded or resource generation skip this
        if (initialise) {

            // load the pages (actually clears down the pages collection and reloads the headers)
            application.getPages().loadpages(servletContext);

            // initialise the application and create the resources
            application.initialise(servletContext, true);

        }

        // log that the application was loaded
        logger.info("Loaded application " + application.getName() + "/" + application.getVersion()
                + (initialise ? "" : " (no initialisation)"));

        return application;

    } catch (JAXBException ex) {

        throw new RapidLoadingException("Error loading application file at " + file, ex);

    }

}