Example usage for org.dom4j Node valueOf

List of usage examples for org.dom4j Node valueOf

Introduction

In this page you can find the example usage for org.dom4j Node valueOf.

Prototype

String valueOf(String xpathExpression);

Source Link

Document

valueOf evaluates an XPath expression and returns the textual representation of the results the XPath string-value of this node.

Usage

From source file:fullyMeshedNet.FullyMeshedNet.java

License:Open Source License

public FullyMeshedNet loadFromXML(Node nd) {
    try {/*from w  w w  .j  ava 2  s . c o m*/
        // Add properties
        loadProperties();

        // set generator
        generator = new NESRandom(FrevoMain.getSeed());

        String fitnessString = nd.valueOf("./@fitness");
        if (!fitnessString.isEmpty()) {
            this.setFitness(Double.parseDouble(fitnessString));
        }

        this.input_nodes = Integer.parseInt(nd.valueOf("./@input_nodes"));
        this.output_nodes = Integer.parseInt(nd.valueOf("./@output_nodes"));
        this.nodes = Integer.parseInt(nd.valueOf("./@nodes"));
        this.weight_range = Float.parseFloat(nd.valueOf("./@weight_range"));
        this.bias_range = Float.parseFloat(nd.valueOf("./@bias_range"));
        this.random_bias_range = Float.parseFloat(nd.valueOf("./@random_bias_range"));
        this.random_source = Boolean.parseBoolean(nd.valueOf("./@random_source"));

        this.variable_mutation_rate = Boolean.parseBoolean(nd.valueOf("./@variable_mutation_rate"));
        if (variable_mutation_rate)
            this.mutationRate = Float.parseFloat(nd.valueOf("./@mutation_rate"));

        this.activationFunction = ActivationFunction.valueOf(nd.valueOf("./@activation_function"));

        this.activation = new float[this.nodes];
        this.output = new float[this.nodes];
        this.bias = new float[this.nodes];
        this.randombias = new float[this.nodes];
        this.weight = new float[this.nodes][this.nodes];

        Node dnodes = nd.selectSingleNode("./nodes");
        for (int nr = this.input_nodes; nr < this.nodes; nr++) {
            Node curnode = dnodes.selectSingleNode("./node[@nr='" + nr + "']");
            if (curnode == null)
                throw new IllegalArgumentException("CompleteNetwork: node tags inconsistent!"
                        + "\ncheck 'nr' attributes and nodes count in nnetwork!");
            this.bias[nr] = Float.parseFloat(curnode.valueOf("./bias"));
            if (random_source) {
                this.randombias[nr] = Float.parseFloat(curnode.valueOf("./randombias"));
            }

            Node dweights = curnode.selectSingleNode("./weights");
            for (int from = 0; from < this.nodes; from++) {
                String ws = dweights.valueOf("./weight[@from='" + from + "']");
                if (ws.length() == 0)
                    throw new IllegalArgumentException("CompleteNetwork: weight tags inconsistent!"
                            + "\ncheck 'from' attributes and nodes count in nnetwork!");
                float val = Float.parseFloat(ws);
                this.weight[from][nr] = val;
            }
        }
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("CompleteNetwork: NumberFormatException! Check XML File");
    }
    return this;
}

From source file:gg.imports.GrisbiFile050.java

License:Open Source License

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

    // Save default payee in the database
    Datamodel.savePayee(Payee.NO_PAYEE); // This constant is used to search the transactions for which no payee is defined

    // Import the payees from the Grisbi file into the embedded database
    int numberOfImportedPayees = 0;
    List listOfPayees = grisbiFileDocument.selectNodes("/Grisbi/Tiers/Detail_des_tiers/Tiers");
    Iterator payeesIterator = listOfPayees.iterator();
    while (payeesIterator.hasNext() && !isImportCancelled()) { // Go through the list of payees found in the Grisbi XML file
        // Get the current payee node
        Node payeeNode = (Node) payeesIterator.next();

        // Get the ID and the name of the current payee
        String payeeIdValue = payeeNode.valueOf("@No");
        assert (payeeIdValue != null);
        long payeeId = Long.parseLong(payeeIdValue);
        assert (payeeId > 0);
        String payeeName = payeeNode.valueOf("@Nom");
        assert (payeeName != null);

        // Create a new payee and save it in the embedded database
        Payee payee = new Payee(payeeId, payeeName, false);
        Datamodel.savePayee(payee);

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

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

    long endImportingPayeesTime = System.currentTimeMillis();
    log.info(numberOfImportedPayees + " payees have been successfully imported in "
            + (endImportingPayeesTime - startImportingPayeesTime) + " ms");
    log.exiting(this.getClass().getName(), "importPayees");
}

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//from   ww  w . j  a  va  2  s . c o 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 currencies into the database
 * @param p Progress handle for the progress bar
 * @param expectedNumberOfCurrencies Expected number of currencies: the number of imported currencies should be equal to this number
 * @throws ParsingException//from  w  w  w  . ja  v  a 2  s . com
 * <UL>
 * <LI>If there is a problem finding the needed nodes</LI>
 * <LI>If the number of imported currencies is not equal to the number of currencies defined in the Grisbi file</LI>
 * </UL>
 * @throws NumberFormatException If a string is read when a number is expected
 */
private void importCurrencies(ProgressHandle p, int expectedNumberOfCurrencies)
        throws ParsingException, NumberFormatException {
    log.entering(this.getClass().getName(), "importCurrencies");
    long startImportingCurrenciesTime = System.currentTimeMillis();

    // Import the currencies into the embedded database
    int numberOfImportedCurrencies = 0;
    List listOfCurrencies = grisbiFileDocument.selectNodes("/Grisbi/Devises/Detail_des_devises/Devise");
    Iterator currenciesIterator = listOfCurrencies.iterator();
    while (currenciesIterator.hasNext() && !isImportCancelled()) { // Go through the list of currencies
        // Get the current currency node
        Node currencyNode = (Node) currenciesIterator.next();

        // Get the ID, the name and the ISO code of the current currency
        String currencyIdValue = currencyNode.valueOf("@No");
        assert (currencyIdValue != null);
        long currencyId = Long.parseLong(currencyIdValue); // Get the ID of the currency
        assert (currencyId > 0);
        String currencyName = currencyNode.valueOf("@Nom"); // Get the name of the currency
        assert (currencyName != null);
        String currencyCode = currencyNode.valueOf("@Code"); // Get the code of the currency
        assert (currencyCode != null);
        String currencyIsoCode = currencyNode.valueOf("@IsoCode"); // Get the code ISO of the currency
        assert (currencyIsoCode != null);
        String currencyExchangeRateValue = currencyNode.valueOf("@Change"); // Get the exchange rate of the currency
        assert (currencyExchangeRateValue != null);
        BigDecimal currencyExchangeRate = new BigDecimal(currencyExchangeRateValue.replace(',', '.'));
        String currencyRelation = currencyNode.valueOf("@Rapport_entre_devises");
        assert (currencyRelation != null);
        boolean currencyMultiply = (currencyRelation.compareTo("1") == 0);
        String euroConversionValue = currencyNode.valueOf("@Passage_euro");
        assert (euroConversionValue != null);
        boolean currencyEuroConversion = (euroConversionValue.compareTo("1") == 0);

        // Create a new currency and save the currency in the database
        // By default the currencies are not active
        // When the accounts are imported, the currencies are activated
        Currency currency = new Currency(currencyId, currencyName, currencyCode, currencyIsoCode,
                new BigDecimal(0), new BigDecimal(0), currencyExchangeRate, currencyMultiply,
                currencyEuroConversion, false);
        Datamodel.saveCurrency(currency);

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

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

    long endImportingCurrenciesTime = System.currentTimeMillis();
    log.info(numberOfImportedCurrencies + " currencies have been successfully imported in "
            + (endImportingCurrenciesTime - startImportingCurrenciesTime) + " ms");
    log.exiting(this.getClass().getName(), "importCurrencies");
}

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
 *//*from   ww  w.j  a  v  a 2s. co m*/
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:hebbNet.HebbNet.java

License:Open Source License

@Override
public AbstractRepresentation loadFromXML(Node nd) {
    try {/*from w  w  w  . ja  va  2s.c  om*/
        // Add properties
        loadProperties();
        this.learningrate = Float.parseFloat(nd.valueOf("./@learningrate"));
        this.input_nodes = Integer.parseInt(nd.valueOf("./@input_nodes"));
        this.output_nodes = Integer.parseInt(nd.valueOf("./@output_nodes"));
        this.nodes = Integer.parseInt(nd.valueOf("./@nodes"));
        this.weight_range = Float.parseFloat(nd.valueOf("./@weight_range"));
        this.bias_range = Float.parseFloat(nd.valueOf("./@bias_range"));
        this.activation = new float[this.nodes];
        this.output = new float[this.nodes];
        this.bias = new float[this.nodes];
        this.weight = new float[this.nodes][this.nodes];
        this.plasticity = new float[this.nodes][this.nodes];
        this.currentweight = new float[this.nodes][this.nodes];
        Node dnodes = nd.selectSingleNode("./nodes");
        for (int nr = this.input_nodes; nr < this.nodes; nr++) {
            Node curnode = dnodes.selectSingleNode("./node[@nr='" + nr + "']");
            if (curnode == null)
                throw new IllegalArgumentException("HebbNet: node tags inconsistent!"
                        + "\ncheck 'nr' attributes and nodes count in nnetwork!");
            this.bias[nr] = Float.parseFloat(curnode.valueOf("./bias"));
            Node dweights = curnode.selectSingleNode("./weights");
            for (int from = 0; from < this.nodes; from++) {
                Node thisweight = dweights.selectSingleNode("./weight[@from='" + from + "']");
                float plast = Float.parseFloat(thisweight.valueOf("./@plasticity"));
                float weight = Float.parseFloat(thisweight.valueOf("."));
                this.weight[from][nr] = weight;
                this.plasticity[from][nr] = plast;
            }
        }
        resetWeights();
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("HebbNet: NumberFormatException! Check XML File");
    }
    return this;
}

From source file:hk.hku.cecid.piazza.commons.util.LoggerLog4j.java

License:Open Source License

/**
 * Loads the configuration from the specified url location.
 * A DOM configuration will be triggered if the url ends with ".xml". 
 * /*w  w w. j av a  2 s  .  com*/
 * @param url the url of the configuration source.
 * @throws Exception if the operation is unsuccessful. 
 * @see hk.hku.cecid.piazza.commons.module.PersistentComponent#loading(java.net.URL)
 */
protected void loading(URL url) throws Exception {
    if (url.getPath().toLowerCase().endsWith(".xml")) {
        Properties params = getParameters();
        if (params != null) {
            String checkConfig = params.getProperty("checkConfig");

            if (checkConfig != null) {
                if (checkConfig.equals("true")) {

                    SAXReader xmlReader = new SAXReader();
                    xmlReader.setEntityResolver(new EntityResolver() {
                        public InputSource resolveEntity(String publicId, String systemId)
                                throws SAXException, IOException {
                            return new InputSource(new ByteArrayInputStream(new byte[0]));
                        }
                    });
                    org.dom4j.Document doc = xmlReader.read(url);
                    Node node = doc.selectSingleNode("/*[local-name()='configuration']/category/priority");
                    String priority = node.valueOf("@value");
                    if (!chechPriorityString(priority)) {
                        throw new UtilitiesException(
                                "Log4j does not support the value for priority - " + priority);
                    }

                    // Node node2 = doc.selectSingleNode("/*[local-name()='configuration']/root/priority");
                    String priority2 = node.valueOf("@value");
                    if (!chechPriorityString(priority2)) {
                        throw new UtilitiesException(
                                "Log4j does not support the value for priority - " + priority2);
                    }
                }
            }
        }

        DOMConfigurator.configure(url);
    } else {
        PropertyConfigurator.configure(url);
    }
}

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

License:Open Source License

public static HashMap<String, Point> graphicalInfoFrom(Document document) {
    HashMap<String, Point> graphicalInfoMap = new HashMap<String, Point>();
    try {//from w w  w .  j a  v a  2s . c  o m
        SAXReader reader = new SAXReader();
        Pattern p = Pattern.compile("\\s*<workflow>.*</workflow>\\s*", Pattern.DOTALL);

        @SuppressWarnings("unchecked")
        Iterator<Node> iter = document.nodeIterator();
        while (iter.hasNext()) {

            Node xmlNode = iter.next();
            if (xmlNode.getNodeType() == Node.COMMENT_NODE) {

                String graphicalInfo = xmlNode.getText();
                if (p.matcher(graphicalInfo).find()) {

                    Element graphicalElement = reader.read(new StringReader(graphicalInfo)).getRootElement();
                    @SuppressWarnings("unchecked")
                    Iterator<Node> gIter = graphicalElement.nodeIterator();

                    while (gIter.hasNext()) {
                        Node gNode = gIter.next();
                        if (gNode.getName() != null && gNode.getName().equals("node")) {
                            graphicalInfoMap.put(gNode.valueOf("@name"),
                                    new Point(Integer.parseInt(gNode.valueOf("@x")),
                                            Integer.parseInt(gNode.valueOf("@y"))));
                        }
                    }
                    break;

                }

            }

        }
    } catch (DocumentException ex) {
        ex.printStackTrace();
    }
    return graphicalInfoMap;
}

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

License:Open Source License

public static SchemaVersion schemaVersion(String xpath, Node node, String tag) {
    String xmlns = node.valueOf(xpath + "@" + tag);
    return schemaVersion(xmlns);
}

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

License:Open Source License

public static String valueOf(String xpath, Node node) {
    String value = "";
    if (node != null) {
        value = node.valueOf(xpath);
    }//from  w  w w  . j a  v a  2  s  .  co  m
    return value == null ? "" : value;
}