Example usage for org.jdom2.xpath XPathFactory instance

List of usage examples for org.jdom2.xpath XPathFactory instance

Introduction

In this page you can find the example usage for org.jdom2.xpath XPathFactory instance.

Prototype

public static final XPathFactory instance() 

Source Link

Document

Obtain an instance of an XPathFactory using the default mechanisms to determine what XPathFactory implementation to use.

Usage

From source file:ataraxis.passwordmanager.XMLHandler.java

License:Open Source License

/**
 * Check if the ElementId has Child-Elements.
 * //from w w w  . j  ava  2s  .  c o  m
 * @param ElementID
 * @return true if Child's exist, false otherwise
 */
public boolean hasChilds(String ElementID) {
    boolean hasChilds = false;

    if (ElementID == null || ElementID.equals("")) {
        hasChilds = false;
    } else {
        XPathExpression<Element> xpath = XPathFactory.instance().compile("//group[@id='" + ElementID + "']",
                Filters.element());
        Element tempElement = xpath.evaluateFirst(s_doc);

        if (tempElement == null) {
            hasChilds = false;
        } else {
            List<Element> childList = tempElement.getChildren();
            hasChilds = (childList.size() > 0);
        }
    }

    return hasChilds;
}

From source file:ataraxis.passwordmanager.XMLHandler.java

License:Open Source License

/**
 * Return the Element with the ID ElementID
 *
 * @param ElementID the ID of the Element (group or account)
 * @throws JDOMException by problems with jdom
 *///  www  . j  a va  2s . c o  m
private Element getElement(String ElementID) throws JDOMException {
    Element returnElement;

    XPathExpression<Element> xpath = XPathFactory.instance().compile("//*[@id='" + ElementID + "']",
            Filters.element());
    Element tempElement = xpath.evaluateFirst(s_doc);

    if (tempElement != null) {
        returnElement = tempElement;
    } else {
        throw new JDOMException("Element not Found");
    }
    return returnElement;
}

From source file:ca.nrc.cadc.vosi.avail.CheckWebService.java

License:Open Source License

void checkReturnedXml(String strXml) throws CheckException {
    Document doc;/*  ww  w .  j  av  a  2  s  .c  o  m*/
    String xpathStr;

    try {
        StringReader reader = new StringReader(strXml);
        doc = XmlUtil.buildDocument(reader, schemaMap);

        //get namespace and/or prefix from Document, then create xpath based on the prefix
        String nsp = doc.getRootElement().getNamespacePrefix(); //Namespace Prefix
        if (nsp != null && nsp.length() > 0)
            nsp = nsp + ":";
        else
            nsp = "";
        xpathStr = "/" + nsp + "availability/" + nsp + "available";
        XPathBuilder<Element> builder = new XPathBuilder<Element>(xpathStr, Filters.element());
        Namespace ns = Namespace.getNamespace(VOSI.NS_PREFIX, VOSI.AVAILABILITY_NS_URI);
        builder.setNamespace(ns);
        XPathExpression<Element> xpath = builder.compileWith(XPathFactory.instance());
        Element eleAvail = xpath.evaluateFirst(doc);
        log.debug(eleAvail);
        String textAvail = eleAvail.getText();

        // TODO: is this is actually valid? is the content not constrained by the schema?
        if (textAvail == null)
            throw new CheckException(wsURL + " output is invalid: no content in <available> element", null);

        if (!textAvail.equalsIgnoreCase("true")) {
            xpathStr = "/" + nsp + "availability/" + nsp + "note";
            builder = new XPathBuilder<Element>(xpathStr, Filters.element());
            builder.setNamespace(ns);
            xpath = builder.compileWith(XPathFactory.instance());
            Element eleNotes = xpath.evaluateFirst(doc);

            String textNotes = eleNotes.getText();
            throw new CheckException("service " + wsURL + " is not available, reported reason: " + textNotes,
                    null);
        }
    } catch (IOException e) {
        // probably an incorrect setup or bug in the checks
        throw new RuntimeException("failed to test " + wsURL, e);
    } catch (JDOMException e) {
        throw new CheckException(wsURL + " output is invalid", e);
    }
}

From source file:cager.parser.test.SimpleTest2.java

License:Open Source License

private void XMLtoJavaParser() {

    // Creamos el builder basado en SAX  
    SAXBuilder builder = new SAXBuilder();

    try {//from  www.  java  2s . c  om

        String nombreMetodo = null;
        List<String> atributos = new ArrayList<String>();
        String tipoRetorno = null;
        String nombreArchivo = null;
        String exportValue = "";
        String codigoFuente = "";
        HashMap<String, String> tipos = new HashMap<String, String>();

        // Construimos el arbol DOM a partir del fichero xml  
        Document doc = builder.build(new FileInputStream(ruta + "VBParser\\ejemplosKDM\\archivo.kdm"));
        //Document doc = builder.build(new FileInputStream("E:\\WorkspaceParser\\VBParser\\ejemplosKDM\\archivo.kdm"));    

        Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI");

        XPathExpression<Element> xpath = XPathFactory.instance().compile("//codeElement", Filters.element());

        List<Element> elements = xpath.evaluate(doc);

        for (Element emt : elements) {

            if (emt.getAttribute("type", xmi).getValue().compareTo("code:CompilationUnit") == 0) {

                nombreArchivo = emt.getAttributeValue("name").substring(0,
                        emt.getAttributeValue("name").indexOf('.'));

            }

            if (emt.getAttribute("type", xmi).getValue().compareTo("code:LanguageUnit") == 0) {

                List<Element> hijos = emt.getChildren();

                for (Element hijo : hijos) {

                    tipos.put(hijo.getAttributeValue("id", xmi), hijo.getAttributeValue("name"));

                }

            }
        }

        FileOutputStream fout;

        fout = new FileOutputStream(ruta + "VBParser\\src\\cager\\parser\\test\\" + nombreArchivo + ".java");
        //fout = new FileOutputStream("E:\\WorkspaceParser\\VBParser\\src\\cager\\parser\\test\\"+nombreArchivo+".java");           
        // get the content in bytes
        byte[] contentInBytes = null;

        contentInBytes = ("package cager.parser.test;\n\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();

        contentInBytes = ("public class " + nombreArchivo + "{\n\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();

        for (Element emt : elements) {
            // System.out.println("XPath has result: " + emt.getName()+" "+emt.getAttribute("type",xmi));
            if (emt.getAttribute("type", xmi).getValue().compareTo("code:MethodUnit") == 0) {

                nombreMetodo = emt.getAttribute("name").getValue();

                if (emt.getAttribute("export") != null)
                    exportValue = emt.getAttribute("export").getValue();

                atributos = new ArrayList<String>();

                List<Element> hijos = emt.getChildren();

                for (Element hijo : hijos) {

                    if (hijo.getAttribute("type", xmi) != null) {

                        if (hijo.getAttribute("type", xmi).getValue().compareTo("code:Signature") == 0) {

                            List<Element> parametros = hijo.getChildren();

                            for (Element parametro : parametros) {

                                if (parametro.getAttribute("kind") == null
                                        || parametro.getAttribute("kind").getValue().compareTo("return") != 0) {
                                    atributos.add(tipos.get(parametro.getAttribute("type").getValue()) + " "
                                            + parametro.getAttributeValue("name"));
                                } else {
                                    tipoRetorno = tipos.get(parametro.getAttribute("type").getValue());
                                }

                            }

                        }
                    } else if (hijo.getAttribute("snippet") != null) {

                        codigoFuente = hijo.getAttribute("snippet").getValue();

                    }

                }

                //System.out.println("MethodUnit!! " + emt.getName()+" "+emt.getAttribute("type",xmi)+" "+emt.getAttribute("name").getValue());
                //System.out.println(emt.getAttribute("name").getValue());

                if (tipoRetorno.compareTo("Void") == 0) {
                    tipoRetorno = "void";
                }

                contentInBytes = ("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (")
                        .getBytes();

                fout.write(contentInBytes);
                fout.flush();
                int n = 0;
                for (String parametro : atributos) {

                    if (atributos.size() > 0 && n < atributos.size() - 1) {
                        contentInBytes = (" " + parametro + ",").getBytes();
                    } else {
                        contentInBytes = (" " + parametro).getBytes();
                    }

                    fout.write(contentInBytes);
                    fout.flush();
                    n++;
                }

                contentInBytes = (" ) {\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                contentInBytes = ("\n/* \n " + codigoFuente + " \n */\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                contentInBytes = ("\t}\n\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                System.out.print("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (");
                n = 0;
                for (String parametro : atributos) {
                    if (atributos.size() > 0 && n < atributos.size() - 1) {
                        System.out.print(" " + parametro + ", ");
                    } else {
                        System.out.print(" " + parametro);
                    }
                    n++;

                }
                System.out.println(" ) {");
                System.out.println("/* \n " + codigoFuente + " \n */");
                System.out.println("\t}\n");
            }

        }

        contentInBytes = ("}\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();
        fout.close();

        XPathExpression<Attribute> xp = XPathFactory.instance().compile("//@*", Filters.attribute(xmi));
        for (Attribute a : xp.evaluate(doc)) {
            a.setName(a.getName().toLowerCase());
        }

        xpath = XPathFactory.instance().compile("//codeElement/@name='testvb.cls'", Filters.element());
        Element emt = xpath.evaluateFirst(doc);
        if (emt != null) {
            System.out.println("XPath has result: " + emt.getName());
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.c4om.autoconf.ulysses.extra.svrlinterpreter.SVRLInterpreterExtractor.java

License:Apache License

/**
 * Constructor/*  www .  j  av a2 s. c  om*/
 * @param document the document where information should be extracted from
 * @param metamodelPathFile TODO
 */
public SVRLInterpreterExtractor(Document document, String metamodelPath) {
    this.document = document;
    xpathFactory = XPathFactory.instance();
    this.metamodelPath = metamodelPath.replace('\\', '/');
}

From source file:com.globalsight.dispatcher.bo.JobTask.java

License:Apache License

private void createTargetFile(JobBO p_job, String[] p_targetSegments) throws IOException {
    OutputStream writer = null;/*w  ww.  ja  va  2  s . com*/
    File fileStorage = CommonDAO.getFileStorage();
    File srcFile = p_job.getSrcFile();
    Account account = DispatcherDAOFactory.getAccountDAO().getAccount(p_job.getAccountId());
    File trgDir = CommonDAO.getFolder(fileStorage, account.getAccountName() + File.separator + p_job.getJobID()
            + File.separator + AppConstants.XLF_TARGET_FOLDER);
    File trgFile = new File(trgDir, srcFile.getName());
    FileUtils.copyFile(srcFile, trgFile);
    String encoding = FileUtil.getEncodingOfXml(trgFile);

    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(p_job.getSrcFile());
        Element root = doc.getRootElement(); // Get root element
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> tuList = expr.evaluate(fileElem.getChild("body", namespace));
        for (int tuIndex = 0, trgIndex = 0; tuIndex < tuList.size()
                && trgIndex < p_targetSegments.length; tuIndex++, trgIndex++) {
            if (p_targetSegments[trgIndex] == null) {
                continue;
            }

            Element elem = (Element) tuList.get(tuIndex);
            Element srcElem = elem.getChild("source", namespace);
            Element trgElem = elem.getChild("target", namespace);
            if (srcElem == null || srcElem.getContentSize() == 0) {
                trgIndex--;
                continue;
            }

            if (trgElem != null) {
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
            } else {
                trgElem = new Element("target", namespace);
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
                elem.addContent(trgElem);
            }

        }

        XMLOutputter xmlOutput = new XMLOutputter();
        Format format = Format.getRawFormat();
        format.setEncoding(encoding);
        writer = new FileOutputStream(trgFile);
        xmlOutput.setFormat(format);
        writeBOM(writer, format.getEncoding());
        xmlOutput.output(doc, writer);
        p_job.setTrgFile(trgFile);
        logger.info("Create Target File: " + trgFile);
    } catch (JDOMException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } catch (IOException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:com.globalsight.dispatcher.controller.TranslateXLFController.java

License:Apache License

private String parseXLF(JobBO p_job, File p_srcFile) {
    if (p_srcFile == null || !p_srcFile.exists())
        return "File not exits.";

    String srcLang, trgLang;//from   www.  j  a v  a 2  s  .c  o  m
    List<String> srcSegments = new ArrayList<String>();

    try {
        SAXBuilder builder = new SAXBuilder();
        Document read_doc = builder.build(p_srcFile);
        // Get Root Element
        Element root = read_doc.getRootElement();
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        // Get Source/Target Language
        srcLang = fileElem.getAttributeValue(XLF_SOURCE_LANGUAGE);
        trgLang = fileElem.getAttributeValue(XLF_TARGET_LANGUAGE);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> list = expr.evaluate(fileElem.getChild("body", namespace));
        for (int i = 0; i < list.size(); i++) {
            Element tuElem = (Element) list.get(i);
            Element srcElem = tuElem.getChild("source", namespace);
            // Get Source Segment 
            if (srcElem != null && srcElem.getContentSize() > 0) {
                String source = getInnerXMLString(srcElem);
                srcSegments.add(source);
            }
        }

        p_job.setSourceLanguage(srcLang);
        p_job.setTargetLanguage(trgLang);
        p_job.setSourceSegments(srcSegments);
    } catch (Exception e) {
        String msg = "Parse XLIFF file error.";
        logger.error(msg, e);
        return msg;
    }

    return null;
}

From source file:com.googlesource.gerrit.plugins.manifest.ManifestUpdater.java

License:Apache License

public List<Project> getProjects() {
    Document doc = manifestXml.getDocument();
    XPathFactory xFactory = XPathFactory.instance();
    String xPathStr = "/manifest/project";
    XPathExpression<Element> prjXPathExpr = xFactory.compile(xPathStr, Filters.element());

    List<Project> projects = new ArrayList<>();
    for (Element element : prjXPathExpr.evaluate(doc)) {
        projects.add(new Project(element));
    }//w  w w  . j ava 2  s.c  o  m
    return projects;
}

From source file:com.izforge.izpack.util.xmlmerge.factory.XPathOperationFactory.java

License:Open Source License

@Override
public Operation getOperation(Element originalElement, Element patchElement) throws AbstractXmlMergeException {
    for (String xPath : m_map.keySet()) {
        XPathExpression<Element> compiledExpression;
        try {/*from   w ww .j  a v  a  2  s .c om*/
            compiledExpression = XPathFactory.instance().compile(xPath, Filters.element());
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException(e.getMessage(), e);
        }
        if (matches(originalElement, compiledExpression) || matches(patchElement, compiledExpression)) {
            return m_map.get(xPath);
        }
    }
    return m_defaultOperation;
}

From source file:com.kingmed.dp.ndp.impl.NDPServeResponseHandler.java

protected List<Element> checkStatus(String responseBody, String expression) throws JDOMException, IOException {
    List<Element> items = null;
    Reader reader = new StringReader(responseBody);
    SAXBuilder builder = new SAXBuilder();
    Document jdomDoc = null;/*from w  w w.j a v  a  2 s  . c  o m*/
    jdomDoc = builder.build(reader);
    XPathFactory xFactory = XPathFactory.instance();
    XPathExpression<Element> expr = xFactory.compile(expression, Filters.element());
    items = expr.evaluate(jdomDoc);
    return items;
}