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:fullyMeshedNet.FullyMeshedNet.java

License:Open Source License

public FullyMeshedNet(File xmlfile, int popid) {
    // loads properties
    super(xmlfile);

    // load actual data (from CEA2D now)

    // get population root node
    Document doc = SafeSAX.read(xmlfile, true);
    Node dpopulations = doc.selectSingleNode("/frevo/populations");
    List<?> npops = dpopulations.selectNodes(".//population");
    Node pop = (Node) npops.get(popid);

    List<?> nets = pop.selectNodes("./*");

    // return the one with the highest fitness
    int bestID = 0;
    Node net = (Node) nets.get(bestID);
    String fitnessString = net.valueOf("./@fitness");
    double bestfitness = Double.parseDouble(fitnessString);

    for (int i = 1; i < nets.size(); i++) {
        net = (Node) nets.get(i);
        fitnessString = net.valueOf("./@fitness");
        double fitness = Double.parseDouble(fitnessString);
        if (fitness > bestfitness) {
            bestID = i;//w  w w .j  av  a2s  .c  om
            bestfitness = fitness;
        }
    }

    //loadFromXML((Node)nets.get(0));
    loadFromXML((Node) nets.get(bestID));
}

From source file:gg.imports.GrisbiFile050.java

License:Open Source License

/**
 * Imports the categories into the embedded database
 * @param p Progress handle for the progress bar
 * @param expectedNumberOfCategories Expected number of categories: the number of imported categories should be equal to this number
 * @throws ParsingException//w ww. j  av a  2s  .co  m
 * <UL>
 * <LI>If there is a problem finding the needed nodes</LI>
 * <LI>If the number of imported categories is not equal to the number of categories defined in the Grisbi file</LI>
 * </UL>
 * @throws NumberFormatException If a string is read when a number is expected
 */
private void importCategories(ProgressHandle p, int expectedNumberOfCategories)
        throws ParsingException, NumberFormatException {
    log.entering(this.getClass().getName(), "importCategories");
    long startImportingCategoriesTime = System.currentTimeMillis();

    // Save system categories in the embedded database
    Datamodel.saveCategory(Category.TRANSFER);
    Datamodel.saveCategory(Category.BREAKDOWN_OF_TRANSACTIONS);
    Datamodel.saveCategory(Category.NO_CATEGORY);

    // Import the categories from the Grisbi file into the embedded database
    int numberOfImportedCategories = 0;
    List listOfCategories = grisbiFileDocument
            .selectNodes("/Grisbi/Categories/Detail_des_categories/Categorie");
    Iterator categoriesIterator = listOfCategories.iterator();
    while (categoriesIterator.hasNext() && !isImportCancelled()) { // Go through the list of categories written in the Grisbi file
        // Get the current category node
        Node categoryNode = (Node) categoriesIterator.next();

        // Get the ID and the name of the current category
        String categoryIdValue = categoryNode.valueOf("@No");
        assert (categoryIdValue != null);
        long categoryId = Long.parseLong(categoryIdValue); // Get the ID of the category
        assert (categoryId > 0);
        String categoryName = categoryNode.valueOf("@Nom"); // Get the name of the category
        assert (categoryName != null);

        // Create a new category and save it in the embedded database
        Category category = new Category(categoryId, 0L, categoryName, null, false); // There is no sub-category - the field "grisbi_sub_category_id" is set to 0
        Datamodel.saveCategory(category);

        // Import the sub-categories into the database
        List listOfSubCategories = categoryNode.selectNodes("Sous-categorie");
        Iterator subCategoriesIterator = listOfSubCategories.iterator();
        while (subCategoriesIterator.hasNext() && !isImportCancelled()) { // Go through the list of sub-categories of the current category
            // Get the current sub-category node
            Node subCategoryNode = (Node) subCategoriesIterator.next();

            // Get the ID and the name of the current sub-category
            String subCategoryIdValue = subCategoryNode.valueOf("@No");
            assert (subCategoryIdValue != null);
            long subCategoryId = Long.parseLong(subCategoryIdValue); // Get the ID of the sub-category
            assert (subCategoryId > 0);
            String subCategoryName = subCategoryNode.valueOf("@Nom"); // Get the name of the sub-category
            assert (subCategoryName != null);

            // Create a new sub-category and save it in the embedded database
            Category subCategory = new Category(categoryId, subCategoryId, subCategoryName, category, false);
            Datamodel.saveCategory(subCategory);
        }

        // For each category, save an empty sub-category
        Category noSubCategory = new Category(categoryId, Category.NO_SUB_CATEGORY_ID, "No sub-category",
                category, false);
        Datamodel.saveCategory(noSubCategory);

        numberOfImportedCategories++;
        p.progress(workUnit++);
    }

    // Make sure that all categories have been imported
    if (!isImportCancelled() && numberOfImportedCategories != expectedNumberOfCategories) {
        throw new ParsingException("The number of imported categories (" + numberOfImportedCategories
                + ") is not equal to the expected number of categories (" + expectedNumberOfCategories
                + ") written in the Grisbi file '" + pathToGrisbiFile + "'");
    }

    long endImportingCategoriesTime = System.currentTimeMillis();
    log.info(numberOfImportedCategories + " categories have been successfully imported in "
            + (endImportingCategoriesTime - startImportingCategoriesTime) + " ms");
    log.exiting(this.getClass().getName(), "importCategories");
}

From source file:gg.imports.GrisbiFile050.java

License:Open Source License

/**
 * Imports the transactions into the embedded database<BR/>
 * The methods <CODE>importCurrencies()</CODE>, <CODE>importPayees()</CODE>,
 * <CODE>importAccounts()</CODE>, and <CODE>importCategories()</CODE> have to be called before
 * @param p Progress handle for the progress bar
 * @throws ParsingException If there is a problem finding the needed nodes
 * @throws NumberFormatException If a string is read when a number is expected
 * @throws DateFormatException If the date format of a transaction is invalid
 *///  w w w  .j  a  va 2s  .  c om
private void importTransactions(ProgressHandle p)
        throws ParsingException, NumberFormatException, DateFormatException {
    log.entering(this.getClass().getName(), "importTransactions");
    long startImportingTotalTransactionsTime = System.currentTimeMillis();

    Map<Long, Account> accounts = Datamodel.getAccountsWithId();
    Map<Long, Payee> payees = Datamodel.getPayeesWithId();
    Map<GrisbiCategory, Category> categories = Datamodel.getCategoriesWithGrisbiCategory();
    Map<Long, Currency> currencies = Datamodel.getCurrenciesWithId();

    // Import the transactions from each account into the embedded database
    long totalNumberOfImportedTransactions = 0;
    List listOfAccounts = grisbiFileDocument.selectNodes("/Grisbi/Comptes/Compte");
    Iterator accountsIterator = listOfAccounts.iterator();
    while (accountsIterator.hasNext() && !isImportCancelled()) { // Go through the accounts
        long startImportingTransactionsTime = System.currentTimeMillis();

        // Get the account's node
        Node accountNode = (Node) accountsIterator.next();
        assert (accountNode != null);

        // Get the ID of the account
        Node accountIdNode = accountNode.selectSingleNode("Details/No_de_compte");
        assert (accountIdNode != null);
        String accountIdValue = accountIdNode.getStringValue();
        assert (accountIdValue != null);
        long accountId = Long.parseLong(accountIdValue);
        assert (accountId >= 0);

        // Get the name of the current account
        Node accountNameNode = accountNode.selectSingleNode("Details/Nom");
        assert (accountNameNode != null);
        String accountName = accountNameNode.getStringValue();
        assert (accountName != null);

        // Display on the progress bar the account from which transactions are imported
        p.progress("Importing transactions from " + accountName);

        // Get the corresponding Account object
        Account account = accounts.get(accountId);
        assert (account != null);

        // Get the expected number of transactions of the account
        Node expectedNumberOfTransactionsNode = accountNode.selectSingleNode("Details/Nb_operations");
        if (expectedNumberOfTransactionsNode == null) {
            throw new ParsingException(
                    "The expected number of transactions has not been found for the account '" + accountName
                            + "' in the Grisbi file '" + pathToGrisbiFile + "'");
        }
        String expectedNumberOfTransactionsValue = expectedNumberOfTransactionsNode.getStringValue();
        assert (expectedNumberOfTransactionsValue != null);
        int expectedNumberOfTransactions = Integer.parseInt(expectedNumberOfTransactionsValue);

        // Import the transactions of the account into the embedded database
        int numberOfImportedTransactions = 0;
        Map<Long, Transaction> transactions = new HashMap<Long, Transaction>(); // Map containing all the saved transactions - the key of the map is the transaction's ID
        List listOfTransactions = accountNode.selectNodes("Detail_des_operations/Operation");
        Iterator transactionsIterator = listOfTransactions.iterator();
        while (transactionsIterator.hasNext() && !isImportCancelled()) { // Go through the list of transactions of the account

            // Get the transaction node
            Node transactionNode = (Node) transactionsIterator.next();

            // Get the ID of the transaction
            assert (transactionNode != null);
            String transactionIdValue = transactionNode.valueOf("@No");
            assert (transactionIdValue != null);
            long transactionId = Long.parseLong(transactionIdValue);
            assert (transactionId > 0);

            // Get the date of the transaction
            String transactionDateValue = transactionNode.valueOf("@D");
            assert (transactionDateValue != null && transactionDateValue.compareTo("") != 0);
            // Get the date from the string
            LocalDate transactionDate = Period.getDate(transactionDateValue); // Throws a DateFormatException if the format of 'transactionDateValue' is not valid
            assert (transactionDate != null);

            // Get the exchange rate
            String exchangeRateValue = transactionNode.valueOf("@Tc");
            assert (exchangeRateValue != null);
            BigDecimal exchangeRate = new BigDecimal(exchangeRateValue.replace(',', '.')); // exchangeRate = 0 if there is no echange rate

            // Get the fees
            String feesValue = transactionNode.valueOf("@Fc");
            assert (feesValue != null);
            BigDecimal fees = new BigDecimal(feesValue.replace(',', '.'));

            // Get the amount of the transaction
            String transactionAmountValue = transactionNode.valueOf("@M");
            assert (transactionAmountValue != null);
            BigDecimal transactionAmount = new BigDecimal(transactionAmountValue.replace(',', '.'));

            // Get the currency of the transaction
            String transactionCurrencyIdValue = transactionNode.valueOf("@De");
            assert (transactionCurrencyIdValue != null);
            long transactionCurrencyId = Long.parseLong(transactionCurrencyIdValue); // Get the ID of the currency
            Currency transactionCurrency = currencies.get(transactionCurrencyId);
            assert (transactionCurrency != null);
            Currency accountCurrency = currencies.get(account.getCurrency().getId());
            assert (accountCurrency != null);

            // Update the amount of the transaction if the currency of the transaction is different from the currency of the account
            // (Method found in the Grisbi source file: devises.c/calcule_montant_devise_renvoi)
            if (transactionCurrency.getId().compareTo(accountCurrency.getId()) != 0) {
                if (accountCurrency.getEuroConversion()) {
                    if (transactionCurrency.getName().compareToIgnoreCase("euro") == 0) {
                        transactionAmount = transactionAmount.multiply(accountCurrency.getExchangeRate());
                    }
                } else if (accountCurrency.getEuroConversion()
                        && transactionCurrency.getName().compareToIgnoreCase("euro") != 0) {
                    transactionAmount = transactionAmount.divide(transactionCurrency.getExchangeRate(),
                            RoundingMode.HALF_EVEN);
                } else {
                    if (exchangeRate.compareTo(BigDecimal.ZERO) != 0) {
                        String transactionRdcValue = transactionNode.valueOf("@Rdc");
                        assert (transactionRdcValue != null);
                        long transactionRdc = Long.parseLong(transactionRdcValue);

                        if (transactionRdc == 1) {
                            transactionAmount = (transactionAmount.divide(exchangeRate, RoundingMode.HALF_EVEN))
                                    .subtract(fees);
                        } else {
                            transactionAmount = (transactionAmount.multiply(exchangeRate)).subtract(fees);
                        }
                    } else if (transactionCurrency.getExchangeRate().compareTo(BigDecimal.ZERO) != 0) {
                        if (transactionCurrency.getMultiply()) {
                            transactionAmount = (transactionAmount
                                    .multiply(transactionCurrency.getExchangeRate())).subtract(fees);
                        } else {
                            transactionAmount = (transactionAmount.divide(transactionCurrency.getExchangeRate(),
                                    RoundingMode.HALF_EVEN)).subtract(fees);
                        }
                    } else {
                        transactionAmount = new BigDecimal(0);
                    }
                }
            }
            transactionAmount = transactionAmount.setScale(2, RoundingMode.HALF_EVEN);

            // If the current transaction is a transfer:
            String twinTransaction = transactionNode.valueOf("@Ro"); // Twin transaction
            assert (twinTransaction != null);
            String accountOfTransfer = transactionNode.valueOf("@Rc"); // Account where the amount has been transfered (account of the twin transaction)
            assert (accountOfTransfer != null);

            // Is the current transaction a breakdown of transactions?
            String breakdownOfTransaction = transactionNode.valueOf("@Ov"); // breakdownOfTransaction = 1 if the current trasnsaction is a breakdown of transactions
            assert (breakdownOfTransaction != null);

            // Get the category and the sub-category of the transaction
            String transactionGrisbiCategoryIdValue = transactionNode.valueOf("@C"); // Get the category ID ('0' means that the category is not defined)
            assert (transactionGrisbiCategoryIdValue != null);
            long transactionGrisbiCategoryId = Long.parseLong(transactionGrisbiCategoryIdValue);
            assert (transactionGrisbiCategoryId >= 0);

            String transactionGrisbiSubCategoryIdValue = transactionNode.valueOf("@Sc"); // Get the sub-category ID ('0' means that the sub-category is not defined)
            assert (transactionGrisbiSubCategoryIdValue != null);
            long transactionGrisbiSubCategoryId = Long.parseLong(transactionGrisbiSubCategoryIdValue);
            assert (transactionGrisbiSubCategoryId >= 0);

            // Check if the category is "Transfer" or "Breakdown of transactions"
            Category transactionCategory = null;
            GrisbiCategory transactionGrisbiCategory = new GrisbiCategory(0, 0);
            if (transactionGrisbiCategoryId == 0
                    && (twinTransaction.compareTo("0") != 0 || accountOfTransfer.compareTo("0") != 0)) {
                // The current transaction is a transfer
                transactionCategory = Category.TRANSFER;
            } else if (transactionGrisbiCategoryId == 0 && breakdownOfTransaction.compareTo("1") == 0) {
                // The current transaction is a breakdown of transactions
                transactionCategory = Category.BREAKDOWN_OF_TRANSACTIONS;
            } else if (transactionGrisbiSubCategoryId != 0) {
                transactionGrisbiCategory.setCategoryId(transactionGrisbiCategoryId);
                transactionGrisbiCategory.setSubCategoryId(transactionGrisbiSubCategoryId);
                transactionCategory = categories.get(transactionGrisbiCategory);
                assert (transactionCategory != null);
            } else if (transactionGrisbiCategoryId != 0) {
                // Else, if a category is defined, get the category
                transactionGrisbiCategory.setCategoryId(transactionGrisbiCategoryId);
                transactionGrisbiCategory.setSubCategoryId(Category.NO_SUB_CATEGORY_ID);
                transactionCategory = categories.get(transactionGrisbiCategory);
                assert (transactionCategory != null);
            } else {
                // Else, no category is defined
                transactionCategory = Category.NO_CATEGORY;
            }
            assert (transactionCategory != null);

            // Get the comment of the transaction
            String transactionComment = transactionNode.valueOf("@N");
            assert (transactionComment != null);

            // Get the payee of the transaction
            String transactionPayeeIdValue = transactionNode.valueOf("@T"); // 'transactionPayeeIdValue' contains '0' if no payee is defined
            assert (transactionPayeeIdValue != null);
            long transactionPayeeId = Long.parseLong(transactionPayeeIdValue);
            assert (transactionPayeeId >= 0);
            Payee transactionPayee = null;
            if (transactionPayeeId != 0) { // Get the payee if it has been defined
                transactionPayee = payees.get(transactionPayeeId);
                assert (transactionPayee != null);
            } else { // No payee has been defined
                transactionPayee = Payee.NO_PAYEE;
            }

            // Get the parent transaction
            String transactionParentIdValue = transactionNode.valueOf("@Va"); // '0' means that the transaction is a top-transaction ; not '0' means that the transaction is a sub-transaction
            assert (transactionParentIdValue != null);
            long transactionParentId = Long.parseLong(transactionParentIdValue);
            assert (transactionParentId >= 0);
            Transaction transactionParent = null;
            if (transactionParentId != 0) {
                // Get the parent transaction
                transactionParent = transactions.get(transactionParentId); // 'transactionParentId' is the ID of the parent transaction (in Grisbi files, parent transactions are always BEFORE sub-transactions)
                assert (transactionParent != null);
            } else {
                // The current transaction has no parent transaction
                // The current transaction is a top transaction
                transactionParent = null;
            }

            // Create a new transaction and save the transaction in the embedded database
            Transaction transaction = new Transaction(transactionDate, account, transactionAmount,
                    transactionCategory, transactionComment, transactionPayee, transactionParent);
            Datamodel.saveTransaction(transaction);
            transactions.put(transactionId, transaction); // Save the transaction in the map, so that parent transactions can be found

            numberOfImportedTransactions++;
            p.progress(workUnit++);
        }

        // Make sure that the number of imported transactions and sub-transactions is the expected number
        if (!isImportCancelled() && numberOfImportedTransactions != expectedNumberOfTransactions) {
            throw new ParsingException("For the account '" + accountName
                    + "', the number of imported transactions (" + numberOfImportedTransactions
                    + ") is not equal to the expected number of transactions (" + expectedNumberOfTransactions
                    + ") in the Grisbi file '" + pathToGrisbiFile + "'");
        }

        long endImportingTransactionsTime = System.currentTimeMillis();
        log.info(numberOfImportedTransactions + " transactions have been successfully imported in the account '"
                + accountName + "' in " + (endImportingTransactionsTime - startImportingTransactionsTime)
                + " ms");
        totalNumberOfImportedTransactions += numberOfImportedTransactions;
    }

    long endImportingTotalTransactionsTime = System.currentTimeMillis();
    log.info(totalNumberOfImportedTransactions + " transactions have been successfully imported in "
            + (endImportingTotalTransactionsTime - startImportingTotalTransactionsTime) + " ms");
    log.exiting(this.getClass().getName(), "importTransactions");
}

From source file:GnuCash.Transaction.java

License:Open Source License

static void addTransactions(Vector<Transaction> transactions, Node n, String account_id) {
    List<Node> NL = n.selectNodes("trn:splits[trn:split[split:account='" + account_id + "']]/trn:split");

    for (int i = 0; i < NL.size(); i++) {

        Transaction t = new Transaction();
        t.description = n.selectSingleNode("trn:description").getText();
        t.currency_id = n.selectSingleNode("trn:currency/cmdty:id").getText();
        t.date = getDateValue(n.selectSingleNode("trn:date-posted/ts:date").getText());

        t.value = getDoubleValue(NL.get(i).selectSingleNode("split:value").getText());

        if (NL.get(i).selectSingleNode("split:account[@type='guid']").getText().equals(account_id)) {
            t.quantity = getDoubleValue(NL.get(i).selectSingleNode("split:quantity").getText());
        }/*from  ww  w.j av  a  2s .c  o  m*/

        transactions.add(t);
    }
}

From source file:io.mashin.oep.hpdl.XMLReadUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
public static void initPropertiesCollectionFrom(PropertyElementCollection pec, Node node, String groupXPath,
        String propertyXPath) {/*from   w w w .  j ava  2 s  .c o m*/
    List<Node> subNodes = null;
    if (groupXPath != null && !groupXPath.isEmpty()) {
        if (node.selectSingleNode(groupXPath) != null) {
            subNodes = node.selectSingleNode(groupXPath).selectNodes(propertyXPath);
        }
    } else {
        subNodes = node.selectNodes(propertyXPath);
    }

    if (subNodes != null) {
        for (Node subNode : subNodes) {
            PropertyPropertyElement pe = (PropertyPropertyElement) pec.createAndAdd();
            pe.setValueOfName(XMLReadUtils.valueOf("./name", subNode));
            pe.setValueOfValue(XMLReadUtils.valueOf("./value", subNode));
            pe.setValueOfDescription(XMLReadUtils.valueOf("./description", subNode));
        }
    }
}

From source file:io.mashin.oep.hpdl.XMLReadUtils.java

License:Open Source License

public static PropertyElementCollection propertiesCollectionFrom(Node node, String xpath,
        PropertyElementCollection pec) {
    @SuppressWarnings("unchecked")
    List<Node> subNodes = node.selectNodes(xpath);
    if (subNodes != null) {
        for (Node subNode : subNodes) {
            initPropertyPropertyElementFrom((PropertyPropertyElement) pec.createAndAdd(), subNode);
        }//from   w w w.jav  a2 s.  c o m
    }
    return pec;
}

From source file:io.mashin.oep.hpdl.XMLReadUtils.java

License:Open Source License

public static void initCredentialsCollectionFrom(PropertyElementCollection pec, Node node, String groupXPath,
        String childXPath) {//from   w w  w . java  2 s  .c  o  m
    Node groupNode = node.selectSingleNode(groupXPath);
    if (groupNode != null) {
        @SuppressWarnings("unchecked")
        List<Node> subNodes = groupNode.selectNodes(childXPath);
        if (subNodes != null) {
            for (Node subNode : subNodes) {
                CredentialPropertyElement cpe = (CredentialPropertyElement) pec.createAndAdd();
                cpe.setValueOfName(valueOf("@name", subNode));
                cpe.setValueOfType(valueOf("@type", subNode));
                initPropertiesCollectionFrom(cpe.credential, subNode, null, "./property");
            }
        }
    }
}

From source file:io.mashin.oep.hpdl.XMLReadUtils.java

License:Open Source License

public static PropertyElementCollection credentialsCollectionFrom(Node element, String xpath,
        PropertyElementCollection pec) {
    @SuppressWarnings("unchecked")
    List<Node> nodes = element.selectNodes(xpath);
    if (nodes != null) {
        for (Node node : nodes) {
            initCredentialPropertyElementFrom((CredentialPropertyElement) pec.createAndAdd(), node,
                    pec.getCategory());//from   ww  w .  ja va 2  s . com
        }
    }
    return pec;
}

From source file:io.mashin.oep.hpdl.XMLReadUtils.java

License:Open Source License

public static void initTextCollectionFrom(PropertyElementCollection pec, Node node, String xpath) {
    @SuppressWarnings("unchecked")
    List<Node> subNodes = node.selectNodes(xpath);
    if (subNodes != null) {
        for (Node subNode : subNodes) {
            TextPropertyElement tpe = (TextPropertyElement) pec.createAndAdd();
            tpe.setStringValue(valueOf(subNode));
        }//  w  w  w . j ava2  s  . c  o  m
    }
}

From source file:io.mashin.oep.hpdl.XMLReadUtils.java

License:Open Source License

public static void initTextCollectionFromAttribute(PropertyElementCollection pec, Node node, String xpath,
        String attributeXPath) {/* w w w .j a  v a 2s  .c  o m*/
    @SuppressWarnings("unchecked")
    List<Node> subNodes = node.selectNodes(xpath);
    if (subNodes != null) {
        for (Node subNode : subNodes) {
            TextPropertyElement tpe = (TextPropertyElement) pec.createAndAdd();
            tpe.setStringValue(valueOf(attributeXPath, subNode));
        }
    }
}