Example usage for org.jdom2.xpath XPathFactory compile

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

Introduction

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

Prototype

public <T> XPathExpression<T> compile(String expression, Filter<T> filter) 

Source Link

Document

Create a XPathExpression<T> instance from this factory.

Usage

From source file:com.xebialabs.overcast.support.libvirt.jdom.FilesystemXml.java

License:Apache License

public static void removeFilesystemsWithTarget(Document domainXml, String targetDir) {
    XPathFactory xpf = XPathFactory.instance();
    XPathExpression<Element> fsExpr = xpf.compile(
            String.format("/domain/devices/filesystem[@type='mount']/target[@dir='%s']", targetDir),
            Filters.element());/*  w ww.j  a va  2  s  .  c o  m*/
    List<Element> tfs = fsExpr.evaluate(domainXml);
    for (Element e : tfs) {
        e.getParentElement().getParentElement().removeContent(e.getParentElement());
    }
}

From source file:com.xebialabs.overcast.support.libvirt.jdom.FilesystemXml.java

License:Apache License

/**
 * Get map of {@link Filesystem}s. The key in the map is the target inside the domain. This will only return
 * filesystems of type 'mount'.//  w  w  w  .  j av  a 2  s .c  o  m
 */
public static Map<String, Filesystem> getFilesystems(Document domainXml) {
    Map<String, Filesystem> ret = Maps.newHashMap();
    XPathFactory xpf = XPathFactory.instance();
    XPathExpression<Element> fsExpr = xpf.compile(XPATH_FILESYSTEM, Filters.element());
    List<Element> filesystems = fsExpr.evaluate(domainXml);
    for (Element fs : filesystems) {
        Attribute accessMode = fs.getAttribute("accessmode");
        String source = fs.getChild("source").getAttribute("dir").getValue();
        String target = fs.getChild("target").getAttribute("dir").getValue();
        boolean readOnly = fs.getChild("readonly") != null;

        ret.put(target, new Filesystem(source, target,
                AccessMode.valueOf(accessMode.getValue().toUpperCase(Locale.US)), readOnly));
    }
    return ret;
}

From source file:com.xebialabs.overcast.support.libvirt.jdom.InterfaceXml.java

License:Apache License

/**
 * Get a map of mac addresses of interfaces defined on the domain. This is somewhat limited at the moment. It is
 * assumed that only one network interface with mac is connected to a bridge or network. For instance if you have a
 * bridged network device connected to 'br0' then you will find it's MAC address with the key 'br0'.
 *//*w w  w . ja va  2  s. c om*/
public static Map<String, String> getMacs(Document domainXml) {
    Map<String, String> macs = Maps.newHashMap();
    XPathFactory xpf = XPathFactory.instance();
    XPathExpression<Element> interfaces = xpf.compile("/domain/devices/interface", Filters.element());
    for (Element iface : interfaces.evaluate(domainXml)) {
        String interfaceType = iface.getAttribute("type").getValue();
        logger.debug("Detecting IP on network of type '{}'", interfaceType);
        if ("bridge".equals(interfaceType)) {
            Element macElement = iface.getChild("mac");
            String mac = macElement.getAttribute("address").getValue();
            Element sourceElement = iface.getChild("source");
            String bridge = sourceElement.getAttribute("bridge").getValue();
            logger.info("Detected MAC '{}' on bridge '{}'", mac, bridge);
            macs.put(bridge, mac);
        } else if ("network".equals(interfaceType)) {
            Element macElement = iface.getChild("mac");
            String mac = macElement.getAttribute("address").getValue();
            Element sourceElement = iface.getChild("source");
            String network = sourceElement.getAttribute("network").getValue();
            logger.info("Detected MAC '{}' on network '{}'", mac, network);
            macs.put(network, mac);
        } else {
            logger.warn("Ignoring network of type {}", interfaceType);
        }
    }
    return macs;
}

From source file:displayclient.DownloadManager.java

License:Open Source License

@Override
public void run() {
    int updateInterval = Integer.parseInt(DisplayClient.prop.getProperty("CollectInterval"));
    log.log(Level.INFO, "Run. Collection Interval = {0}", updateInterval);

    while (running) {
        // Update thread limits and updateInterval incase they changed on
        // instruction from the CMS
        this.numThreadsLimit = Integer.parseInt(DisplayClient.prop.getProperty("MaxConcurrentDownloads"));
        updateInterval = Integer.parseInt(DisplayClient.prop.getProperty("CollectInterval"));

        String response = "";
        try {/*from w w w  . j  a v a 2  s  . co m*/
            response = this.DC.XMDS.RequiredFiles(DisplayClient.prop.getProperty("ServerKey"),
                    DisplayClient.prop.getProperty("HardwareKey"));
            log.log(Level.FINE, "DownloadManager: xmds.requiredFiles => {0}", response);
        } catch (Exception ex) {
            log.log(Level.FINEST, "DownloadManager: xmds.requiredFiles => {0}", response);
            log.log(Level.WARNING, "DownloadManager: Could not connect to XMDS at {0}",
                    DisplayClient.prop.getProperty("ServerUri"));
            log.log(Level.WARNING, "DownloadManager: xmds.requiredFiles => {0}", ex);
            continue;
        }

        Document doc;
        Iterator iter;

        if (!response.equals("")) {
            // Code here to parse the returned XML
            SAXBuilder sb = new SAXBuilder();

            try {
                doc = sb.build(new StringReader(response));

                // Build an iterator over the files section of the response
                XPathFactory xFactory = XPathFactory.instance();

                XPathExpression<Element> expr = xFactory.compile("//file", Filters.element());
                List<Element> files = expr.evaluate(doc);
                for (Element n : files) {

                    FileFetcher f = null;

                    if (n.getAttributeValue("download").equalsIgnoreCase("http")) {
                        f = new HttpFileFetcher(this, n);
                    } else {
                        f = new XmdsFileFetcher(this, n);
                    }

                    Boolean skip = false;

                    // Check to see if there is already a download
                    // running for this file ID. If there is, skip it.
                    for (FileFetcher tmp : runningDownloads) {
                        try {
                            if (f.getID() == tmp.getID()) {
                                skip = true;
                                log.log(Level.FINEST,
                                        "DownloadManager: FileFetcher {0} is still running from previous collection. Skipping.",
                                        f.getID());
                            }
                        } catch (NullPointerException e) {
                            // The download completed while we were testing for it.
                            // Ignore it.
                            skip = true;
                        }
                    }

                    if (!skip) {
                        f.start();
                        this.runningDownloads.add(f);
                        this.numThreads++;
                    }

                    while (this.numThreads >= (this.numThreadsLimit - 1)) {
                        // Thread throttling
                        // Sleep until there is a spare space for a new thread.
                        try {
                            log.log(Level.FINE, "DownloadManager: {0} downloads in progress. Sleeping.",
                                    this.numThreadsLimit);
                            sleep(5000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
            } catch (JDOMException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Make sure updateInterval is sane.
        if (updateInterval < 30) {
            updateInterval = 30;
        }

        // Sleep for "updateInterval" seconds before trying again.
        try {
            sleep(updateInterval * 1000);
        } catch (InterruptedException e) {
        }
    }
}

From source file:elh.eus.absa.CorpusReader.java

License:Open Source License

private void extractOpinionsAbsaSemEval2014(InputStream fileName) {
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    try {/*from  ww  w  .  j  a v  a  2  s .c om*/
        Document doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);
        Integer sId = 0; //sentence id
        Integer oId = 0; //opinion id         
        for (Element sent : sentences) {
            sId++;
            StringBuilder sb = new StringBuilder();
            String sentString = sent.getChildText("text");
            sb = sb.append(sentString);
            Element aspectTerms = sent.getChild("aspectTerms");
            if (aspectTerms != null) {
                List<Element> aspectTermList = aspectTerms.getChildren();
                for (Element aspectElem : aspectTermList) {
                    oId++;
                    String trgt = aspectElem.getAttributeValue("target");
                    Integer offsetFrom = Integer.parseInt(aspectElem.getAttributeValue("from"));
                    Integer offsetTo = Integer.parseInt(aspectElem.getAttributeValue("to"));
                    String polarity = aspectElem.getAttributeValue("polarity");
                    //String cat = aspectElem.getAttributeValue("category");

                    //create and add opinion to the structure
                    Opinion op = new Opinion("o" + oId, trgt, offsetFrom, offsetTo, polarity, null, "s" + sId);
                    this.addOpinion(op);
                }

                //System.out.println(sb.toString());
            }
        }
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}

From source file:elh.eus.absa.CorpusReader.java

License:Open Source License

/**
 * Read semeval-absa 2015 shared task formatted corpus and extract opinions.
 * //from  w w  w . j  a va 2  s. c  o m
 * @param InputStream fileName: corpus 
 * @param boolean nullSentOps: whether null opinions should be created for sentence with no opinion
 *                              (only used for semeval-absa 2015 formatted corpora)
 * 
 */
private void extractOpinionsAbsaSemEval2015(InputStream fileName, boolean nullSentenceOps) {
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    try {
        Document doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);
        String rId = "";
        String sId = ""; //sentence id
        Integer oId = 0; //opinion id
        for (Element sent : sentences) {
            sId = sent.getAttributeValue("id");
            rId = sId.replaceAll(":[0-9]+$", "");

            if (rId.equalsIgnoreCase(sId)) {
                rId = sId.replaceAll("#[0-9]+$", "");
            }

            //store the sentence and the corresponding review
            addRevSent(rId, sId);
            StringBuilder sb = new StringBuilder();
            String sentString = sent.getChildText("text");
            //add sentence to the reader object
            this.addSentence(sId, sentString);

            sb = sb.append(sentString);
            Element opinions = sent.getChild("Opinions");
            if (opinions != null) {
                List<Element> opinionList = opinions.getChildren();
                //there is no opinions
                if (opinionList.isEmpty()) {
                    //System.err.println("kkkkk");
                    //create sentence at list, even if it has no opinion elements
                    sId = sent.getAttributeValue("id");
                    addRevSent(rId, sId);
                    String sentStr = sent.getChildText("text");
                    //add sentence to the reader object
                    this.addSentence(sId, sentStr);
                    if (nullSentenceOps) {
                        oId++;
                        //create and add opinion to the structure
                        Opinion op = new Opinion("o" + oId, "NULL", 0, 0, "NULL", "NULL", sId);
                        this.addOpinion(op);
                    }
                }

                for (Element opElem : opinionList) {
                    oId++;
                    String trgt = opElem.getAttributeValue("target");
                    Integer offsetFrom = 0;
                    Integer offsetTo = 0;
                    try {
                        offsetFrom = Integer.parseInt(opElem.getAttributeValue("from"));
                        offsetTo = Integer.parseInt(opElem.getAttributeValue("to"));

                    } catch (NumberFormatException ne) {
                    }
                    String polarity = opElem.getAttributeValue("polarity");
                    String cat = opElem.getAttributeValue("category");

                    //create and add opinion to the structure
                    Opinion op = new Opinion("o" + oId, trgt, offsetFrom, offsetTo, polarity, cat, sId);
                    this.addOpinion(op);

                    //debugging
                    sb.append("\n\t> " + "o" + oId + " " + trgt + " " + offsetFrom + "-" + offsetTo + " "
                            + polarity + " " + cat);
                }
                //System.out.println(sb.toString());
            } else {
                //System.err.println("kkkkk");
                //create sentence at list, even if it has no opinion elements
                sId = sent.getAttributeValue("id");
                addRevSent(rId, sId);
                String sentStr = sent.getChildText("text");
                //add sentence to the reader object
                this.addSentence(sId, sentStr);
                if (nullSentenceOps) {
                    oId++;
                    //create and add opinion to the structure
                    Opinion op = new Opinion("o" + oId, "NULL", 0, 0, "NULL", "NULL", sId);
                    this.addOpinion(op);
                }
            }
        }
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}

From source file:elh.eus.absa.CorpusReader.java

License:Open Source License

/**
 *    Extract sentence texts from tabulated format. The function assumes the text is PoS tagged in
 *  Conll tabulated format./*from  w  w  w  .j  av  a 2 s  .c o  m*/
 * 
 * @param fileName string: input corpus file path
 */
private void extractOpinionsTabText(InputStream fileName) {
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    try {
        Document doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);
        String rId = "";
        String sId = ""; //sentence id
        Integer oId = 0; //opinion id
        for (Element sent : sentences) {
            sId = sent.getAttributeValue("id");
            rId = sId;
            oId++;

            /*store the sentence and the corresponding review
             * (in this case this info is redundant, because a whole review is represented by a sentence)  
             */
            addRevSent(rId, sId);
            //StringBuilder sb = new StringBuilder();
            String sentString = sent.getChildText("text");
            //add sentence to the reader object
            this.addSentence(sId, sentString);

            String polarity = sent.getAttributeValue("polarity");
            if (polarity == null) {
                System.err.println("no polarity annotation for review " + rId + "."
                        + " Review won't be taken into account");
                continue;
            }

            String trgt = "";
            String cat = "global";
            Integer offsetFrom = 0;
            Integer offsetTo = 0;

            //create and add opinion to the structure
            Opinion op = new Opinion("o" + oId, trgt, offsetFrom, offsetTo, polarity, cat, sId);
            this.addOpinion(op);

            //debugging
            //sb.append("\n\t> "+"o"+oId+" "+trgt+" "+offsetFrom+"-"+offsetTo+" "+polarity+" "+cat);
        }
        //System.out.println(sentString);         
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}

From source file:es.ehu.si.ixa.pipe.convert.Convert.java

License:Apache License

public void absaSemEvalToNER(String fileName) {
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    try {//from   w w w .  ja  va  2 s .  c  o m
        Document doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);
        for (Element sent : sentences) {

            StringBuilder sb = new StringBuilder();
            String sentString = sent.getChildText("text");
            sb = sb.append(sentString);
            Element aspectTerms = sent.getChild("aspectTerms");
            if (aspectTerms != null) {
                List<List<Integer>> offsetList = new ArrayList<List<Integer>>();
                List<Integer> offsets = new ArrayList<Integer>();
                List<Element> aspectTermList = aspectTerms.getChildren();
                if (!aspectTermList.isEmpty()) {
                    for (Element aspectElem : aspectTermList) {
                        Integer offsetFrom = Integer.parseInt(aspectElem.getAttributeValue("from"));
                        Integer offsetTo = Integer.parseInt(aspectElem.getAttributeValue("to"));
                        offsets.add(offsetFrom);
                        offsets.add(offsetTo);
                    }
                }
                Collections.sort(offsets);
                for (int i = 0; i < offsets.size(); i++) {
                    List<Integer> offsetArray = new ArrayList<Integer>();
                    offsetArray.add(offsets.get(i++));
                    if (offsets.size() > i) {
                        offsetArray.add(offsets.get(i));
                    }
                    offsetList.add(offsetArray);
                }
                int counter = 0;
                for (List<Integer> offsetSent : offsetList) {
                    Integer offsetFrom = offsetSent.get(0);
                    Integer offsetTo = offsetSent.get(1);
                    String aspectString = sentString.substring(offsetFrom, offsetTo);
                    sb.replace(offsetFrom + counter, offsetTo + counter,
                            "<START:term> " + aspectString + " <END>");
                    counter += 19;
                }
            }
            System.out.println(sb.toString());
        }
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}

From source file:es.ehu.si.ixa.pipe.convert.Convert.java

License:Apache License

public void absaSemEvalToNER2015(String fileName) {
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    try {//from  www .ja  v a  2  s .c  om
        Document doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);
        for (Element sent : sentences) {

            String sentString = sent.getChildText("text");
            StringBuilder sb = new StringBuilder();
            sb = sb.append(sentString);
            Element opinionsElement = sent.getChild("Opinions");
            if (opinionsElement != null) {
                List<List<Integer>> offsetList = new ArrayList<List<Integer>>();
                List<Integer> offsets = new ArrayList<Integer>();
                List<Element> oteList = opinionsElement.getChildren();
                for (Element aspectElem : oteList) {
                    if (!aspectElem.getAttributeValue("target").equals("NULL")) {
                        Integer offsetFrom = Integer.parseInt(aspectElem.getAttributeValue("from"));
                        Integer offsetTo = Integer.parseInt(aspectElem.getAttributeValue("to"));
                        offsets.add(offsetFrom);
                        offsets.add(offsetTo);
                    }
                }
                List<Integer> offsetsWithoutDuplicates = new ArrayList<Integer>(new HashSet<Integer>(offsets));
                Collections.sort(offsetsWithoutDuplicates);

                for (int i = 0; i < offsetsWithoutDuplicates.size(); i++) {
                    List<Integer> offsetArray = new ArrayList<Integer>();
                    offsetArray.add(offsetsWithoutDuplicates.get(i++));
                    if (offsetsWithoutDuplicates.size() > i) {
                        offsetArray.add(offsetsWithoutDuplicates.get(i));
                    }
                    offsetList.add(offsetArray);
                }
                int counter = 0;
                for (List<Integer> offsetSent : offsetList) {
                    Integer offsetFrom = offsetSent.get(0);
                    Integer offsetTo = offsetSent.get(1);
                    String aspectString = sentString.substring(offsetFrom, offsetTo);
                    sb.replace(offsetFrom + counter, offsetTo + counter,
                            "<START:target> " + aspectString + " <END>");
                    counter += 21;
                }
                System.out.println(sb.toString());
            }
        }
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}

From source file:es.ehu.si.ixa.pipe.convert.Convert.java

License:Apache License

public void absaSemEvalToMultiClassNER2015(String fileName) {
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    try {/*ww  w  .j a v  a  2s .com*/
        Document doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);
        for (Element sent : sentences) {

            String sentString = sent.getChildText("text");
            StringBuilder sb = new StringBuilder();
            sb = sb.append(sentString);
            Element opinionsElement = sent.getChild("Opinions");
            if (opinionsElement != null) {
                List<List<Integer>> offsetList = new ArrayList<List<Integer>>();
                HashSet<String> targetClassSet = new LinkedHashSet<String>();
                List<Integer> offsets = new ArrayList<Integer>();
                List<Element> opinionList = opinionsElement.getChildren();
                for (Element opinion : opinionList) {
                    if (!opinion.getAttributeValue("target").equals("NULL")) {
                        String className = opinion.getAttributeValue("category");
                        String targetString = opinion.getAttributeValue("target");
                        Integer offsetFrom = Integer.parseInt(opinion.getAttributeValue("from"));
                        Integer offsetTo = Integer.parseInt(opinion.getAttributeValue("to"));
                        offsets.add(offsetFrom);
                        offsets.add(offsetTo);
                        targetClassSet.add(targetString + "JAR!" + className + opinion.getAttributeValue("from")
                                + opinion.getAttributeValue("to"));
                    }
                }
                List<Integer> offsetsWithoutDuplicates = new ArrayList<Integer>(new HashSet<Integer>(offsets));
                Collections.sort(offsetsWithoutDuplicates);
                List<String> targetClassList = new ArrayList<String>(targetClassSet);

                for (int i = 0; i < offsetsWithoutDuplicates.size(); i++) {
                    List<Integer> offsetArray = new ArrayList<Integer>();
                    offsetArray.add(offsetsWithoutDuplicates.get(i++));
                    if (offsetsWithoutDuplicates.size() > i) {
                        offsetArray.add(offsetsWithoutDuplicates.get(i));
                    }
                    offsetList.add(offsetArray);
                }
                int counter = 0;
                for (int i = 0; i < offsetList.size(); i++) {
                    Integer offsetFrom = offsetList.get(i).get(0);
                    Integer offsetTo = offsetList.get(i).get(1);
                    String className = targetClassList.get(i);
                    String aspectString = sentString.substring(offsetFrom, offsetTo);
                    sb.replace(offsetFrom + counter, offsetTo + counter, "<START:"
                            + className.split("JAR!")[1].substring(0, 3) + "> " + aspectString + " <END>");
                    counter += 18;
                }
                System.out.println(sb.toString());
            }
        }
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }
}