Example usage for org.dom4j Node selectSingleNode

List of usage examples for org.dom4j Node selectSingleNode

Introduction

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

Prototype

Node selectSingleNode(String xpathExpression);

Source Link

Document

selectSingleNode evaluates an XPath expression and returns the result as a single Node instance.

Usage

From source file:feedForwardNetwork.FeedForwardNetwork.java

License:Open Source License

@Override
public AbstractRepresentation loadFromXML(Node nd) {
    try {/*from  www.  j av a  2  s  . co  m*/
        String fitnessString = nd.valueOf("./@fitness");
        if (!fitnessString.isEmpty()) {
            this.setFitness(Double.parseDouble(fitnessString));
        }

        // load activation function
        XMLFieldEntry afprop = getProperties().get("activationFunction");
        if (afprop == null) {
            activationFunction = DEFAULT_ACTIVATION_FUNCTION;
        } else {
            activationFunction = ActivationFunction.valueOf(afprop.getValue());
        }

        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.layers = Integer.parseInt(nd.valueOf("./@layers"));
        // this.iteration =
        // Integer.parseInt(nd.valueOf("./simulation/@iteration"));
        // this.score = Integer.parseInt(nd.valueOf("./simulation/@score"));
        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];
        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("ThreeLayerNetwork: 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++) {
                String ws = dweights.valueOf("./weight[@from='" + from + "']");
                if (ws.length() == 0)
                    throw new IllegalArgumentException("ThreeLayerNetwork: weight tags inconsistent!"
                            + "\ncheck 'from' attributes and nodes count in nnetwork!");
                float val = Float.parseFloat(ws);
                this.weight[from][nr] = val;
            }
        }
        // this.gahist = new GAHistory(this.config, nd);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("ThreeLayerNetwork: NumberFormatException! Check XML File");
    }
    return this;
}

From source file:fr.gouv.culture.vitam.reader.XmlReader.java

License:Open Source License

@Override
public String[] readOneLine() throws IOException {
    if (this.nodes != null) {
        if (this.nodes.isEmpty()) {
            this.nodes = null;
            return null;
        }/*from   w  w  w .j  a  v a 2 s.co m*/
        String[] result = new String[xpaths.length - 1];
        Node root = this.nodes.remove(0);
        for (int i = 1; i < xpaths.length; i++) {
            Node sub = root.selectSingleNode(xpaths[i]);
            if (sub != null) {
                result[i - 1] = sub.getText();
            } else {
                result[i - 1] = null;
            }
        }
        return result;
    }
    return null;
}

From source file:fr.gouv.culture.vitam.utils.XmlDom.java

License:Open Source License

/**
 * Attached file accessibility test//  w w w  .  j  a v  a 2 s .c om
 * 
 * @param current_file
 * @param task
 *            optional
 * @param config
 * @param argument
 * @param checkDigest
 * @param checkFormat
 * @param showFormat
 * @return VitamResult
 */
static final public VitamResult all_tests_in_one(File current_file, RunnerLongTask task, ConfigLoader config,
        VitamArgument argument, boolean checkDigest, boolean checkFormat, boolean showFormat) {
    SAXReader saxReader = new SAXReader();
    VitamResult finalResult = new VitamResult();
    Element root = initializeCheck(argument, finalResult, current_file);
    try {
        Document document = saxReader.read(current_file);
        removeAllNamespaces(document);
        Node nodesrc = document.selectSingleNode("/digests");
        String src = null;
        String localsrc = current_file.getParentFile().getAbsolutePath() + File.separator;
        if (nodesrc != null) {
            nodesrc = nodesrc.selectSingleNode("@source");
            if (nodesrc != null) {
                src = nodesrc.getText() + "/";
            }
        }
        if (src == null) {
            src = localsrc;
        }
        @SuppressWarnings("unchecked")
        List<Node> nodes = document.selectNodes("//" + config.DOCUMENT_FIELD);
        if (nodes == null) {
            Element result = fillInformation(argument, root, "result", "filefound", "0");
            addDate(argument, config, result);
        } else {
            String number = "" + nodes.size();
            Element result = fillInformation(argument, root, "result", "filefound", number);
            XMLWriter writer = null;
            writer = new XMLWriter(System.out, StaticValues.defaultOutputFormat);
            int currank = 0;
            for (Node node : nodes) {
                currank++;
                Node attachment = node.selectSingleNode(config.ATTACHMENT_FIELD);
                if (attachment == null) {
                    continue;
                }
                Node file = attachment.selectSingleNode(config.FILENAME_ATTRIBUTE);
                if (file == null) {
                    continue;
                }
                Node mime = null;
                Node format = null;
                if (checkFormat) {
                    mime = attachment.selectSingleNode(config.MIMECODE_ATTRIBUTE);
                    format = attachment.selectSingleNode(config.FORMAT_ATTRIBUTE);
                }
                String sfile = null;
                String smime = null;
                String sformat = null;
                String sintegrity = null;
                String salgo = null;
                if (file != null) {
                    sfile = file.getText();
                }
                if (mime != null) {
                    smime = mime.getText();
                }
                if (format != null) {
                    sformat = format.getText();
                }
                // Now check
                // first existence check
                String ficname = src + sfile;
                Element check = fillInformation(argument, root, "check", "filename", sfile);
                File fic1 = new File(ficname);
                File fic2 = new File(localsrc + sfile);
                File fic = null;
                if (fic1.canRead()) {
                    fic = fic1;
                } else if (fic2.canRead()) {
                    fic = fic2;
                }
                if (fic == null) {
                    fillInformation(argument, check, "find", "status",
                            StaticValues.LBL.error_filenotfile.get());
                    addDate(argument, config, result);
                    finalResult.values[AllTestsItems.FileError.ordinal()]++;
                    finalResult.values[AllTestsItems.GlobalError.ordinal()]++;
                } else {
                    Element find = fillInformation(argument, check, "find", "status", "ok");
                    addDate(argument, config, find);
                    finalResult.values[AllTestsItems.FileSuccess.ordinal()]++;
                    if (checkDigest) {
                        @SuppressWarnings("unchecked")
                        List<Node> integrities = node.selectNodes(config.INTEGRITY_FIELD);
                        for (Node integrity : integrities) {
                            Node algo = integrity.selectSingleNode(config.ALGORITHME_ATTRIBUTE);
                            salgo = null;
                            sintegrity = null;
                            if (integrity != null) {
                                sintegrity = integrity.getText();
                                if (algo != null) {
                                    salgo = algo.getText();
                                } else {
                                    salgo = config.DEFAULT_DIGEST;
                                }
                            }
                            // Digest check
                            if (salgo == null) {
                                // nothing
                            } else if (salgo.equals(StaticValues.XML_SHA1)) {
                                salgo = "SHA-1";
                            } else if (salgo.equals(StaticValues.XML_SHA256)) {
                                salgo = "SHA-256";
                            } else if (salgo.equals(StaticValues.XML_SHA512)) {
                                salgo = "SHA-512";
                            } else {
                                salgo = null;
                            }

                            if (algo != null) {
                                Element eltdigest = Commands.checkDigest(fic, salgo, sintegrity);
                                if (eltdigest.selectSingleNode(".[@status='ok']") != null) {
                                    finalResult.values[AllTestsItems.DigestSuccess.ordinal()]++;
                                } else {
                                    finalResult.values[AllTestsItems.DigestError.ordinal()]++;
                                    finalResult.values[AllTestsItems.GlobalError.ordinal()]++;
                                }
                                addDate(argument, config, eltdigest);
                                addElement(writer, argument, check, eltdigest);
                            }
                        }
                    }
                    // Check format
                    if (checkFormat && config.droidHandler != null) {
                        try {
                            // Droid
                            List<DroidFileFormat> list = config.droidHandler.checkFileFormat(fic, argument);
                            Element cformat = Commands.droidFormat(list, smime, sformat, sfile, fic);
                            if (config.droidHandler != null) {
                                cformat.addAttribute("pronom", config.droidHandler.getVersionSignature());
                            }
                            if (config.droidHandler != null) {
                                cformat.addAttribute("droid", "6.1");
                            }
                            if (cformat.selectSingleNode(".[@status='ok']") != null) {
                                finalResult.values[AllTestsItems.FormatSuccess.ordinal()]++;
                            } else if (cformat.selectSingleNode(".[@status='warning']") != null) {
                                finalResult.values[AllTestsItems.FormatWarning.ordinal()]++;
                                finalResult.values[AllTestsItems.GlobalWarning.ordinal()]++;
                            } else {
                                finalResult.values[AllTestsItems.FormatError.ordinal()]++;
                                finalResult.values[AllTestsItems.GlobalError.ordinal()]++;
                            }
                            addDate(argument, config, cformat);
                            addElement(writer, argument, check, cformat);
                        } catch (Exception e) {
                            Element cformat = fillInformation(argument, check, "format", "status",
                                    "Error " + e.toString());
                            addDate(argument, config, cformat);
                            finalResult.values[AllTestsItems.SystemError.ordinal()]++;
                        }
                    }
                    // Show format
                    if (showFormat && config.droidHandler != null) {
                        Element showformat = Commands.showFormat(sfile, smime, sformat, fic, config, argument);
                        if (showformat.selectSingleNode(".[@status='ok']") != null) {
                            finalResult.values[AllTestsItems.ShowSuccess.ordinal()]++;
                        } else if (showformat.selectSingleNode(".[@status='warning']") != null) {
                            finalResult.values[AllTestsItems.ShowWarning.ordinal()]++;
                            finalResult.values[AllTestsItems.GlobalWarning.ordinal()]++;
                        } else {
                            finalResult.values[AllTestsItems.ShowError.ordinal()]++;
                            finalResult.values[AllTestsItems.GlobalError.ordinal()]++;
                        }
                        addDate(argument, config, showformat);
                        addElement(writer, argument, check, showformat);
                    }
                }
                addDate(argument, config, result);
                root = finalizeOneCheck(argument, finalResult, current_file, number);
                if (root != null) {
                    result = root.element("result");
                }
                if (task != null) {
                    float value = ((float) currank) / (float) nodes.size();
                    value *= 100;
                    task.setProgressExternal((int) value);
                }
            }
        }
        document = null;
    } catch (DocumentException e1) {
        Element result = fillInformation(argument, root, "result", "parsererror",
                StaticValues.LBL.error_error.get() + " " + e1 + " - " + StaticValues.LBL.error_parser.get()
                        + " (" + SAXReader.class.getName() + ")");
        addDate(argument, config, result);
        finalResult.values[AllTestsItems.SystemError.ordinal()]++;
    } catch (UnsupportedEncodingException e1) {
        Element result = fillInformation(argument, root, "result", "parsererror",
                StaticValues.LBL.error_error.get() + " " + e1 + " - " + StaticValues.LBL.error_parser.get()
                        + " (" + XMLWriter.class.getName() + ")");
        addDate(argument, config, result);
        finalResult.values[AllTestsItems.SystemError.ordinal()]++;
    }
    finalizeAllCheck(argument, finalResult);
    return finalResult;
}

From source file:fr.isima.ponge.wsprotocol.xml.XmlIOManager.java

License:Open Source License

/**
 * Reads a business protocol.//from  w ww  .j av a 2s. com
 *
 * @param reader The reader object for the XML source.
 * @return The protocol.
 * @throws DocumentException Thrown if an error occurs.
 */
@SuppressWarnings("unchecked")
public BusinessProtocol readBusinessProtocol(Reader reader) throws DocumentException {
    // Vars
    Iterator it;
    Node node;

    // Parsing
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(reader);

    // Protocol
    BusinessProtocol protocol = factory.createBusinessProtocol(document.valueOf("/business-protocol/name")); //$NON-NLS-1$
    readExtraProperties(protocol, document.selectSingleNode("/business-protocol")); //$NON-NLS-1$

    // States
    Map<String, State> states = new HashMap<String, State>();
    it = document.selectNodes("/business-protocol/state").iterator(); //$NON-NLS-1$
    while (it.hasNext()) {
        node = (Node) it.next();
        State s = factory.createState(node.valueOf("name"), "true" //$NON-NLS-1$ //$NON-NLS-2$
                .equals(node.valueOf("final"))); //$NON-NLS-1$
        readExtraProperties(s, node);
        protocol.addState(s);
        states.put(s.getName(), s);
        if (node.selectSingleNode("initial-state") != null) //$NON-NLS-1$
        {
            protocol.setInitialState(s);
        }
    }

    // Operations & messages
    int legacyOperationNameCounter = 0;
    it = document.selectNodes("/business-protocol/operation").iterator(); //$NON-NLS-1$
    while (it.hasNext()) {
        node = (Node) it.next();
        String opName = node.valueOf("name"); //$NON-NLS-1$
        if ("".equals(opName)) {
            opName = "T" + legacyOperationNameCounter++;
        }
        String msgName = node.valueOf("message/name"); //$NON-NLS-1$
        String msgPol = node.valueOf("message/polarity"); //$NON-NLS-1$
        State s1 = states.get(node.valueOf("source")); //$NON-NLS-1$
        State s2 = states.get(node.valueOf("target")); //$NON-NLS-1$
        Polarity pol;
        if (msgPol.equals("positive")) //$NON-NLS-1$
        {
            pol = Polarity.POSITIVE;
        } else if (msgPol.equals("negative")) //$NON-NLS-1$
        {
            pol = Polarity.NEGATIVE;
        } else {
            pol = Polarity.NULL;
        }
        String opKindValue = node.valueOf("kind");
        OperationKind kind;
        if ("".equals(opKindValue) || "explicit".equals(opKindValue)) {
            kind = OperationKind.EXPLICIT;
        } else {
            kind = OperationKind.IMPLICIT;
        }
        Message msg = factory.createMessage(msgName, pol);
        readExtraProperties(msg, node.selectSingleNode("message")); //$NON-NLS-1$
        Operation op = factory.createOperation(opName, s1, s2, msg, kind);
        readExtraProperties(op, node);
        protocol.addOperation(op);
    }

    return protocol;
}

From source file:fullyMeshedNet.FullyMeshedNet.java

License:Open Source License

public FullyMeshedNet loadFromXML(Node nd) {
    try {/*from   www.j  a  va2  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

/**
 * Gets expected number of transactions (for all accounts)
 * @return Expected number of transactions
 * @throws ParsingException Expected number of transactions not found
 * @throws NumberFormatException The expected number of transactions is not numeric
 *//*from  w w  w.  j a va  2s .c  om*/
private int getExpectedNumberOfTransactions() throws ParsingException, NumberFormatException {
    log.entering(this.getClass().getName(), "getExpectedNumberOfTransactions");
    int expectedNumberOfTransactions = 0;

    List listOfAccounts = grisbiFileDocument.selectNodes("/Grisbi/Comptes/Compte");
    for (Object accountObject : listOfAccounts) {
        Node accountNode = (Node) accountObject;
        assert (accountNode != null);

        // Get the name of the current account
        Node accountNameNode = accountNode.selectSingleNode("Details/Nom");
        assert (accountNameNode != null);
        String accountName = accountNameNode.getStringValue();
        assert (accountName != 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 expectedNumberOfTransactionsForCurrentAccount = Integer.parseInt(expectedNumberOfTransactionsValue);

        expectedNumberOfTransactions += expectedNumberOfTransactionsForCurrentAccount;
    }

    log.exiting(this.getClass().getName(), "getExpectedNumberOfTransactions", expectedNumberOfTransactions);
    return expectedNumberOfTransactions;
}

From source file:gg.imports.GrisbiFile050.java

License:Open Source License

/**
 * Imports the accounts into the database<BR/>
 * The method <CODE>importCurrencies()</CODE> has to be called before
 * @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 format of the date of the first transaction is invalid
 *///from   ww w  .j  a  v  a2s .c om
private void importAccounts() throws ParsingException, NumberFormatException, DateFormatException {
    log.entering(this.getClass().getName(), "importAccounts");
    long startImportingAccountsTime = System.currentTimeMillis();

    // Get all the currencies already saved in the database (the method importCurrencies() has to be called before)
    Map<Long, Currency> currencies = Datamodel.getCurrenciesWithId();

    // Import the accounts in the embedded database
    long numberOfImportedAccounts = 0;
    List listOfAccounts = grisbiFileDocument.selectNodes("/Grisbi/Comptes/Compte");
    Iterator accountsIterator = listOfAccounts.iterator();
    while (accountsIterator.hasNext() && !isImportCancelled()) {

        // Get the account node
        Node accountNode = (Node) accountsIterator.next();

        // Get the "Active" property of the account: is the account closed?
        Node accountActiveNode = accountNode.selectSingleNode("Details/Compte_cloture");
        assert (accountActiveNode != null);
        String accountActiveValue = accountActiveNode.getStringValue();
        assert (accountActiveValue != null);
        boolean accountActive = (accountActiveValue.compareTo("1") != 0);

        // 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 account
        Node accountNameNode = accountNode.selectSingleNode("Details/Nom");
        assert (accountNameNode != null);
        String accountName = accountNameNode.getStringValue();
        assert (accountName != null);

        // Get the currency of the account
        Node currencyIdNode = accountNode.selectSingleNode("Details/Devise");
        assert (currencyIdNode != null);
        String currencyIdValue = currencyIdNode.getStringValue();
        assert (currencyIdValue != null);
        long currencyId = Long.parseLong(currencyIdValue);
        assert (currencyId > 0);

        // Get the corresponding Currency object
        Currency accountCurrency = currencies.get(currencyId); // An account has always a currency in Grisbi
        assert (accountCurrency != null);

        // Activate the currency if needed
        if (accountActive && !accountCurrency.getActive()) {
            accountCurrency.setActive(true);
        }

        // Get the initial amount of the account
        Node accountInitialAmountNode = accountNode.selectSingleNode("Details/Solde_initial");
        assert (accountInitialAmountNode != null);
        String accountInitialAmountValue = accountInitialAmountNode.getStringValue();
        assert (accountInitialAmountValue != null);
        BigDecimal accountInitialAmount = new BigDecimal(accountInitialAmountValue.replace(',', '.'));
        accountInitialAmount = accountInitialAmount.setScale(2, RoundingMode.HALF_EVEN);

        // Get the current balance of the account
        Node accountBalanceNode = accountNode.selectSingleNode("Details/Solde_courant");
        assert (accountBalanceNode != null);
        String accountBalanceValue = accountBalanceNode.getStringValue();
        assert (accountBalanceValue != null);
        BigDecimal accountBalance = new BigDecimal(accountBalanceValue.replace(',', '.'));
        accountBalance = accountBalance.setScale(2, RoundingMode.HALF_EVEN);

        // Create a new account and save the account in the embedded database
        Account account = new Account(accountId, accountName, accountCurrency, accountInitialAmount,
                accountBalance, accountActive);
        Datamodel.saveAccount(account);

        // Update the currency's balance and the currency's initial amount
        if (accountActive) {
            accountCurrency.setBalance(accountCurrency.getBalance().add(accountBalance));
            accountCurrency.setInitialAmount(accountCurrency.getInitialAmount().add(accountInitialAmount));
        }

        numberOfImportedAccounts++;
    }

    // Update the currencies (active flag, balance, initial amount)
    for (Currency currency : currencies.values()) {
        Datamodel.saveCurrency(currency);
    }

    long endImportingAccountsTime = System.currentTimeMillis();
    log.info(numberOfImportedAccounts + " accounts have been successfully imported in "
            + (endImportingAccountsTime - startImportingAccountsTime) + " ms");
    log.exiting(this.getClass().getName(), "importAccounts");
}

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  v  a  2 s .  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:GnuCash.Price.java

License:Open Source License

public Price(Node n) {
    commodity_id = n.selectSingleNode("price:commodity/cmdty:id").getText();
    currency_id = n.selectSingleNode("price:currency/cmdty:id").getText();
    date = getDateValue(n.selectSingleNode("price:time/ts:date").getText());
    source = n.selectSingleNode("price:source").getText();
    type = n.selectSingleNode("price:type").getText();
    value = getDoubleValue(n.selectSingleNode("price:value").getText());

    //System.out.println(commodity_id + ":" + formatDate(date) + ":" + value);
}

From source file:GnuCash.Transaction.java

License:Open Source License

public Transaction(Node n, String account_id) {
    description = n.selectSingleNode("../../trn:description").getText();
    currency_id = n.selectSingleNode("../../trn:currency/cmdty:id").getText();
    date = getDateValue(n.selectSingleNode("../../trn:date-posted/ts:date").getText());
    value = getDoubleValue(n.selectSingleNode("split:value").getText());
    //quantity = getDoubleValue(n.selectSingleNode("split:quantity").getText());

    if (n.selectSingleNode("split:account[@type='guid']").getText().equals(account_id)) {
        quantity = getDoubleValue(n.selectSingleNode("split:quantity").getText());
    }/* www .j av  a 2 s .  co m*/
}