Example usage for org.jdom2 Element getChild

List of usage examples for org.jdom2 Element getChild

Introduction

In this page you can find the example usage for org.jdom2 Element getChild.

Prototype

public Element getChild(final String cname) 

Source Link

Document

This returns the first child element within this element with the given local name and belonging to no namespace.

Usage

From source file:com.thoughtworks.go.util.SvnLogXmlParser.java

License:Apache License

private Modification parseLogEntry(Element logEntry, String path) throws ParseException {
    Element logEntryPaths = logEntry.getChild("paths");
    if (logEntryPaths == null) {
        /* Path-based access control forbids us from learning
         * details of this log entry, so skip it. */
        return null;
    }//w w  w .  ja v a2s .  c o  m

    Date modifiedTime = convertDate(logEntry.getChildText("date"));
    String author = logEntry.getChildText("author");
    String comment = logEntry.getChildText("msg");
    String revision = logEntry.getAttributeValue("revision");

    Modification modification = new Modification(author, comment, null, modifiedTime, revision);

    List paths = logEntryPaths.getChildren("path");
    for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
        Element node = (Element) iterator.next();
        if (underPath(path, node.getText())) {
            ModifiedAction action = convertAction(node.getAttributeValue("action"));
            modification.createModifiedFile(node.getText(), null, action);
        }
    }

    return modification;
}

From source file:com.thoughtworks.go.util.SvnLogXmlParser.java

License:Apache License

public HashMap<String, String> parseInfoToGetUUID(String output, String queryURL, SAXBuilder builder) {
    HashMap<String, String> uidToUrlMap = new HashMap<>();
    try {//from  w  w w.jav  a  2 s .c  om
        Document document = builder.build(new StringReader(output));
        Element root = document.getRootElement();
        List<Element> entries = root.getChildren("entry");
        for (Element entry : entries) {
            uidToUrlMap.put(queryURL, entry.getChild("repository").getChild("uuid").getValue());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return uidToUrlMap;
}

From source file:com.versionmaintain.files.LastVersionInfosParser.java

License:Apache License

public List<VersionInfo> getVersionInfo() {
    SAXBuilder builder = new SAXBuilder();
    List<VersionInfo> infos = new ArrayList<VersionInfo>();
    try {//from w ww .j  a v a 2s  . c o m
        Document doc = builder.build(new File(System.getProperty("user.dir") + File.separator + FILE_NAME));
        Element root = doc.getRootElement();
        List<Element> softEles = root.getChildren("software");
        for (Element softEle : softEles) {
            String appName = softEle.getAttribute("name").getValue();
            String versionCode = softEle.getChildText("latest-version-code");
            String versionName = softEle.getChildText("latest-version");

            Element detailEles = softEle.getChild("latest-version-detail");
            List<Element> detailItemEles = detailEles.getChildren("item");
            List<VersionInfoDetail> details = new ArrayList<VersionInfoDetail>();
            for (Element detailItem : detailItemEles) {
                String title = detailItem.getAttributeValue("name");
                List<Element> detailEleList = detailItem.getChildren("detail");
                List<String> detailList = new ArrayList<String>();
                for (Element detailEle : detailEleList) {
                    String strDetail = detailEle.getText();
                    detailList.add(strDetail);
                }
                details.add(new VersionInfoDetail(title, detailList));
            }

            VersionInfo versionInfo = new VersionInfo();
            versionInfo.setAppName(appName);
            versionInfo.setVersion(versionName);
            versionInfo.setVersionCode(Integer.parseInt(versionCode));
            versionInfo.setDetails(details);
            infos.add(versionInfo);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return infos;
}

From source file:com.webfront.app.utils.PDFImporter.java

@Override
public void doImport(BufferedReader reader) throws IOException, ParseException {
    PDFTextStripper pdfStripper = new PDFTextStripper();
    BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(fileName));
    try (PDDocument document = PDDocument.load(inStream)) {
        txtOutput = pdfStripper.getText(document);
        try (FileWriter writer = new FileWriter(cfg.getTmpDir() + cfg.getFileSep() + "pdfOut.txt")) {
            writer.write(txtOutput);/*from   w ww. j a v a  2 s. c o m*/
            writer.close();
            txtReader = new BufferedReader(new FileReader(cfg.getTmpDir() + cfg.getFileSep() + "pdfOut.txt"));
            String text = "";
            while (text != null) {
                text = txtReader.readLine();
                buffer.put(currentLine++, text);
            }
        }
        getConfig();
        currentLine = 0;
        Element root = xmlDoc.getRootElement();
        int maxLines = buffer.size() - 3;
        int markedLine = 0;
        // Scan the output and mark the start of each section
        for (Element el : root.getChildren()) {
            for (Element section : el.getChildren()) {
                String sectionName = section.getAttributeValue("content");
                Element startElement = section.getChild("start");
                Element endElement = section.getChild("end");
                if (startElement != null) {
                    boolean endHasBounds = true;
                    if (endElement.getAttribute("bounded") != null) {
                        String bounds = endElement.getAttributeValue("bounded");
                        if (bounds.equals("false")) {
                            endHasBounds = false;
                        }
                    }
                    Pattern linePattern = Pattern.compile(startElement.getText());
                    String text = "";
                    boolean elementFound = false;
                    while (currentLine < maxLines) {
                        text = buffer.get(currentLine++);
                        if (linePattern.matcher(text).matches()) {
                            markedLine = currentLine - 1;
                            markers.put(sectionName, markedLine);
                            elementFound = true;
                            if (!endHasBounds) {
                                currentLine--;
                            }
                            break;
                        }
                    }
                    if (!elementFound) {
                        currentLine = markedLine;
                    }
                }
            }
        }

        ArrayList<Integer> lineNumbers = new ArrayList<>(markers.values());
        lineNumbers.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
        sectionMarks = new TreeSet(markers.values());
        currentLine = 0;
        for (Element element : root.getChildren()) {
            int lines = 0;
            if (element.getAttribute("lines") != null) {
                lines = element.getAttribute("lines").getIntValue();
            }
            for (Element section : element.getChildren()) {
                String contentDesc;
                contentDesc = (section.getAttribute("content") == null ? ""
                        : section.getAttributeValue("content"));
                if (markers.containsKey(contentDesc)) {
                    currentLine = markers.get(contentDesc);
                    processSection(section);
                }
            }
        }
    } catch (DataConversionException ex) {
        Logger.getLogger(PDFImporter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ElementNotFoundException ex) {
        Logger.getLogger(PDFImporter.class.getName()).log(Level.SEVERE, null, ex);
    }
    entries.sort(LedgerEntry.LedgerComparator);
    for (LedgerEntry item : entries) {
        java.util.Date date = new java.util.Date(DateConvertor.toLong(item.getDate(), "MM/dd/yyyy"));
        String amountString = item.getAmount();
        boolean isCredit = true;
        if (item.getAmount().startsWith("-")) {
            isCredit = false;
            String amt = item.getAmount().replaceFirst("-", "");
            item.setAmount(amt);
        }
        float amount = Float.parseFloat(amountString);
        if (isCredit) {
            lastBalance += amount;
            totalDeposits += amount;
        } else {
            lastBalance -= amount;
            totalWithdrawals += amount;
        }
        Ledger ledger = new Ledger(null, date, amount, lastBalance, accountId);
        if (item.getDescription().length() > 120) {
            item.setDescription(item.getDescription().substring(0, 119));
        }
        if (item.getCheckNumber() != null && !item.getCheckNumber().isEmpty()) {
            ledger.setCheckNum(item.getCheckNumber());
            totalChecks -= amount;
        }
        ledger.setTransDesc(item.getDescription());
        getItemList().add(ledger);
    }
}

From source file:com.webfront.app.utils.PDFImporter.java

public void processSection(Element section) throws ElementNotFoundException {
    String name = section.getName();
    boolean hasEntry = false;
    String contentDesc = (section.getAttribute("content") == null ? "" : section.getAttributeValue("content"));
    int lines = 1;
    int maxLines = 0;
    int linesProcessed = 0;
    boolean endHasBounds = true;
    Element startElement = section.getChild("start");
    Element endElement = section.getChild("end");
    Element dataDefinition = section.getChild("data");
    Element lineDefinition = section.getChild("line");
    Pattern dataPattern = null;//from w ww  .  j ava 2s. c  om
    Pattern linePattern = null;
    String transType = (section.getAttribute("type") == null ? "info" : section.getAttributeValue("type"));
    String prevLine = "";
    int nextSection = buffer.size() - 1;
    if (sectionMarks.higher(currentLine) != null) {
        nextSection = (int) sectionMarks.higher(currentLine);
    }

    if (startElement.getAttributeValue("lines") != null) {
        lines = Integer.parseInt(startElement.getAttributeValue("lines"));
        currentLine += lines;
    }
    if (lineDefinition != null) {
        linePattern = Pattern.compile(lineDefinition.getText());
        if (lineDefinition.getAttribute("lines") != null) {
            String l = lineDefinition.getAttributeValue("lines");
            if (!l.equals("+")) {
                maxLines = Integer.parseInt(lineDefinition.getAttributeValue("lines"));
            }
        }
    }
    if (endElement.getAttribute("bounded") != null) {
        String bounds = endElement.getAttributeValue("bounded");
        if (bounds.equals("false")) {
            endHasBounds = false;
        }
    }
    Pattern endPattern = Pattern.compile(endElement.getText());
    while (currentLine < nextSection) {
        prevLine = buffer.get(currentLine - 1);
        String text = buffer.get(currentLine++);
        Matcher lineMatcher = null;
        if (lineDefinition != null) {
            lineMatcher = linePattern.matcher(text);
        }
        Matcher endMatcher = endPattern.matcher(text);
        if (endMatcher.matches()) {
            if (!endHasBounds) {
                currentLine -= 1;
            }
            break;
        } else {
            if (currentLine >= buffer.size()) {
                throw new ElementNotFoundException("Not found");
            }
        }
        if (lineMatcher != null && lineMatcher.matches()) {
            if (!contentDesc.equals("discard")) {
                //                    System.out.println(text);
            }
            hasEntry = false;
            if (dataDefinition != null) {
                LedgerEntry entry = new LedgerEntry();
                for (Element dataLine : dataDefinition.getChildren()) {
                    String tag = dataLine.getAttributeValue("content");
                    String regex = dataLine.getText();
                    Matcher matcher = Pattern.compile(regex).matcher(text);
                    String value = "";
                    if (matcher.find()) {
                        value = matcher.group();
                    }
                    switch (tag) {
                    case "beginningBalance":
                        beginningBalance = Float.parseFloat(value.replaceAll(",", ""));
                        break;
                    case "totalDeposits":
                        value.replaceAll(",", "");
                        totalDeposits = Float.parseFloat(value.replaceAll(",", ""));
                        break;
                    case "totalWithdrawals":
                        value.replaceAll(",", "");
                        totalWithdrawals = Float.parseFloat(value.replaceAll(",", ""));
                        break;
                    case "endingBalance":
                        value.replaceAll(",", "");
                        endingBalance = Float.parseFloat(value.replaceAll(",", ""));
                        break;
                    case "accountNumber":
                        summary.put("accountNumber", value);
                        break;
                    case "periodFrom":
                        summary.put("startDate", value);
                        break;
                    case "periodTo":
                        summary.put("endDate", value);
                        break;
                    case "date":
                        entry.setDate(value);
                        text = matcher.replaceFirst("");
                        break;
                    case "check":
                        entry.setCheckNumber(value);
                        break;
                    case "amount":
                        if (transType.equals("debit")) {
                            value = "-" + value;
                        }
                        entry.setAmount(value);
                        text = matcher.replaceFirst("");
                        if (section.getAttributeValue("content").equals("fees")) {
                            String amt = entry.getAmount();
                            amt = amt.replaceAll("-", "");
                            amt = amt.replaceAll(",", "");
                            totalFees += Float.parseFloat(amt);
                        }
                        break;
                    case "description":
                        entry.setDescription(value);
                        break;
                    }
                }
                if (maxLines > 0 && ++linesProcessed == maxLines) {
                    return;
                }
                if (!contentDesc.equals("dailyBalance") && !contentDesc.endsWith("Info")) {
                    entries.add(entry);
                    hasEntry = true;
                }
            }
        } else {
            if (linePattern.matcher(prevLine).matches() && hasEntry) {
                if (!contentDesc.equals("dailyBalance")) {
                    int lastEntry = entries.size() - 1;
                    LedgerEntry entry = entries.get(lastEntry);
                    entry.setDescription(entry.getDescription() + " " + text);
                    entries.set(lastEntry, entry);
                    hasEntry = false;
                }
            }
        }

    }
}

From source file:com.webfront.app.utils.PDFImporter.java

private void getConfig() {
    jdomBuilder = new SAXBuilder();
    String xmlSource = cfg.getInstallDir() + cfg.getFileSep() + "pnc.xml";
    try {//from  w w w .  j  a v  a  2  s .c  om
        xmlDoc = jdomBuilder.build(xmlSource);
        Element root = xmlDoc.getRootElement();
        List<Content> configContent = root.getContent();
        List<Element> childElements = root.getChildren();
        Element header = root.getChild("header");
        for (Element e : header.getChildren()) {
            String content = e.getAttributeValue("content");
            String format = e.getAttributeValue("format");
            String text = e.getText();
        }
    } catch (JDOMException ex) {
        Logger.getLogger(PDFImporter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PDFImporter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.webfront.model.Config.java

public void getConfig() {
    jdomBuilder = new SAXBuilder();
    try {//from  w w  w .j a  v  a2  s . c  om
        xmlDoc = jdomBuilder.build(getInstallDir() + getFileSep() + configFileName);
        Element docRoot = xmlDoc.getRootElement();
        Element systemNode = docRoot.getChild("system");
        installDir = systemNode.getChildText("installDir");
        tmpDir = systemNode.getChildText("tmpDir");
    } catch (FileNotFoundException ex) {
        //Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JDOMException ex) {
        Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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'.//from  w  w w.java2  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'.
 *//*from w ww .  ja v  a 2  s . co m*/
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:computeBase.ParseDataset.java

public List<IAtomContainer> getStructs() {
    //On cre une List contenant tous les noeuds "etudiant" de l'Element racine

    List listDrugs = drugs.getChildren("drug");

    float logp = 0;
    String smiles = "";
    String name;/*from  w w  w  .j  av  a  2s .  c  o m*/
    String cas;

    DrugStruct tmpDrug;
    int good = 0;
    int bad = 0;
    //On cre un Iterator sur notre liste
    Iterator itDrug = listDrugs.iterator();
    while (itDrug.hasNext()) {
        Element drug = (Element) itDrug.next();

        name = drug.getChild("name").getText();
        cas = drug.getChild("cas-number").getText();

        List listExpProp = drug.getChild("experimental-properties").getChildren("property");

        Iterator itExpProp = listExpProp.iterator();
        while (itExpProp.hasNext()) {
            Element expProp = (Element) itExpProp.next();

            if (expProp.getChild("kind").getText().equals("logP")) {
                logp = Float.parseFloat(expProp.getChild("value").getText());
            }
        }

        List listCalcProp = drug.getChild("calculated-properties").getChildren("property");

        Iterator itCalcProp = listCalcProp.iterator();
        while (itCalcProp.hasNext()) {
            Element calcProp = (Element) itCalcProp.next();

            if (calcProp.getChild("kind").getText().equals("SMILES")) {
                smiles = calcProp.getChild("value").getText();
            }
        }
        try {
            tmpDrug = new DrugStruct(smiles, logp, name, cas);
            ListDrug.add(tmpDrug.drug);
            good++;
        } catch (CDKException e) {
            System.out.println("---BUG--- " + name + " -- " + cas + " -- " + smiles + " -- " + logp);
            bad++;
        }
        System.out.println(good + "/" + bad);
    }
    return ListDrug;
}