Example usage for org.dom4j Node selectNodes

List of usage examples for org.dom4j Node selectNodes

Introduction

In this page you can find the example usage for org.dom4j Node selectNodes.

Prototype

List<Node> selectNodes(String xpathExpression);

Source Link

Document

selectNodes evaluates an XPath expression and returns the result as a List of Node instances or String instances depending on the XPath expression.

Usage

From source file:edu.scripps.fl.pubchem.web.pug.PUGRequest.java

License:Apache License

public static void setResponseIds(Document document, Type type, Collection<Object> ids) throws Exception {
    String idTypePath = "//PCT-QueryAssayData_";
    idTypePath += Type.AID.equals(type) ? "aids" : "scids";
    Node localRoot = document.selectSingleNode(idTypePath);
    Node node = localRoot.selectSingleNode(".//PCT-ID-List_db");
    node.setText(type.getDatabase());/*from   ww w .ja v  a 2 s.c  o  m*/
    node = localRoot.selectSingleNode(".//PCT-ID-List_uids");
    //      if (node == null)
    //         throw new Exception("Cannot find PCT-ID-List_uids node");
    for (Node child : (List<Node>) node.selectNodes("*"))
        child.detach();
    for (Object id : ids) {
        Element aidElem = DocumentHelper.createElement("PCT-ID-List_uids_E");
        aidElem.setText(id.toString());
        ((Element) node).add(aidElem);
    }
}

From source file:edu.scripps.fl.pubchem.xml.extract.CategorizedCommentExtractor.java

License:Apache License

public List<CategorizedComment> getCategorizedCommentsFromXML(Document doc) throws Exception {
    List<CategorizedComment> comments = new ArrayList<CategorizedComment>();
    List<Node> nodes = doc.selectNodes("//PC-AssayDescription_categorized-comment/PC-CategorizedComment");
    PubChemXMLUtils utils = new PubChemXMLUtils();
    for (Node nn : nodes) {
        CategorizedComment comment = new CategorizedComment();
        comment.setCommentTag(nn.selectSingleNode("PC-CategorizedComment_title").getText());
        List<Node> valueNodes = nn.selectNodes("PC-CategorizedComment_comment/PC-CategorizedComment_comment_E");
        String text = "";
        for (Node valeuNode : valueNodes) {
            if (null != valeuNode.getText())
                text = text + valeuNode.getText() + "\n";
        }/*from   www . j  a v a 2s . com*/
        comment.setCommentValue(text);
        comments.add(comment);
    }
    return comments;
}

From source file:edu.scripps.fl.pubchem.xml.extract.PanelExtractor.java

License:Apache License

public List<Panel> getPanelValuesFromXML(Document doc) throws Exception {
    List<Panel> panelValues = new ArrayList<Panel>();
    List<Node> nodes = doc.selectNodes(
            "//PC-AssayDescription_panel-info/PC-AssayPanel/PC-AssayPanel_member/PC-AssayPanelMember");
    for (Node nn : nodes) {
        Panel panelValue = new Panel();
        panelValue.setPanelName(nn.selectSingleNode("PC-AssayPanelMember_name").getText());
        List<Node> targetNodes = nn.selectNodes("PC-AssayPanelMember_target/PC-AssayTargetInfo");
        if (targetNodes != null && targetNodes.size() > 0) {
            List<PanelTarget> targets = new ArrayList<PanelTarget>();
            for (Node targetNode : targetNodes) {
                PanelTarget target = new PanelTarget();
                target.setPanelTargetName(targetNode.selectSingleNode("PC-AssayTargetInfo_name").getText());
                BeanUtils.setProperty(target, "panelTargetGi",
                        targetNode.selectSingleNode("PC-AssayTargetInfo_mol-id").getText());
                target.setPanelTargetType(
                        targetNode.selectSingleNode("PC-AssayTargetInfo_molecule-type").valueOf("@value"));
                targets.add(target);/*from  w w w.  j a  v  a  2  s  . co m*/
            }
            panelValue.setPanelTarget(targets);
        }

        Node p = nn.selectSingleNode("PC-AssayPanelMember_xref");
        if (p != null) {
            List<Integer> taxonomies = getXrefValues(
                    "PC-AnnotatedXRef/PC-AnnotatedXRef_xref/PC-XRefData/PC-XRefData_taxonomy", p);
            panelValue.setPanelTaxonomy(taxonomies);
            List<Integer> genes = getXrefValues(
                    "PC-AnnotatedXRef/PC-AnnotatedXRef_xref/PC-XRefData/PC-XRefData_gene", p);
            panelValue.setPanelGene(genes);
        }
        panelValues.add(panelValue);
    }
    return panelValues;
}

From source file:edu.scripps.fl.pubchem.xml.extract.PanelExtractor.java

License:Apache License

private List<Integer> getXrefValues(String nodeName, Node parent) {
    List<Node> nodes = parent.selectNodes(nodeName);
    List<Integer> list = new ArrayList<Integer>();
    if (nodes != null) {
        for (Node node : nodes)
            list.add(Integer.parseInt(node.getText()));
    }/*from ww w  .ja v  a2 s . com*/
    return list;
}

From source file:edu.umd.cs.buildServer.inspection.PMDRunner.java

License:Apache License

private void readPMDTestOutcomes(XMLDocumentBuilder stdoutMonitor) {
    Document document = stdoutMonitor.getDocument();
    if (document == null)
        return;/*from   ww w .  j a va  2  s  .co m*/

    int count = TestOutcome.FIRST_TEST_NUMBER;
    Iterator<?> fileNodeIter = document.selectNodes("//pmd/file").iterator();
    while (fileNodeIter.hasNext()) {
        Node fileElement = (Node) fileNodeIter.next();
        String fileName = fileElement.valueOf("@name");
        Iterator<?> violationIter = fileElement.selectNodes("./violation").iterator();
        while (violationIter.hasNext()) {
            Node violationElement = (Node) violationIter.next();
            String line = violationElement.valueOf("@line");
            String rule = violationElement.valueOf("@rule");
            String description = violationElement.getText();
            String priority = violationElement.valueOf("@priority");

            // Turn the warning into a TestOutcome
            TestOutcome testOutcome = new TestOutcome();
            testOutcome.setTestType(TestOutcome.TestType.PMD);
            testOutcome.setTestName(rule);
            testOutcome.setOutcome(TestOutcome.STATIC_ANALYSIS);
            testOutcome.setShortTestResult(fileName + ":" + line);
            testOutcome.setLongTestResultCompressIfNeeded(description);
            testOutcome.setTestNumber(Integer.toString(count++));
            testOutcome.setExceptionClassName(priority); // XXX: HACK!

            testOutcomeCollection.add(testOutcome);
        }
    }

    projectSubmission.getLog().info("Recorded " + count + " PMD warnings as test outcomes");
}

From source file:edu.umd.cs.findbugs.xml.XMLUtil.java

License:Open Source License

@SuppressWarnings("unchecked")
public static <T> List<T> selectNodes(Node node, String arg0) {
    return node.selectNodes(arg0);
}

From source file:eleyzhu.facetid.common.PluginManager.java

License:Open Source License

/**
 * Loads public plugins.//from  w  w w.  j ava2s .  c o m
 *
 * @param pluginDir the directory of the expanded public plugin.
 * @return the new Plugin model for the Public Plugin.
 */
private Plugin loadPublicPlugin(File pluginDir) {

    File pluginFile = new File(pluginDir, "plugin.xml");
    SAXReader saxReader = new SAXReader();
    Document pluginXML = null;
    try {
        pluginXML = saxReader.read(pluginFile);
    } catch (DocumentException e) {
        Log.error(e);
    }

    Plugin pluginClass = null;

    List<? extends Node> plugins = pluginXML.selectNodes("/plugin");
    for (Node plugin1 : plugins) {
        PublicPlugin publicPlugin = new PublicPlugin();

        String clazz = null;
        String name;
        String minVersion;

        try {

            name = plugin1.selectSingleNode("name").getText();
            clazz = plugin1.selectSingleNode("class").getText();

            try {
                String lower = name.replaceAll("[^0-9a-zA-Z]", "").toLowerCase();
                // Dont load the plugin if its on the Blacklist
                if (_blacklistPlugins.contains(lower) || _blacklistPlugins.contains(clazz)
                        || SettingsManager.getLocalPreferences().getDeactivatedPlugins().contains(name)) {
                    return null;
                }
            } catch (Exception e) {
                // Whatever^^
                return null;
            }

            // Check for minimum Spark version
            try {
                minVersion = plugin1.selectSingleNode("minSparkVersion").getText();

                String buildNumber = JiveInfo.getVersion();
                boolean ok = buildNumber.compareTo(minVersion) >= 0;

                if (!ok) {
                    return null;
                }
            } catch (Exception e) {
                Log.error("Unable to load plugin " + name
                        + " due to missing <minSparkVersion>-Tag in plugin.xml.");
                return null;
            }

            // Check for minimum Java version
            try {
                String javaversion = plugin1.selectSingleNode("java").getText().replaceAll("[^0-9]", "");
                javaversion = javaversion == null ? "0" : javaversion;
                int jv = Integer.parseInt(attachMissingZero(javaversion));

                String myversion = System.getProperty("java.version").replaceAll("[^0-9]", "");
                int mv = Integer.parseInt(attachMissingZero(myversion));

                boolean ok = (mv >= jv);

                if (!ok) {
                    Log.error("Unable to load plugin " + name + " due to old JavaVersion.\nIt Requires "
                            + plugin1.selectSingleNode("java").getText() + " you have "
                            + System.getProperty("java.version"));
                    return null;
                }

            } catch (NullPointerException e) {
                Log.warning("Plugin " + name + " has no <java>-Tag, consider getting a newer Version");
            }

            // set dependencies 
            try {
                List<? extends Node> dependencies = plugin1.selectNodes("depends/plugin");
                for (Node depend1 : dependencies) {
                    Element depend = (Element) depend1;
                    PluginDependency dependency = new PluginDependency();
                    dependency.setVersion(depend.selectSingleNode("version").getText());
                    dependency.setName(depend.selectSingleNode("name").getText());
                    publicPlugin.addDependency(dependency);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Do operating system check.
            boolean operatingSystemOK = isOperatingSystemOK(plugin1);
            if (!operatingSystemOK) {
                return null;
            }

            publicPlugin.setPluginClass(clazz);
            publicPlugin.setName(name);

            try {
                String version = plugin1.selectSingleNode("version").getText();
                publicPlugin.setVersion(version);

                String author = plugin1.selectSingleNode("author").getText();
                publicPlugin.setAuthor(author);

                String email = plugin1.selectSingleNode("email").getText();
                publicPlugin.setEmail(email);

                String description = plugin1.selectSingleNode("description").getText();
                publicPlugin.setDescription(description);

                String homePage = plugin1.selectSingleNode("homePage").getText();
                publicPlugin.setHomePage(homePage);
            } catch (Exception e) {
                Log.debug("We can ignore these.");
            }

            try {
                pluginClass = (Plugin) getParentClassLoader().loadClass(clazz).newInstance();
                Log.debug(name + " has been loaded.");
                publicPlugin.setPluginDir(pluginDir);
                publicPlugins.add(publicPlugin);

                registerPlugin(pluginClass);
            } catch (Throwable e) {
                Log.error("Unable to load plugin " + clazz + ".", e);
            }
        } catch (Exception ex) {
            Log.error("Unable to load plugin " + clazz + ".", ex);
        }

    }

    return pluginClass;
}

From source file:Emporium.Servlet.ServImportaImpressaoPLP.java

public static String leXmlPLP(String xml, String idPLP, int idCliente, int idDepto, String nomeBD)
        throws DocumentException, HeadlessException {
    String ret = "";
    xml = xml.replaceAll("&", "E");
    //System.out.println(xml);
    if (xml != null && !xml.isEmpty()) {

        SAXReader reader = new SAXReader();
        StringReader sr = new StringReader(xml);
        Document doc = reader.read(sr);
        List<Node> eventos = (List<Node>) doc.selectNodes("//correioslog");

        // processa eventos
        for (Node node : eventos) {
            String contrato = node.valueOf("remetente/numero_contrato");
            String cartaoPostagem = "";//node.valueOf("");
            String codigoAdministrativo = node.valueOf("remetente/codigo_administrativo");

            String nomeRemetente = node.valueOf("remetente/nome_remetente");
            String cepRemetente = node.valueOf("remetente/cep_remetente");
            String enderecoRemetente = node.valueOf("remetente/logradouro_remetente");
            String numeroRemetente = node.valueOf("remetente/numero_remetente");
            String complementoRemetente = node.valueOf("remetente/complemento_remetente");
            String bairroRemetente = node.valueOf("remetente/bairro_remetente");
            String cidadeRemetente = node.valueOf("remetente/cidade_remetente");
            String ufRemetente = node.valueOf("remetente/uf_remetente");
            Endereco endRemetente = new Endereco(nomeRemetente, enderecoRemetente, numeroRemetente,
                    complementoRemetente, bairroRemetente, cidadeRemetente, ufRemetente, cepRemetente);

            List<Node> evnt = (List<Node>) node.selectNodes("objeto_postal");
            for (Node nd : evnt) {

                String notaFiscal = nd.valueOf("nacional/numero_nota_fiscal");
                int codECT = Integer.parseInt(nd.valueOf("codigo_servico_postagem").trim());
                String servico = ContrServicoECT.consultaGrupoServicoByCodECT(codECT);

                String nomeDestinatario = nd.valueOf("destinatario/nome_destinatario");
                String cepDestinatario = nd.valueOf("nacional/cep_destinatario");
                String enderecoDestinatario = nd.valueOf("destinatario/logradouro_destinatario");
                String numeroDestinatario = nd.valueOf("destinatario/numero_end_destinatario");
                String complementoDestinatario = nd.valueOf("destinatario/complemento_destinatario");
                String bairroDestinatario = nd.valueOf("nacional/bairro_destinatario");
                String cidadeDestinatario = nd.valueOf("nacional/cidade_destinatario");
                String ufDestinatario = nd.valueOf("nacional/uf_destinatario");
                Endereco endDestinatario = new Endereco(nomeDestinatario, enderecoDestinatario,
                        numeroDestinatario, complementoDestinatario, bairroDestinatario, cidadeDestinatario,
                        ufDestinatario, cepDestinatario);

                int ar = 0;
                int mp = 0;
                int rg = 0;
                int rm = 0;
                int pr = 0;
                float vd = 0;
                List<Node> evtAdicionais = (List<Node>) node.selectNodes("servico_adicional");
                for (Node nda : evtAdicionais) {
                    int codAd = Integer.parseInt(nda.valueOf("codigo_servico_adicional").trim());
                    switch (codAd) {
                    case 1:
                        ar = 1;//  w ww.  j a  v a 2  s .c o  m
                        break;
                    case 2:
                        mp = 1;
                        break;
                    case 4:
                        rm = 1;
                        break;
                    case 15:
                        pr = 1;
                        break;
                    case 19:
                    case 35:
                        vd = Float.parseFloat(nda.valueOf("valor_declarado").trim().replace(",", "."));
                        break;
                    default:
                        break;
                    }
                }

                String sro = nd.valueOf("numero_etiqueta");
                ContrImpressaoPLP.inserePLP(sro, idPLP, 0, contrato, cartaoPostagem, codigoAdministrativo,
                        codECT, servico, idCliente, idDepto, ar, mp, vd, pr, rg, rm, notaFiscal, endRemetente,
                        endDestinatario, nomeBD);

            }
        }

    } else {
        ret = "XML da PLP est vazio!";
    }

    return ret;
}

From source file:fr.gouv.culture.vitam.utils.XmlDom.java

License:Open Source License

/**
 * Attached file accessibility test/*from   w w w .j  ava2  s .  c o m*/
 * 
 * @param current_file
 * @param task
 *            optional
 * @param config
 * @param argument
 * @param checkDigest
 * @param checkFormat
 * @param showFormat
 * @return VitamResult
 */
static final public VitamResult all_tests_in_one(File current_file, RunnerLongTask task, ConfigLoader config,
        VitamArgument argument, boolean checkDigest, boolean checkFormat, boolean showFormat) {
    SAXReader saxReader = new SAXReader();
    VitamResult finalResult = new VitamResult();
    Element root = initializeCheck(argument, finalResult, current_file);
    try {
        Document document = saxReader.read(current_file);
        removeAllNamespaces(document);
        Node nodesrc = document.selectSingleNode("/digests");
        String src = null;
        String localsrc = current_file.getParentFile().getAbsolutePath() + File.separator;
        if (nodesrc != null) {
            nodesrc = nodesrc.selectSingleNode("@source");
            if (nodesrc != null) {
                src = nodesrc.getText() + "/";
            }
        }
        if (src == null) {
            src = localsrc;
        }
        @SuppressWarnings("unchecked")
        List<Node> nodes = document.selectNodes("//" + config.DOCUMENT_FIELD);
        if (nodes == null) {
            Element result = fillInformation(argument, root, "result", "filefound", "0");
            addDate(argument, config, result);
        } else {
            String number = "" + nodes.size();
            Element result = fillInformation(argument, root, "result", "filefound", number);
            XMLWriter writer = null;
            writer = new XMLWriter(System.out, StaticValues.defaultOutputFormat);
            int currank = 0;
            for (Node node : nodes) {
                currank++;
                Node attachment = node.selectSingleNode(config.ATTACHMENT_FIELD);
                if (attachment == null) {
                    continue;
                }
                Node file = attachment.selectSingleNode(config.FILENAME_ATTRIBUTE);
                if (file == null) {
                    continue;
                }
                Node mime = null;
                Node format = null;
                if (checkFormat) {
                    mime = attachment.selectSingleNode(config.MIMECODE_ATTRIBUTE);
                    format = attachment.selectSingleNode(config.FORMAT_ATTRIBUTE);
                }
                String sfile = null;
                String smime = null;
                String sformat = null;
                String sintegrity = null;
                String salgo = null;
                if (file != null) {
                    sfile = file.getText();
                }
                if (mime != null) {
                    smime = mime.getText();
                }
                if (format != null) {
                    sformat = format.getText();
                }
                // Now check
                // first existence check
                String ficname = src + sfile;
                Element check = fillInformation(argument, root, "check", "filename", sfile);
                File fic1 = new File(ficname);
                File fic2 = new File(localsrc + sfile);
                File fic = null;
                if (fic1.canRead()) {
                    fic = fic1;
                } else if (fic2.canRead()) {
                    fic = fic2;
                }
                if (fic == null) {
                    fillInformation(argument, check, "find", "status",
                            StaticValues.LBL.error_filenotfile.get());
                    addDate(argument, config, result);
                    finalResult.values[AllTestsItems.FileError.ordinal()]++;
                    finalResult.values[AllTestsItems.GlobalError.ordinal()]++;
                } else {
                    Element find = fillInformation(argument, check, "find", "status", "ok");
                    addDate(argument, config, find);
                    finalResult.values[AllTestsItems.FileSuccess.ordinal()]++;
                    if (checkDigest) {
                        @SuppressWarnings("unchecked")
                        List<Node> integrities = node.selectNodes(config.INTEGRITY_FIELD);
                        for (Node integrity : integrities) {
                            Node algo = integrity.selectSingleNode(config.ALGORITHME_ATTRIBUTE);
                            salgo = null;
                            sintegrity = null;
                            if (integrity != null) {
                                sintegrity = integrity.getText();
                                if (algo != null) {
                                    salgo = algo.getText();
                                } else {
                                    salgo = config.DEFAULT_DIGEST;
                                }
                            }
                            // Digest check
                            if (salgo == null) {
                                // nothing
                            } else if (salgo.equals(StaticValues.XML_SHA1)) {
                                salgo = "SHA-1";
                            } else if (salgo.equals(StaticValues.XML_SHA256)) {
                                salgo = "SHA-256";
                            } else if (salgo.equals(StaticValues.XML_SHA512)) {
                                salgo = "SHA-512";
                            } else {
                                salgo = null;
                            }

                            if (algo != null) {
                                Element eltdigest = Commands.checkDigest(fic, salgo, sintegrity);
                                if (eltdigest.selectSingleNode(".[@status='ok']") != null) {
                                    finalResult.values[AllTestsItems.DigestSuccess.ordinal()]++;
                                } else {
                                    finalResult.values[AllTestsItems.DigestError.ordinal()]++;
                                    finalResult.values[AllTestsItems.GlobalError.ordinal()]++;
                                }
                                addDate(argument, config, eltdigest);
                                addElement(writer, argument, check, eltdigest);
                            }
                        }
                    }
                    // Check format
                    if (checkFormat && config.droidHandler != null) {
                        try {
                            // Droid
                            List<DroidFileFormat> list = config.droidHandler.checkFileFormat(fic, argument);
                            Element cformat = Commands.droidFormat(list, smime, sformat, sfile, fic);
                            if (config.droidHandler != null) {
                                cformat.addAttribute("pronom", config.droidHandler.getVersionSignature());
                            }
                            if (config.droidHandler != null) {
                                cformat.addAttribute("droid", "6.1");
                            }
                            if (cformat.selectSingleNode(".[@status='ok']") != null) {
                                finalResult.values[AllTestsItems.FormatSuccess.ordinal()]++;
                            } else if (cformat.selectSingleNode(".[@status='warning']") != null) {
                                finalResult.values[AllTestsItems.FormatWarning.ordinal()]++;
                                finalResult.values[AllTestsItems.GlobalWarning.ordinal()]++;
                            } else {
                                finalResult.values[AllTestsItems.FormatError.ordinal()]++;
                                finalResult.values[AllTestsItems.GlobalError.ordinal()]++;
                            }
                            addDate(argument, config, cformat);
                            addElement(writer, argument, check, cformat);
                        } catch (Exception e) {
                            Element cformat = fillInformation(argument, check, "format", "status",
                                    "Error " + e.toString());
                            addDate(argument, config, cformat);
                            finalResult.values[AllTestsItems.SystemError.ordinal()]++;
                        }
                    }
                    // Show format
                    if (showFormat && config.droidHandler != null) {
                        Element showformat = Commands.showFormat(sfile, smime, sformat, fic, config, argument);
                        if (showformat.selectSingleNode(".[@status='ok']") != null) {
                            finalResult.values[AllTestsItems.ShowSuccess.ordinal()]++;
                        } else if (showformat.selectSingleNode(".[@status='warning']") != null) {
                            finalResult.values[AllTestsItems.ShowWarning.ordinal()]++;
                            finalResult.values[AllTestsItems.GlobalWarning.ordinal()]++;
                        } else {
                            finalResult.values[AllTestsItems.ShowError.ordinal()]++;
                            finalResult.values[AllTestsItems.GlobalError.ordinal()]++;
                        }
                        addDate(argument, config, showformat);
                        addElement(writer, argument, check, showformat);
                    }
                }
                addDate(argument, config, result);
                root = finalizeOneCheck(argument, finalResult, current_file, number);
                if (root != null) {
                    result = root.element("result");
                }
                if (task != null) {
                    float value = ((float) currank) / (float) nodes.size();
                    value *= 100;
                    task.setProgressExternal((int) value);
                }
            }
        }
        document = null;
    } catch (DocumentException e1) {
        Element result = fillInformation(argument, root, "result", "parsererror",
                StaticValues.LBL.error_error.get() + " " + e1 + " - " + StaticValues.LBL.error_parser.get()
                        + " (" + SAXReader.class.getName() + ")");
        addDate(argument, config, result);
        finalResult.values[AllTestsItems.SystemError.ordinal()]++;
    } catch (UnsupportedEncodingException e1) {
        Element result = fillInformation(argument, root, "result", "parsererror",
                StaticValues.LBL.error_error.get() + " " + e1 + " - " + StaticValues.LBL.error_parser.get()
                        + " (" + XMLWriter.class.getName() + ")");
        addDate(argument, config, result);
        finalResult.values[AllTestsItems.SystemError.ordinal()]++;
    }
    finalizeAllCheck(argument, finalResult);
    return finalResult;
}

From source file:fr.isima.ponge.wsprotocol.xml.XmlIOManager.java

License:Open Source License

/**
 * Reads extra properties.//from  w  w  w.  j  a  va2 s  . c  o  m
 *
 * @param keeper   The object having extra properties.
 * @param rootNode The XML node to gather the properties from.
 */
protected void readExtraProperties(ExtraPropertiesKeeper keeper, Node rootNode) {
    for (Object o : rootNode.selectNodes("extra-property")) {
        Node node = (Node) o;
        String className = node.valueOf("@type");
        if (className == null) {
            className = String.class.getName();
        }
        ExtraPropertyHandler handler = getExtraPropertyHandler(className);
        if (handler != null) {
            handler.readExtraProperty((Element) node, keeper);
        }
    }
}