Example usage for org.jdom2 Element getAttribute

List of usage examples for org.jdom2 Element getAttribute

Introduction

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

Prototype

public Attribute getAttribute(final String attname) 

Source Link

Document

This returns the attribute for this element with the given name and within no namespace, or null if no such attribute exists.

Usage

From source file:com.sun.syndication.io.impl.RSS20Parser.java

License:Open Source License

public boolean isMyType(Document document) {
    boolean ok;/*from w ww  . j  a  va  2 s.  c  o  m*/
    Element rssRoot = document.getRootElement();
    ok = rssRoot.getName().equals("rss");
    if (ok) {
        ok = false;
        Attribute version = rssRoot.getAttribute("version");
        if (version != null) {
            // At this point, as far ROME is concerned RSS 2.0, 2.00 and 
            // 2.0.X are all the same, so let's use startsWith for leniency.
            ok = version.getValue().startsWith(getRSSVersion());
        }
    }
    return ok;
}

From source file:com.tactfactory.harmony.dependencies.android.sdk.AndroidSDKManager.java

License:Open Source License

/**
 * Find the latest SDK Tools link.//  w  w w.j av a 2s  .co  m
 * 
 * @param platform The user platform
 * @return The latest SDK tools link
 */
public final String findLatestSDKToolsLink(final String platform) {
    String result = null;

    Document document = XMLUtils.getRemoteXML(SDK_URL + XML_REPO_FILE);
    Element root = document.getRootElement();
    Namespace ns = root.getNamespace("sdk");

    Element sdkTool = root.getChild("tool", ns);
    List<Element> sdkArchives = sdkTool.getChild("archives", ns).getChildren();

    for (Element sdkArchive : sdkArchives) {
        if (sdkArchive.getAttribute("os").getValue().equals(platform)) {
            result = SDK_URL + sdkArchive.getChildText("url", ns);
        }
    }

    return result;
}

From source file:com.tactfactory.harmony.platform.winphone.updater.XmlProjectWinphone.java

License:Open Source License

private void removeIfExists(Element element, String type, String file) {
    Filter<Element> filter = new ElementFilter(type);
    List<Element> content = element.getContent(filter);
    List<Element> elementToDelete = new ArrayList<>();

    for (Element node : content) {
        if (node.getAttribute("Include").getValue().equals(file)) {
            elementToDelete.add(node);//from   www  . j a v  a2 s  . com
        }
    }

    for (Element node : elementToDelete) {
        element.removeContent(node);
    }
}

From source file:com.tactfactory.harmony.ProjectContext.java

License:Open Source License

/**
 * Extract Project Name from configuration file.
 *
 * @param config Configuration file/*from w  w  w.  ja va 2  s  .c  o m*/
 * @return Project Name Space
 */
public static void loadProjectNameFromConfig(final File config) {
    String result = null;
    SAXBuilder builder;
    Document doc;

    if (config.exists()) {
        // Make engine
        builder = new SAXBuilder();
        try {
            // Load XML File
            doc = builder.build(config);
            // Load Root element
            final Element rootNode = doc.getRootElement();
            result = rootNode.getAttribute("name").getValue();
        } catch (final JDOMException e) {
            ConsoleUtils.displayError(e);
        } catch (final IOException e) {
            ConsoleUtils.displayError(e);
        }
    }

    if (result != null) {
        ApplicationMetadata.INSTANCE.setName(result.trim());
    }
}

From source file:com.thoughtworks.go.config.ConfigCipherUpdater.java

License:Apache License

public void migrate() {
    File cipherFile = systemEnvironment.getDESCipherFile();
    String timestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(timeProvider.currentTime());

    File backupCipherFile = new File(systemEnvironment.getConfigDir(), "cipher.original." + timestamp);
    File configFile = new File(systemEnvironment.getCruiseConfigFile());
    File backupConfigFile = new File(configFile.getParentFile(),
            configFile.getName() + ".original." + timestamp);
    try {//from  w  w w  . jav a  2  s.  co  m
        if (!cipherFile.exists() || !FileUtils.readFileToString(cipherFile, UTF_8).equals(FLAWED_VALUE)) {
            return;
        }
        LOGGER.info("Found unsafe cipher {} on server, Go will make an attempt to rekey", FLAWED_VALUE);
        FileUtils.copyFile(cipherFile, backupCipherFile);
        LOGGER.info("Old cipher was successfully backed up to {}", backupCipherFile.getAbsoluteFile());
        FileUtils.copyFile(configFile, backupConfigFile);
        LOGGER.info("Old config was successfully backed up to {}", backupConfigFile.getAbsoluteFile());

        String oldCipher = FileUtils.readFileToString(backupCipherFile, UTF_8);
        new DESCipherProvider(systemEnvironment).resetCipher();

        String newCipher = FileUtils.readFileToString(cipherFile, UTF_8);

        if (newCipher.equals(oldCipher)) {
            LOGGER.warn("Unable to generate a new safe cipher. Your cipher is unsafe.");
            FileUtils.deleteQuietly(backupCipherFile);
            FileUtils.deleteQuietly(backupConfigFile);
            return;
        }
        Document document = new SAXBuilder().build(configFile);
        List<String> encryptedAttributes = Arrays.asList("encryptedPassword", "encryptedManagerPassword");
        List<String> encryptedNodes = Arrays.asList("encryptedValue");
        XPathFactory xPathFactory = XPathFactory.instance();
        for (String attributeName : encryptedAttributes) {
            XPathExpression<Element> xpathExpression = xPathFactory
                    .compile(String.format("//*[@%s]", attributeName), Filters.element());
            List<Element> encryptedPasswordElements = xpathExpression.evaluate(document);
            for (Element element : encryptedPasswordElements) {
                Attribute encryptedPassword = element.getAttribute(attributeName);
                encryptedPassword.setValue(reEncryptUsingNewKey(decodeHex(oldCipher), decodeHex(newCipher),
                        encryptedPassword.getValue()));
                LOGGER.debug("Replaced encrypted value at {}", element.toString());
            }
        }
        for (String nodeName : encryptedNodes) {
            XPathExpression<Element> xpathExpression = xPathFactory.compile(String.format("//%s", nodeName),
                    Filters.element());
            List<Element> encryptedNode = xpathExpression.evaluate(document);
            for (Element element : encryptedNode) {
                element.setText(
                        reEncryptUsingNewKey(decodeHex(oldCipher), decodeHex(newCipher), element.getValue()));
                LOGGER.debug("Replaced encrypted value at {}", element.toString());
            }
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(configFile)) {
            XmlUtils.writeXml(document, fileOutputStream);
        }
        LOGGER.info("Successfully re-encrypted config");
    } catch (Exception e) {
        LOGGER.error("Re-keying of cipher failed with error: [{}]", e.getMessage(), e);
        if (backupCipherFile.exists()) {
            try {
                FileUtils.copyFile(backupCipherFile, cipherFile);
            } catch (IOException e1) {
                LOGGER.error(
                        "Could not replace the cipher file [{}] with original one [{}], please do so manually. Error: [{}]",
                        cipherFile.getAbsolutePath(), backupCipherFile.getAbsolutePath(), e.getMessage(), e);
                bomb(e1);
            }
        }
    }
}

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

License:Apache License

public String getAttribute(Element e, String attribute) {
    Attribute attr = e.getAttribute(attribute);
    if (attr == null) {
        throw bomb("Error finding attribute '" + attribute + "' in config: " + configFile + elementOutput(e));
    }//from  w  ww.j  a va  2  s  .  co  m
    return attr.getValue();
}

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

License:Apache License

public boolean hasAttribute(Element e, String attribute) {
    return e.getAttribute(attribute) != null;
}

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 {//  w w  w  .ja v  a2s  . com
        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);/* w w w . j a  v  a  2 s .  c  om*/
            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 w  w . ja v  a2s .c  o m*/
    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;
                }
            }
        }

    }
}