Пример #1
0
  public static void setUpdateOnStartup(final boolean update) {
    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    if (engine != null) {
      engine.putBoolean(UPDATE_ON_STARTUP, update);
    }
  }
Пример #2
0
    @Override
    public void run() {

      assert liabilityAccount != null && elementMap != null;

      AmortizeObject ao = new AmortizeObject();

      ao.setBankAccount(accountMap.get(elementMap.get("bankAccount")));
      ao.setDate(decodeDate(elementMap.get("date")));

      if (elementMap.get("daysPerYear") != null) {
        ao.setDaysPerYear(new BigDecimal(elementMap.get("daysPerYear")));
      }

      ao.setFees(new BigDecimal(elementMap.get("fees")));
      ao.setFeesAccount(accountMap.get(elementMap.get("feesAccount")));
      ao.setInterestAccount(accountMap.get(elementMap.get("interestAccount")));
      ao.setInterestPeriods(Integer.parseInt(elementMap.get("compondingPeriods")));
      ao.setLength(Integer.parseInt(elementMap.get("length")));
      ao.setMemo(elementMap.get("memo"));
      ao.setPayee(elementMap.get("payee"));
      ao.setPaymentPeriods(Integer.parseInt(elementMap.get("paymentPeriods")));
      ao.setPrincipal(new BigDecimal(elementMap.get("principal")));
      ao.setRate(new BigDecimal(elementMap.get("rate")));
      ao.setUseDailyRate(Boolean.parseBoolean(elementMap.get("useDailyRate")));

      Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
      engine.setAmortizeObject(liabilityAccount, ao);
    }
Пример #3
0
    @Override
    public Boolean call() throws Exception {
      boolean result = false;

      final Engine e = EngineFactory.getEngine(EngineFactory.DEFAULT);

      if (e != null && securityNode.getQuoteSource() != QuoteSource.NONE) {
        final SecurityParser parser = securityNode.getQuoteSource().getParser();

        if (parser != null
            && !Thread.currentThread().isInterrupted()) { // check for thread interruption
          if (parser.parse(securityNode)) {

            final SecurityHistoryNode node =
                new SecurityHistoryNode(
                    parser.getDate(),
                    parser.getPrice(),
                    parser.getVolume(),
                    parser.getHigh(),
                    parser.getLow());

            if (!Thread.currentThread().isInterrupted()) { // check for thread interruption
              result = e.addSecurityHistory(securityNode, node);

              if (result) {
                logger.info(
                    ResourceUtils.getString("Message.UpdatedPrice", securityNode.getSymbol()));
              }
            }
          }
        }
      }

      return result;
    }
Пример #4
0
  private static void parseExchangeRate(final XMLStreamReader reader) {
    Map<String, String> elementMap = new HashMap<>();

    /* still at start of the exchange rate.  Need to know when end is reached */
    QName parsingElement = reader.getName();

    try {
      while (reader.hasNext()) {

        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            String element = reader.getLocalName();
            elementMap.put(element.intern(), reader.getElementText());
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getName().equals(parsingElement)) {
              logger.finest("Found the end of the exchange rate");

              try {
                String key = elementMap.get("key");

                if (key != null && key.length() == 6) {

                  Engine e = EngineFactory.getEngine(EngineFactory.DEFAULT);

                  CurrencyNode cOne = e.getCurrency(key.substring(0, 3));
                  CurrencyNode cTwo = e.getCurrency(key.substring(3, 6));

                  // jGnash 1.x would hold onto old exchange rates for deleted commodities
                  if (cOne != null && cTwo != null) {
                    BigDecimal rate = new BigDecimal(elementMap.get("rate"));

                    EngineFactory.getEngine(EngineFactory.DEFAULT)
                        .setExchangeRate(cOne, cTwo, rate);

                    logger.log(
                        Level.FINE,
                        "Set ExchangeRate {0}:{1}",
                        new Object[] {key, rate.toString()});
                  }
                }

              } catch (Exception e) {
                logger.log(Level.SEVERE, e.toString(), e);
              }
              return;
            }
            break;
          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.severe("Error importing exchange rate");
      logger.log(Level.SEVERE, e.toString(), e);
    }
  }
Пример #5
0
  private void createReport() {
    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
    Account root = engine.getRootAccount();

    baseCommodity = engine.getDefaultCurrency();

    numberFormat = CommodityFormat.getFullNumberFormat(baseCommodity);
    SimpleDateFormat df = new SimpleDateFormat("dd-MMMMM-yyyy");

    dates = getDates();

    // title and dates
    pl.add(rb.getString("Title.ProfitLoss"));
    pl.add("");
    pl.add("From " + df.format(dates[0]) + " To " + df.format(dates[1]));
    pl.add("");
    pl.add("");

    // Income
    pl.add("Income");
    pl.add("------------------------------------------------------");
    getBalances(root, dates, AccountType.INCOME);

    // Add up the  Gross Income.
    BigDecimal total1 = BigDecimal.ZERO;
    for (Object aBalance1 : balance) {
      total1 = total1.add((BigDecimal) aBalance1);
    }
    pl.add("------------------------------------------------------");
    pl.add(formatAcctNameOut(rb.getString("Word.GrossIncome")) + " " + formatDecimalOut(total1));
    pl.add("------------------------------------------------------");
    pl.add("");
    pl.add("");

    // Expense
    pl.add("Expenses");
    pl.add("------------------------------------------------------");
    balance = new ArrayList<>();
    getBalances(root, dates, AccountType.EXPENSE);

    // Add up the Gross Expenses
    BigDecimal total2 = BigDecimal.ZERO;
    for (Object aBalance : balance) {
      total2 = total2.add((BigDecimal) aBalance);
    }
    pl.add("------------------------------------------------------");
    pl.add(formatAcctNameOut(rb.getString("Word.GrossExpense")) + " " + formatDecimalOut(total2));
    pl.add("------------------------------------------------------");
    pl.add("");
    pl.add("");

    // Net Total
    pl.add("------------------------------------------------------");
    pl.add(
        formatAcctNameOut(rb.getString("Word.NetIncome"))
            + " "
            + formatDecimalOut(total1.add(total2)));
    pl.add("======================================================");
  }
Пример #6
0
  @FXML
  private void updateSecurities() {
    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    Objects.requireNonNull(engine);

    engine.startSecuritiesUpdate(0);
  }
Пример #7
0
  @FXML
  private void updateCurrencies() {
    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    Objects.requireNonNull(engine);

    engine.startExchangeRateUpdate(0);
  }
Пример #8
0
  public static boolean getUpdateOnStartup() {
    boolean result = false;

    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    if (engine != null) {
      result = engine.getBoolean(UPDATE_ON_STARTUP, false);
    }

    return result;
  }
  @FXML
  private void handleDeleteAccountAction() {
    if (getSelectedAccount().isPresent()) {
      final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
      Objects.requireNonNull(engine);

      if (!engine.removeAccount(getSelectedAccount().get())) {
        StaticUIMethods.displayError(resources.getString("Message.Error.AccountRemove"));
      }
    }
  }
Пример #10
0
  private void parseTransaction(final XMLStreamReader reader) {

    assert reader.getAttributeCount() == 2;

    Map<String, String> elementMap = new HashMap<>();

    /* still at start of the transaction.  Need to know when end is reached */
    QName parsingElement = reader.getName();

    String transactionClass = reader.getAttributeValue(0);
    String transactionId = reader.getAttributeValue(1);

    elementMap.put(ID, transactionId);

    try {
      while (reader.hasNext()) {

        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            String element = reader.getLocalName();
            elementMap.put(element.intern(), reader.getElementText());
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getName().equals(parsingElement)) {
              logger.log(Level.FINEST, "Found the end of a Transaction: {0}", transactionId);

              try {
                Transaction transaction = generateTransaction(transactionClass, elementMap);

                if (transaction != null) {
                  Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
                  engine.addTransaction(transaction);
                  logger.finest("Transaction add complete");
                }
              } catch (Exception e) {
                logger.log(Level.SEVERE, "Error importing transaction id: {0}", transactionId);
                logger.log(Level.SEVERE, e.toString(), e);
                throw new RuntimeException(e);
              }
              return;
            }
            break;
          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, "Error importing transaction id: {0}", transactionId);
      logger.log(Level.SEVERE, e.toString(), e);
    }
  }
Пример #11
0
  private SecurityNode decodeSecurity(final String symbol) {
    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    SecurityNode sNode = engine.getSecurity(symbol);

    if (sNode == null) {

      Commodity cNode = commodityMap.get(symbol);

      if (cNode != null) {

        logger.log(Level.INFO, "Converting a commodity into a security: {0}", symbol);

        sNode = new SecurityNode(engine.getDefaultCurrency());

        sNode.setDescription(cNode.description);
        sNode.setPrefix(cNode.prefix);
        sNode.setSuffix(cNode.suffix);
        sNode.setScale(cNode.scale);
        sNode.setSymbol(cNode.symbol);
        sNode.setQuoteSource(QuoteSource.YAHOO);

        engine.addSecurity(sNode);
      } else { // may be a currency... try to create a security

        CurrencyNode currency = decodeCurrency(symbol);

        if (currency != null) {

          logger.info("Converting a currency into a security");

          sNode = new SecurityNode();

          sNode.setDescription(currency.getDescription());
          sNode.setPrefix(currency.getPrefix());
          sNode.setSuffix(currency.getSuffix());
          sNode.setScale(currency.getScale());
          sNode.setSymbol(currency.getSymbol());

          sNode.setReportedCurrencyNode(currency);
          sNode.setQuoteSource(QuoteSource.YAHOO);

          engine.addSecurity(sNode);
        }
      }
    }

    if (sNode == null) {
      logger.log(Level.SEVERE, "Bad file, security {0} not mapped", symbol);
    }

    return sNode;
  }
Пример #12
0
  @FXML
  @Override
  public void handleEnterAction() {
    if (validateForm()) {
      if (modTrans == null) { // new transaction
        Transaction newTrans = buildTransaction();

        ReconcileManager.reconcileTransaction(
            accountProperty.get(), newTrans, getReconciledState());

        newTrans = attachmentPane.buildTransaction(newTrans); // chain the transaction build

        final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

        if (engine != null) {
          engine.addTransaction(newTrans);
        }
      } else {
        Transaction newTrans = buildTransaction();

        newTrans.setDateEntered(modTrans.getDateEntered());

        // restore the reconciled state of the previous old transaction
        for (final Account a : modTrans.getAccounts()) {
          if (!a.equals(accountProperty.get())) {
            ReconcileManager.reconcileTransaction(a, newTrans, modTrans.getReconciled(a));
          }
        }

        /*
         * Reconcile the modified transaction for this account.
         * This must be performed last to ensure consistent results per the ReconcileManager rules
         */
        ReconcileManager.reconcileTransaction(
            accountProperty.get(), newTrans, getReconciledState());

        newTrans = attachmentPane.buildTransaction(newTrans); // chain the transaction build

        final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

        if (engine != null && engine.removeTransaction(modTrans)) {
          engine.addTransaction(newTrans);
        }
      }
      clearForm();

      if (payeeTextField != null) {
        payeeTextField.requestFocus();
      } else {
        memoTextField.requestFocus();
      }
    }
  }
Пример #13
0
  void importAccounts(final XMLStreamReader reader) {

    logger.info("Begin Account import");

    try {
      parse:
      while (reader.hasNext()) {
        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            if (reader.getAttributeCount() > 0) {
              if (reader.getAttributeValue(0).contains("Account")) {
                logger.finest("Found the start of an Account");
                parseAccount(reader);
              }
            }
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getLocalName().equals("objects")) {
              logger.finest("Found the end of the object list and accounts");
              break parse;
            }
            break;
          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, e.toString(), e);
    }

    logger.info("Linking accounts");

    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    for (Account account : parentMap.keySet()) {
      if (account.getAccountType() != AccountType.ROOT) {
        Account parent = accountMap.get(parentMap.get(account));
        if (!account.getParent().equals(parent)) {
          if (engine.moveAccount(account, parent)) {
            logger.log(
                Level.FINEST,
                "Moving {0} to {1}",
                new Object[] {account.getName(), parent.getName()});
          }
        }
      }
    }

    logger.info("Account import complete");
  }
Пример #14
0
  private void updateAccountCode(final Account account, final Integer code) {
    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    if (engine != null) {
      try {
        final Account template = (Account) account.clone();
        template.setAccountCode(code);

        engine.modifyAccount(template, account);
      } catch (final CloneNotSupportedException e) {
        Logger.getLogger(AccountsViewController.class.getName())
            .log(Level.SEVERE, e.getLocalizedMessage(), e);
      }
    }
  }
Пример #15
0
  private void loadAccountTree() {
    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    if (engine != null) {
      RootAccount r = engine.getRootAccount();

      final TreeItem<Account> root = new TreeItem<>(r);
      root.setExpanded(true);

      treeTableView.setRoot(root);
      loadChildren(root);
    } else {
      treeTableView.setRoot(null);
    }
  }
Пример #16
0
  @FXML
  private void convertAction() {
    final Optional<Account> accountOptional =
        StaticAccountsMethods.selectAccount(null, accountProperty.get());
    if (accountOptional.isPresent()) {
      final Account opp = accountOptional.get();

      final Transaction t = new Transaction();

      t.setDate(datePicker.getValue());
      t.setNumber(numberComboBox.getValue());
      t.setPayee(payeeTextField.getText());

      final TransactionEntry entry = new TransactionEntry();
      entry.setMemo(memoTextField.getText());

      if (amountField.getDecimal().signum() >= 0) {
        entry.setCreditAccount(accountProperty.get());
        entry.setDebitAccount(opp);
      } else {
        entry.setDebitAccount(accountProperty.get());
        entry.setCreditAccount(opp);
      }

      entry.setCreditAmount(amountField.getDecimal().abs());
      entry.setDebitAmount(amountField.getDecimal().abs().negate());

      t.addTransactionEntry(entry);

      ReconcileManager.reconcileTransaction(accountProperty.get(), t, getReconciledState());

      TransactionDialog.showAndWait(
          accountProperty.get(),
          t,
          optional -> {
            if (optional.isPresent()) {
              final Transaction tran = optional.get();
              final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
              Objects.requireNonNull(engine);

              if (engine.removeTransaction(modTrans)) {
                engine.addTransaction(tran);
              }
              clearForm();
            }
          });
    }
  }
Пример #17
0
    @Override
    public void run() {
      try {
        SecurityNode clone = (SecurityNode) sNode.clone();

        Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

        CurrencyNode currencyNode = engine.getCurrency(cNode);

        if (currencyNode != null) {
          clone.setReportedCurrencyNode(currencyNode);
          engine.updateCommodity(sNode, clone);
        }
      } catch (CloneNotSupportedException e) {
        logger.log(Level.SEVERE, e.toString(), e);
      }
    }
Пример #18
0
  private static void parseCurrencyNode(final XMLStreamReader reader) {
    Map<String, String> elementMap = new HashMap<>();

    /* still at start of the element.  Need to know when end is reached */
    QName parsingElement = reader.getName();

    try {
      while (reader.hasNext()) {
        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            String element = reader.getLocalName();
            elementMap.put(element, reader.getElementText());
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getName().equals(parsingElement)) {
              logger.finest("Found the end of a CurrencyNode");

              Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

              if (engine.getCurrency(elementMap.get("symbol")) == null) {

                CurrencyNode node = new CurrencyNode();

                node.setSymbol(elementMap.get("symbol"));
                node.setDescription(elementMap.get("description"));
                node.setPrefix(elementMap.get("prefix"));
                node.setSuffix(elementMap.get("suffix"));
                node.setScale(Byte.parseByte(elementMap.get("scale")));

                engine.addCurrency(node);
              }
              return;
            }
            break;

          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, e.toString(), e);
    }
  }
Пример #19
0
  private static void configureLogging() {
    final Handler[] handlers = Logger.getLogger("").getHandlers();
    for (final Handler handler : handlers) {
      handler.setLevel(Level.ALL);
    }

    Engine.getLogger().setLevel(Level.ALL);
    YahooParser.logger.setLevel(Level.ALL);
  }
Пример #20
0
  /**
   * Changes and transaction number to the next available in the account and returns the resultant
   *
   * @param transaction transaction to change the check number
   * @return the resultant transaction
   */
  private static Transaction changeTransNum(final Transaction transaction) {
    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    try {
      Transaction clone = (Transaction) transaction.clone();

      clone.setNumber(getNextTransactionNum(transaction));

      if (engine.removeTransaction(transaction)) {
        engine.addTransaction(clone);
        return clone;
      }
    } catch (CloneNotSupportedException e) {
      Logger.getLogger(PrintCheckFactory.class.getName()).log(Level.SEVERE, null, e);
    }

    return transaction;
  }
Пример #21
0
    @Override
    public Boolean call() throws Exception {
      boolean result = true;

      try {
        final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
        Objects.requireNonNull(engine);

        final List<SecurityHistoryNode> newSecurityNodes =
            downloadHistory(securityNode, startDate, endDate);

        for (final SecurityHistoryNode historyNode : newSecurityNodes) {
          engine.addSecurityHistory(securityNode, historyNode);
        }
      } catch (NullPointerException | NumberFormatException ex) {
        logger.log(Level.SEVERE, null, ex);
        result = false;
      }

      return result;
    }
Пример #22
0
    @Override
    public Boolean call() throws Exception {

      boolean result = true;

      final Engine e = EngineFactory.getEngine(EngineFactory.DEFAULT);

      final LocalDate oldest = securityNode.getHistoryNodes().get(0).getLocalDate();

      if (e != null && securityNode.getQuoteSource() != QuoteSource.NONE) {

        final Set<SecurityHistoryEvent> oldHistoryEvents =
            new HashSet<>(securityNode.getHistoryEvents());

        for (final SecurityHistoryEvent securityHistoryEvent :
            YahooEventParser.retrieveNew(securityNode)) {
          if (!Thread.currentThread().isInterrupted()) { // check for thread interruption

            if (securityHistoryEvent.getDate().isAfter(oldest)
                || securityHistoryEvent.getDate().isEqual(oldest)) {
              if (!oldHistoryEvents.contains(securityHistoryEvent)) {
                result = e.addSecurityHistoryEvent(securityNode, securityHistoryEvent);

                if (result) {
                  logger.info(
                      ResourceUtils.getString(
                          "Message.UpdatedSecurityEvent", securityNode.getSymbol()));
                }
              }
            }
          }
        }
      }

      return result;
    }
Пример #23
0
  @Test
  public void testExportBudgetResultsModel() throws Exception {

    File file = File.createTempFile("budget", ".xml");
    file.deleteOnExit();

    Engine e =
        EngineFactory.bootLocalEngine(
            file.getName(), EngineFactory.DEFAULT, PASSWORD, DataStoreType.XML);
    CurrencyNode node = e.getDefaultCurrency();

    Account account1 = new Account(AccountType.EXPENSE, node);
    account1.setName("Expense 1");
    e.addAccount(e.getRootAccount(), account1);

    Account account2 = new Account(AccountType.EXPENSE, node);
    account2.setName("Expense 2");
    e.addAccount(e.getRootAccount(), account2);

    Budget budget = new Budget();
    budget.setName("My Budget");
    budget.setDescription("Test");
    budget.setBudgetPeriod(BudgetPeriod.MONTHLY);

    e.addBudget(budget);

    BudgetResultsModel model = new BudgetResultsModel(budget, 2012, node);

    BudgetResultsExport.exportBudgetResultsModel(
        new File(System.getProperty("java.io.tmpdir") + File.separator + "testworkbook.xls"),
        model);

    // file.delete();

    assertTrue(true);
  }
Пример #24
0
  private static void exportXML(final Engine engine, final String fileName) {
    ArrayList<StoredObject> list = new ArrayList<>(engine.getStoredObjects());

    EngineFactory.exportCompressedXML(fileName, list);
  }
Пример #25
0
  @FXML
  private void initialize() {

    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
    if (engine != null) {
      accountSeparatorTextField.setText(engine.getAccountSeparator());

      accountSeparatorTextField
          .textProperty()
          .addListener(
              (observable, oldValue, newValue) -> {
                if (newValue != null && newValue.length() > 0) {
                  engine.setAccountSeparator(newValue);
                }
              });
    } else {
      accountSeparatorTextField.setDisable(true);
    }

    useAccountingTermsCheckBox
        .selectedProperty()
        .bindBidirectional(Options.useAccountingTermsProperty());

    switch (AccountBalanceDisplayManager.getDisplayMode()) {
      case NONE:
        noAccountsRadioButton.setSelected(true);
        break;
      case REVERSE_CREDIT:
        creditAccountsRadioButton.setSelected(true);
        break;
      case REVERSE_INCOME_EXPENSE:
        incomeExpenseAccountsRadioButton.setSelected(true);
        break;
    }

    noAccountsRadioButton
        .selectedProperty()
        .addListener(
            (observable, oldValue, newValue) -> {
              if (newValue) {
                AccountBalanceDisplayManager.setDisplayMode(AccountBalanceDisplayMode.NONE);
              }
            });

    creditAccountsRadioButton
        .selectedProperty()
        .addListener(
            (observable, oldValue, newValue) -> {
              if (newValue) {
                AccountBalanceDisplayManager.setDisplayMode(
                    AccountBalanceDisplayMode.REVERSE_CREDIT);
              }
            });

    incomeExpenseAccountsRadioButton
        .selectedProperty()
        .addListener(
            (observable, oldValue, newValue) -> {
              if (newValue) {
                AccountBalanceDisplayManager.setDisplayMode(
                    AccountBalanceDisplayMode.REVERSE_INCOME_EXPENSE);
              }
            });
  }
Пример #26
0
  private Account generateAccount(final String accountClass, final Map<String, Object> elementMap) {

    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

    CurrencyNode node = decodeCurrency((String) elementMap.get("commodity"));

    if (accountClass.equals("RootAccount")) {
      engine.setDefaultCurrency(node);
      return engine.getRootAccount();
    }

    Account account = null;

    switch (accountClass) {
      case "BankAccount":
        account = new Account(AccountType.BANK, node);
        break;
      case "ExpenseAccount":
        account = new Account(AccountType.EXPENSE, node);
        break;
      case "IncomeAccount":
        account = new Account(AccountType.INCOME, node);
        break;
      case "InvestmentAccount":
        {
          account = new Account(AccountType.INVEST, node);

          String[] securities = (String[]) elementMap.get("securities");

          if (securities != null) {
            for (String s : securities) {
              SecurityNode sNode = decodeSecurity(s);
              account.addSecurity(sNode);
            }
          }
          break;
        }
      case "MutualFundAccount":
        {
          account = new Account(AccountType.MUTUAL, node);

          String[] securities = (String[]) elementMap.get("securities");

          if (securities != null) {
            for (String s : securities) {
              SecurityNode sNode = decodeSecurity(s);
              account.addSecurity(sNode);
            }
          }
          break;
        }
      case "CreditAccount":
        account = new Account(AccountType.CREDIT, node);
        break;
      case "CashAccount":
        account = new Account(AccountType.CASH, node);
        break;
      case "EquityAccount":
        account = new Account(AccountType.EQUITY, node);
        break;
      case "LiabilityAccount":
        account = new Account(AccountType.LIABILITY, node);
        break;
      case "AssetAccount":
        account = new Account(AccountType.ASSET, node);
        break;
      default:
        break;
    }

    if (account != null) {
      account.setName((String) elementMap.get("name"));
      account.setDescription((String) elementMap.get("description"));
      account.setNotes((String) elementMap.get("notes"));
      account.setVisible(Boolean.parseBoolean((String) elementMap.get("visible")));
      account.setPlaceHolder(Boolean.parseBoolean((String) elementMap.get("placeHolder")));
      account.setAccountNumber((String) elementMap.get("code"));
    }
    return account;
  }
Пример #27
0
  private void parseSecurityNode(final XMLStreamReader reader) {
    Map<String, String> elementMap = new HashMap<>();
    List<SecurityHistoryNode> history = null;

    try {
      /* still at start of the element.  Need to know when end is reached */
      QName parsingElement = reader.getName();

      while (reader.hasNext()) {
        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            if (reader.getLocalName().equals("history")) {
              logger.finest("parse history");
              history = parseHistoryNodes(reader);
            } else {
              String element = reader.getLocalName();
              elementMap.put(element, reader.getElementText());
            }
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getName().equals(parsingElement)) {
              logger.finest("Found the end of a SecurityNode");

              Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

              if (engine.getSecurity(elementMap.get("symbol")) == null) {

                SecurityNode node = new SecurityNode(engine.getDefaultCurrency());

                node.setSymbol(elementMap.get("symbol"));
                node.setDescription(elementMap.get("description"));
                node.setPrefix(elementMap.get("prefix"));
                node.setSuffix(elementMap.get("suffix"));
                node.setScale(Byte.parseByte(elementMap.get("scale")));
                node.setQuoteSource(QuoteSource.YAHOO);

                if (elementMap.get("reportedCurrency") != null) {
                  SecurityThread thread =
                      new SecurityThread(node, elementMap.get("reportedCurrency"));
                  workQueue.add(thread);
                }

                engine.addSecurity(node);
              }

              if (history != null) {
                SecurityNode node = engine.getSecurity(elementMap.get("symbol"));
                if (node != null) {
                  for (SecurityHistoryNode hNode : history) {
                    if (!engine.addSecurityHistory(node, hNode)) {
                      logger.warning("Failed to add security history");
                    }
                  }
                }
              }
              return;
            }
            break;

          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, "Exception at element: {0}", reader.getName().toString());
      logger.log(Level.SEVERE, e.toString(), e);
    }
  }
Пример #28
0
  public static void doImport(final String filename) {

    Import imp = new Import();

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();

    try {
      Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

      CurrencyNode defaultCurrency = DefaultCurrencies.getDefault();

      if (engine.getCurrency(defaultCurrency.getSymbol()) == null) {
        engine.addCurrency(defaultCurrency);
        engine.setDefaultCurrency(defaultCurrency);
      }

      /* read commodity data first */
      try (InputStream input = new BufferedInputStream(new FileInputStream(new File(filename)))) {
        XMLStreamReader reader = inputFactory.createXMLStreamReader(input, "UTF-8");
        imp.importCommodities(reader);
        reader.close();
      }

      /* Run commodity generation cleanup threads */
      ExecutorService es = Executors.newSingleThreadExecutor();

      for (Iterator<Runnable> i = workQueue.iterator(); i.hasNext(); ) {
        es.execute(i.next());
        i.remove();
      }

      es.shutdown(); // shutdown after threads are complete

      while (!es.isTerminated()) {
        imp.getLogger().info("Waiting for commodity cleanup threads to complete");
        try {
          es.awaitTermination(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
          imp.getLogger().log(Level.SEVERE, e.toString(), e);
        }
      }

      imp.getLogger().info("Commodity cleanup threads complete");

      /* read account data first */
      try (InputStream input = new BufferedInputStream(new FileInputStream(new File(filename)))) {
        XMLStreamReader reader = inputFactory.createXMLStreamReader(input, "UTF-8");
        imp.importAccounts(reader);
        reader.close();
      }

      imp.getLogger().info("Running account cleanup threads");

      /* Run account generation cleanup threads */
      es = Executors.newSingleThreadExecutor();

      for (Iterator<Runnable> i = workQueue.iterator(); i.hasNext(); ) {
        es.execute(i.next());
        i.remove();
      }

      es.shutdown(); // shutdown after threads are complete

      while (!es.isTerminated()) {
        imp.getLogger().info("Waiting for account cleanup threads to complete");
        try {
          es.awaitTermination(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
          imp.getLogger().log(Level.SEVERE, e.toString(), e);
        }
      }

      imp.getLogger().info("Account cleanup threads complete");

      /* import transactions */
      try (InputStream input = new BufferedInputStream(new FileInputStream(new File(filename)))) {
        XMLStreamReader reader = inputFactory.createXMLStreamReader(input, "UTF-8");
        imp.importTransactions(reader);
        reader.close();
      }

      /* Lock accounts after transactions have been added */
      imp.lockAccounts();

    } catch (XMLStreamException | IOException e) {
      imp.getLogger().log(Level.SEVERE, e.toString(), e);
    }
  }
Пример #29
0
  void importTransactions(final XMLStreamReader reader) {

    logger.info("Begin transaction import");

    try {
      parse:
      while (reader.hasNext()) {
        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            if (reader.getAttributeCount() > 0
                && reader.getAttributeValue(0).contains("Transaction")) {
              logger.finest("Found the start of a Transaction");
              parseTransaction(reader);
            }
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getLocalName().equals("objects")) {
              logger.fine("Found the end of the object list and transactions");
              break parse;
            }
            break;
          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, e.toString(), e);
    }

    logger.log(Level.INFO, "Generating {0} Split Transactions", splitList.size());

    /* loop through the lists and add split transactions */
    for (Iterator<Map<String, String>> i = splitList.iterator(); i.hasNext(); ) {

      Map<String, String> map = i.next();

      String id = map.get(ID);

      Transaction transaction = new Transaction();

      transaction.setDate(decodeDate(map.get("voucherDate")));
      transaction.setDateEntered(decodeDate(map.get("actTransDate")));
      transaction.setNumber(map.get("number"));
      transaction.setPayee(map.get("payee"));
      transaction.setMemo(map.get("memo"));

      for (Iterator<Map<String, String>> j = this.splitEntryList.iterator(); j.hasNext(); ) {
        Map<String, String> entryMap = j.next();

        if (entryMap.get("parent").equals(id)) {

          TransactionEntry entry = new TransactionEntry();

          entry.setMemo(entryMap.get("memo"));

          Account creditAccount = accountMap.get(entryMap.get("creditAccount"));
          Account debitAccount = accountMap.get(entryMap.get("debitAccount"));

          boolean creditReconciled = Boolean.parseBoolean(entryMap.get("creditReconciled"));
          boolean debitReconciled = Boolean.parseBoolean(entryMap.get("debitReconciled"));

          entry.setCreditAccount(creditAccount);
          entry.setDebitAccount(debitAccount);

          CurrencyNode node = decodeCurrency(entryMap.get("commodity"));
          BigDecimal amount = new BigDecimal(entryMap.get("amount"));

          if (creditAccount.getCurrencyNode().equals(node)) {
            entry.setCreditAmount(amount);
          } else {
            BigDecimal exchangeRate = new BigDecimal(entryMap.get("exchangeRate"));
            entry.setCreditAmount(amount.multiply(exchangeRate));
          }

          if (debitAccount.getCurrencyNode().equals(node)) {
            entry.setDebitAmount(amount.negate());
          } else {
            BigDecimal exchangeRate = new BigDecimal(entryMap.get("exchangeRate"));
            entry.setDebitAmount(amount.multiply(exchangeRate).negate());
          }

          transaction.addTransactionEntry(entry);

          transaction.setReconciled(
              creditAccount,
              creditReconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);

          transaction.setReconciled(
              debitAccount,
              debitReconciled ? ReconciledState.RECONCILED : ReconciledState.NOT_RECONCILED);

          j.remove();
        }
      }

      assert transaction.size() > 0;

      Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

      if (!engine.addTransaction(transaction)) {
        logger.log(Level.SEVERE, "Failed to import transaction: {0}", id);
      }

      i.remove();
    }

    logger.info("Transaction import complete");
  }
Пример #30
0
  @SuppressWarnings({"unchecked", "ConstantConditions"})
  private void parseAccount(final XMLStreamReader reader) {

    assert reader.getAttributeCount() == 2;

    Map<String, Object> elementMap = new HashMap<>();

    /* still at start of the account.  Need to know when end is reached */
    QName parsingElement = reader.getName();

    String accountClass = reader.getAttributeValue(0);
    String accountId = reader.getAttributeValue(1);

    try {
      while (reader.hasNext()) {
        int event = reader.next();

        switch (event) {
          case XMLStreamConstants.START_ELEMENT:
            String element = reader.getLocalName();

            switch (element) {
              case "securities":
                logger.info("Parsing account securities");
                elementMap.put("securities", parseAccountSecurities(reader));
                break;
              case "amortize":
                logger.info("Parsing amortize object");
                elementMap.put("amortize", parseAmortizeObject(reader));
                break;
              case "locked":
                lockMap.put(accountId, Boolean.valueOf(reader.getElementText()));
                break;
              default:
                elementMap.put(element, reader.getElementText());
                break;
            }
            break;
          case XMLStreamConstants.END_ELEMENT:
            if (reader.getName().equals(parsingElement)) {
              logger.finest("Found the end of an Account");

              Account account = generateAccount(accountClass, elementMap);

              if (account != null) {
                accountMap.put(accountId, account);

                // do not put the root account into the parent map
                if (account.getAccountType() != AccountType.ROOT) {
                  parentMap.put(account, (String) elementMap.get("parentAccount"));
                }

                if (account.getAccountType() != AccountType.ROOT) {
                  Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);

                  engine.addAccount(engine.getRootAccount(), account);

                  if (account.getAccountType() == AccountType.LIABILITY) {
                    Map<String, String> amortizeObject =
                        (Map<String, String>) elementMap.get("amortize");

                    if (amortizeObject != null) {
                      AOThread t = new AOThread(account, amortizeObject);
                      workQueue.add(t);
                    }
                  }
                }
              }
              return;
            }
            break;
          default:
            break;
        }
      }
    } catch (XMLStreamException e) {
      logger.log(Level.SEVERE, "Error importing account id: {0}", accountId);
      logger.log(Level.SEVERE, e.toString(), e);
    }
  }