Example usage for org.w3c.dom Node getNextSibling

List of usage examples for org.w3c.dom Node getNextSibling

Introduction

In this page you can find the example usage for org.w3c.dom Node getNextSibling.

Prototype

public Node getNextSibling();

Source Link

Document

The node immediately following this node.

Usage

From source file:org.nuxeo.runtime.deployment.preprocessor.PackZip.java

protected void moveNonEjbsToLib(File wd) throws ParserConfigurationException, SAXException, IOException {
    File file = new File(wd, "META-INF" + File.separator + "application.xml");
    if (!file.isFile()) {
        log.error("You should run this tool from a preprocessed nuxeo.ear folder");
    }//from   ww  w . j  av a 2  s  . c  om
    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    FileInputStream in = new FileInputStream(file);
    Document doc = docBuilder.parse(in);
    Element root = doc.getDocumentElement();
    NodeList list = root.getElementsByTagName("module");
    Collection<String> paths = new ArrayList<String>();
    for (int i = 0; i < list.getLength(); i++) {
        Element el = (Element) list.item(i);
        Node n = el.getFirstChild();
        while (n != null) {
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                Element mtype = ((Element) n);
                String type = n.getNodeName().toLowerCase();
                if (!"web".equals(type)) {
                    String path = mtype.getTextContent().trim();
                    paths.add(path);
                }
            }
            n = n.getNextSibling();
        }
    }

    File ejbs = new File(wd, "tmp-ejbs");
    ejbs.mkdirs();
    for (String path : paths) {
        log.info("Move EAR module " + path + " to " + ejbs.getName());
        File f = new File(wd, path);
        if (f.getName().endsWith(".txt")) {
            continue;
        }
        FileUtils.moveToDirectory(f, ejbs, false);
    }
    File lib = new File(wd, "lib");
    File[] files = new File(wd, "bundles").listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.getName().endsWith(".txt")) {
                continue;
            }
            log.info("Move POJO bundle " + f.getName() + " to lib");
            FileUtils.moveToDirectory(f, lib, false);
        }
    }
    File bundles = new File(wd, "bundles");
    files = ejbs.listFiles();
    if (files != null) {
        for (File f : files) {
            if (f.getName().endsWith(".txt")) {
                continue;
            }
            log.info("Move back EAR module " + f.getName() + " to bundles");
            FileUtils.moveToDirectory(f, bundles, false);
        }
    }
}

From source file:org.nuxeo.runtime.jboss.deployer.structure.DeploymentStructureReader.java

public DeploymentStructure read(VirtualFile vhome, InputStream in) throws Exception {
    DeploymentStructure md = new DeploymentStructure(vhome);
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.parse(in);
    Element root = doc.getDocumentElement();
    Attr attr = root.getAttributeNode("children");
    if (attr != null) {
        String[] ar = Utils.split(attr.getValue().trim(), ':', true);
        md.setChildren(ar);//w  ww.j a  v  a 2 s  . c o m
    }
    attr = root.getAttributeNode("bundles");
    if (attr != null) {
        String[] ar = Utils.split(attr.getValue().trim(), ':', true);
        md.setBundles(ar);
    }
    Node node = root.getFirstChild();
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            String name = node.getNodeName().toLowerCase();
            if ("context".equalsIgnoreCase(name)) {
                readContext((Element) node, md);
            } else if ("properties".equals(name)) {
                readProperties(vhome, (Element) node, md);
            } else if ("preprocessor".equals(name)) {
                readPreprocessor((Element) node, md);
            }
        }
        node = node.getNextSibling();
    }
    return md;
}

From source file:org.nuxeo.runtime.jboss.deployer.structure.DeploymentStructureReader.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void readProperties(VirtualFile file, Element element, DeploymentStructure md) throws Exception {
    Attr attr = element.getAttributeNode("src");
    if (attr != null) {
        VirtualFile vf = file.getChild(attr.getValue().trim());
        if (vf != null) {
            InputStream in = vf.openStream();
            try {
                Properties props = new Properties();
                props.load(in);/*from w w  w  . j a  v  a 2s  . c  o  m*/
                md.getProperties().putAll((Map) props);
            } finally {
                in.close();
            }
        } else {
            log.warn(
                    "Properties file referenced in nuxeo-structure.xml could not be found: " + attr.getValue());
        }
    }
    // load contents too if any
    Node child = element.getFirstChild();
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            if (child.getNodeName().equalsIgnoreCase("property")) {
                Element echild = (Element) child;
                attr = echild.getAttributeNode("name");
                if (attr == null) {
                    log.warn(
                            "Invalid property element format in nuxeo-structure.xml. Property name attribute is required");
                }
                md.setProperty(attr.getValue().trim(), echild.getTextContent().trim());
            }
        }
        child = child.getNextSibling();
    }
}

From source file:org.nuxeo.runtime.model.persistence.fs.FileSystemStorage.java

public static void loadMetadata(Contribution contrib) {
    try {//  ww  w.ja va 2  s  . c  o m
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(new ByteArrayInputStream(contrib.getContent().getBytes()));
        Element root = doc.getDocumentElement();
        contrib.setDisabled(Boolean.parseBoolean(root.getAttribute("disabled")));
        Node node = root.getFirstChild();
        while (node != null) {
            if (node.getNodeType() == Node.ELEMENT_NODE && "documentation".equals(node.getNodeName())) {
                break;
            }
            node = node.getNextSibling();
        }
        if (node != null) {
            node = node.getFirstChild();
            StringBuilder buf = new StringBuilder();
            while (node != null) {
                if (node.getNodeType() == Node.TEXT_NODE) {
                    buf.append(node.getNodeValue());
                }
                node = node.getNextSibling();
            }
            contrib.setDescription(buf.toString().trim());
        } else {
            contrib.setDescription("");
        }
    } catch (ParserConfigurationException | SAXException | IOException | DOMException e) {
        log.error("Failed to read contribution metadata", e);
    }
}

From source file:org.nuxeo.runtime.model.persistence.fs.FileSystemStorage.java

@Override
public Contribution updateContribution(Contribution contribution) {
    File file = new File(root, contribution.getName() + ".xml");
    String content = safeRead(file);
    DocumentBuilder docBuilder;/*w  ww. ja  v  a  2 s.co  m*/
    try {
        docBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Document doc;
    try {
        doc = docBuilder.parse(new ByteArrayInputStream(content.getBytes()));
    } catch (SAXException | IOException e) {
        throw new RuntimeException(e);
    }
    Element root = doc.getDocumentElement();
    if (contribution.isDisabled()) {
        root.setAttribute("disabled", "true");
    } else {
        root.removeAttribute("disabled");
    }
    Node node = root.getFirstChild();
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE && "documentation".equals(node.getNodeName())) {
            break;
        }
        node = node.getNextSibling();
    }
    String description = contribution.getDescription();
    if (description == null) {
        description = "";
    }
    if (node != null) {
        root.removeChild(node);
    }
    Element el = doc.createElement("documentation");
    el.appendChild(doc.createTextNode(description));
    root.appendChild(el);

    try {
        safeWrite(file, DOMSerializer.toString(doc));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return getContribution(contribution.getName());
}

From source file:org.openehealth.ipf.commons.ihe.ws.utils.SoapUtils.java

/**
 * Searches for the first sub-element of the given XML element, which has
 * the given local name and whose namespace belongs to the given set.
 *
 * @param root//from ww w.j a va2 s  .co m
 *      an XML element whose children will be iterated, null values are allowed
 * @param nsUris
 *      a set of namespace URIs the wanted element can belong to
 * @param wantedLocalName
 *      local name of the wanted element
 * @return
 *      corresponding child element or <code>null</code> when none found
 */
public static Element getElementNS(Element root, Set<String> nsUris, String wantedLocalName) {
    if (root == null) {
        return null;
    }

    Node node = root.getFirstChild();
    while (node != null) {
        if ((node instanceof Element) && nsUris.contains(node.getNamespaceURI())
                && node.getLocalName().equals(wantedLocalName)) {
            return (Element) node;
        }

        node = node.getNextSibling();
    }

    return null;
}

From source file:org.openmrs.module.web.WebModuleUtil.java

/**
 * Performs the webapp specific startup needs for modules Normal startup is done in
 * {@link ModuleFactory#startModule(Module)} If delayContextRefresh is true, the spring context
 * is not rerun. This will save a lot of time, but it also means that the calling method is
 * responsible for restarting the context if necessary (the calling method will also have to
 * call {@link #loadServlets(Module, ServletContext)} and
 * {@link #loadFilters(Module, ServletContext)}).<br>
 * <br>//from w  w w.ja va  2 s .com
 * If delayContextRefresh is true and this module should have caused a context refresh, a true
 * value is returned. Otherwise, false is returned
 *
 * @param mod Module to start
 * @param servletContext the current ServletContext
 * @param delayContextRefresh true/false whether or not to do the context refresh
 * @return boolean whether or not the spring context need to be refreshed
 */
public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh) {

    if (log.isDebugEnabled()) {
        log.debug("trying to start module " + mod);
    }

    // only try and start this module if the api started it without a
    // problem.
    if (ModuleFactory.isModuleStarted(mod) && !mod.hasStartupError()) {

        String realPath = getRealPath(servletContext);

        if (realPath == null) {
            realPath = System.getProperty("user.dir");
        }

        File webInf = new File(realPath + "/WEB-INF".replace("/", File.separator));
        if (!webInf.exists()) {
            webInf.mkdir();
        }

        copyModuleMessagesIntoWebapp(mod, realPath);
        log.debug("Done copying messages");

        // flag to tell whether we added any xml/dwr/etc changes that necessitate a refresh
        // of the web application context
        boolean moduleNeedsContextRefresh = false;

        // copy the html files into the webapp (from /web/module/ in the module)
        // also looks for a spring context file. If found, schedules spring to be restarted
        JarFile jarFile = null;
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            File modFile = mod.getFile();
            jarFile = new JarFile(modFile);
            Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                log.debug("Entry name: " + name);
                if (name.startsWith("web/module/")) {
                    // trim out the starting path of "web/module/"
                    String filepath = name.substring(11);

                    StringBuffer absPath = new StringBuffer(realPath + "/WEB-INF");

                    // If this is within the tag file directory, copy it into /WEB-INF/tags/module/moduleId/...
                    if (filepath.startsWith("tags/")) {
                        filepath = filepath.substring(5);
                        absPath.append("/tags/module/");
                    }
                    // Otherwise, copy it into /WEB-INF/view/module/moduleId/...
                    else {
                        absPath.append("/view/module/");
                    }

                    // if a module id has a . in it, we should treat that as a /, i.e. files in the module
                    // ui.springmvc should go in folder names like .../ui/springmvc/...
                    absPath.append(mod.getModuleIdAsPath() + "/" + filepath);
                    if (log.isDebugEnabled()) {
                        log.debug("Moving file from: " + name + " to " + absPath);
                    }

                    // get the output file
                    File outFile = new File(absPath.toString().replace("/", File.separator));
                    if (entry.isDirectory()) {
                        if (!outFile.exists()) {
                            outFile.mkdirs();
                        }
                    } else {
                        // make the parent directories in case it doesn't exist
                        File parentDir = outFile.getParentFile();
                        if (!parentDir.exists()) {
                            parentDir.mkdirs();
                        }

                        //if (outFile.getName().endsWith(".jsp") == false)
                        //   outFile = new File(absPath.replace("/", File.separator) + MODULE_NON_JSP_EXTENSION);

                        // copy the contents over to the webapp for non directories
                        outStream = new FileOutputStream(outFile, false);
                        inStream = jarFile.getInputStream(entry);
                        OpenmrsUtil.copyFile(inStream, outStream);
                    }
                } else if (name.equals("moduleApplicationContext.xml")
                        || name.equals("webModuleApplicationContext.xml")) {
                    moduleNeedsContextRefresh = true;
                } else if (name.equals(mod.getModuleId() + "Context.xml")) {
                    String msg = "DEPRECATED: '" + name
                            + "' should be named 'moduleApplicationContext.xml' now. Please update/upgrade. ";
                    throw new ModuleException(msg, mod.getModuleId());
                }
            }
        } catch (IOException io) {
            log.warn("Unable to copy files from module " + mod.getModuleId() + " to the web layer", io);
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException io) {
                    log.warn("Couldn't close jar file: " + jarFile.getName(), io);
                }
            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close InputStream: " + io);
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close OutputStream: " + io);
                }
            }
        }

        // find and add the dwr code to the dwr-modules.xml file (if defined)
        InputStream inputStream = null;
        try {
            Document config = mod.getConfig();
            Element root = config.getDocumentElement();
            if (root.getElementsByTagName("dwr").getLength() > 0) {

                // get the dwr-module.xml file that we're appending our code to
                File f = new File(realPath + "/WEB-INF/dwr-modules.xml".replace("/", File.separator));

                // testing if file exists
                if (!f.exists()) {
                    // if it does not -> needs to be created
                    createDwrModulesXml(realPath);
                }

                inputStream = new FileInputStream(f);
                Document dwrmodulexml = getDWRModuleXML(inputStream, realPath);
                Element outputRoot = dwrmodulexml.getDocumentElement();

                // loop over all of the children of the "dwr" tag
                Node node = root.getElementsByTagName("dwr").item(0);
                Node current = node.getFirstChild();

                while (current != null) {
                    if ("allow".equals(current.getNodeName()) || "signatures".equals(current.getNodeName())
                            || "init".equals(current.getNodeName())) {
                        ((Element) current).setAttribute("moduleId", mod.getModuleId());
                        outputRoot.appendChild(dwrmodulexml.importNode(current, true));
                    }

                    current = current.getNextSibling();
                }

                moduleNeedsContextRefresh = true;

                // save the dwr-modules.xml file.
                OpenmrsUtil.saveDocument(dwrmodulexml, f);
            }
        } catch (FileNotFoundException e) {
            throw new ModuleException(realPath + "/WEB-INF/dwr-modules.xml file doesn't exist.", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException io) {
                    log.error("Error while closing input stream", io);
                }
            }
        }

        // mark to delete the entire module web directory on exit
        // this will usually only be used when an improper shutdown has occurred.
        String folderPath = realPath + "/WEB-INF/view/module/" + mod.getModuleIdAsPath();
        File outFile = new File(folderPath.replace("/", File.separator));
        outFile.deleteOnExit();

        // additional checks on module needing a context refresh
        if (moduleNeedsContextRefresh == false && mod.getAdvicePoints() != null
                && mod.getAdvicePoints().size() > 0) {

            // AOP advice points are only loaded during the context refresh now.
            // if the context hasn't been marked to be refreshed yet, mark it
            // now if this module defines some advice
            moduleNeedsContextRefresh = true;

        }

        // refresh the spring web context to get the just-created xml
        // files into it (if we copied an xml file)
        if (moduleNeedsContextRefresh && delayContextRefresh == false) {
            if (log.isDebugEnabled()) {
                log.debug("Refreshing context for module" + mod);
            }

            try {
                refreshWAC(servletContext, false, mod);
                log.debug("Done Refreshing WAC");
            } catch (Exception e) {
                String msg = "Unable to refresh the WebApplicationContext";
                mod.setStartupErrorMessage(msg, e);

                if (log.isWarnEnabled()) {
                    log.warn(msg + " for module: " + mod.getModuleId(), e);
                }

                try {
                    stopModule(mod, servletContext, true);
                    ModuleFactory.stopModule(mod, true, true); //remove jar from classloader play
                } catch (Exception e2) {
                    // exception expected with most modules here
                    if (log.isWarnEnabled()) {
                        log.warn("Error while stopping a module that had an error on refreshWAC", e2);
                    }
                }

                // try starting the application context again
                refreshWAC(servletContext, false, mod);

                notifySuperUsersAboutModuleFailure(mod);
            }

        }

        if (!delayContextRefresh && ModuleFactory.isModuleStarted(mod)) {
            // only loading the servlets/filters if spring is refreshed because one
            // might depend on files being available in spring
            // if the caller wanted to delay the refresh then they are responsible for
            // calling these two methods on the module

            // find and cache the module's servlets
            //(only if the module started successfully previously)
            log.debug("Loading servlets and filters for module: " + mod);
            loadServlets(mod, servletContext);
            loadFilters(mod, servletContext);
        }

        // return true if the module needs a context refresh and we didn't do it here
        return (moduleNeedsContextRefresh && delayContextRefresh == true);

    }

    // we aren't processing this module, so a context refresh is not necessary
    return false;
}

From source file:org.openmrs.projectbuendia.webservices.rest.XformResource.java

/**
 * Converts a vanilla Xform into one that ODK Collect is happy to work with.
 * This requires://from w  w  w  .jav a2 s . co  m
 * <ul>
 * <li>Changing the namespace of the the root element to http://www.w3.org/1999/xhtml
 * <li>Wrapping the model element in an HTML head element, with a title child element
 * <li>Wrapping remaining elements in an HTML body element
 * </ul>
 */
static String convertToOdkCollect(String xml, String title) throws IOException, SAXException {
    // Change the namespace of the root element. I haven't figured out a way
    // to do
    // this within a document; removing the root element from the document
    // seems
    // to do odd things... so instead, we import it into a new document.
    Document oldDoc = XmlUtil.parse(xml);
    Document doc = XmlUtil.getDocumentBuilder().newDocument();
    Element root = (Element) doc.importNode(oldDoc.getDocumentElement(), true);
    root = (Element) doc.renameNode(root, HTML_NAMESPACE, "h:form");
    doc.appendChild(root);

    // Prepare the new wrapper elements
    Element head = doc.createElementNS(HTML_NAMESPACE, "h:head");
    Element titleElement = XmlUtil.appendElementNS(head, HTML_NAMESPACE, "h:title");
    titleElement.setTextContent(title);
    Element body = doc.createElementNS(HTML_NAMESPACE, "h:body");

    // Find the model element to go in the head, and all its following
    // siblings to go in the body.
    // We do this before moving any elements, for the sake of sanity.
    Element model = getElementOrThrowNS(root, XFORMS_NAMESPACE, "model");
    List<Node> nodesAfterModel = new ArrayList<>();
    Node nextSibling = model.getNextSibling();
    while (nextSibling != null) {
        nodesAfterModel.add(nextSibling);
        nextSibling = nextSibling.getNextSibling();
    }

    // Now we're done with the preparation, we can move everything.
    head.appendChild(model);
    for (Node node : nodesAfterModel) {
        body.appendChild(node);
    }

    // Having removed the model and everything after it, we can now just
    // append the head and body to the document element...
    root.appendChild(head);
    root.appendChild(body);

    return XformsUtil.doc2String(doc);
}

From source file:org.opensingular.internal.lib.commons.xml.MElement.java

/**
 * Conta o nmero de ocorrncias de Elements filhos do no com o nome
 * especificado./*w  ww. j  a va 2  s.c o m*/
 *
 * @param nome do elemento a ser procurado. Se for null conta todos.
 * @return o nmero de ocorrncias
 */
public final int count(String nome) {
    int qtd = 0;
    Node node = getFirstChild();
    while (node != null) {
        if (XmlUtil.isNodeTypeElement(node, nome)) {
            qtd++;
        }
        node = node.getNextSibling();
    }
    return qtd;
}

From source file:org.opensingular.internal.lib.commons.xml.TestMElement.java

License:asdf

/**
 * Verifica se ambos os nos so iguais fazendo uma comparao em
 * profundidade.//from  w ww . j a v  a 2  s .c o m
 *
 * @param n1 -
 * @param n2 -
 * @throws Exception Se nbo forem iguais
 */
public static void isIgual(Node n1, Node n2) throws Exception {
    if (n1 == n2) {
        return;
    }

    isIgual(n1, n2, "NodeName", n1.getNodeName(), n2.getNodeName());
    isIgual(n1, n2, "NodeValue", n1.getNodeValue(), n2.getNodeValue());
    isIgual(n1, n2, "Namespace", n1.getNamespaceURI(), n2.getNamespaceURI());
    isIgual(n1, n2, "Prefix", n1.getPrefix(), n2.getPrefix());
    isIgual(n1, n2, "LocalName", n1.getLocalName(), n2.getLocalName());

    if (isMesmaClasse(Element.class, n1, n2)) {
        Element e1 = (Element) n1;
        Element e2 = (Element) n2;
        //Verifica se possuem os mesmos atributos
        NamedNodeMap nn1 = e1.getAttributes();
        NamedNodeMap nn2 = e2.getAttributes();
        if (nn1.getLength() != nn2.getLength()) {
            fail("O nmero atributos em " + XPathToolkit.getFullPath(n1) + " (qtd=" + nn1.getLength()
                    + "  diferente de n2 (qtd=" + nn2.getLength() + ")");
        }
        for (int i = 0; i < nn1.getLength(); i++) {
            isIgual((Attr) nn1.item(i), (Attr) nn2.item(i));
        }

        //Verifica se possuem os mesmos filhos
        Node filho1 = e1.getFirstChild();
        Node filho2 = e2.getFirstChild();
        int count = 0;
        while ((filho1 != null) && (filho2 != null)) {
            isIgual(filho1, filho2);
            filho1 = filho1.getNextSibling();
            filho2 = filho2.getNextSibling();
            count++;
        }
        if (filho1 != null) {
            fail("H mais node [" + count + "] " + XPathToolkit.getNomeTipo(filho1) + " ("
                    + XPathToolkit.getFullPath(filho1) + ") em n1:" + XPathToolkit.getFullPath(n1));
        }
        if (filho2 != null) {
            fail("H mais node [" + count + "] " + XPathToolkit.getNomeTipo(filho2) + " ("
                    + XPathToolkit.getFullPath(filho2) + ") em n2:" + XPathToolkit.getFullPath(n2));
        }

    } else if (isMesmaClasse(Attr.class, n1, n2)) {
        //Ok

    } else if (isMesmaClasse(Text.class, n1, n2)) {
        //Ok

    } else {
        fail("Tipo de n " + n1.getClass() + " no tratado");
    }

}