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); } }
@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(); } } }
private CurrencyNode decodeCurrency(final String currency) { // Check if the currency is already in the cache. if (currencyCache.containsKey(currency)) { return currencyCache.get(currency); } String split[] = CURRENCY_DELIMITER_PATTERN.split(currency); String symbol = split[0]; CurrencyNode node = EngineFactory.getEngine(EngineFactory.DEFAULT).getCurrency(symbol); if (node == null) { logger.log(Level.INFO, "Converting a commodity into a currency: {0}", symbol); Commodity cNode = commodityMap.get(symbol); if (cNode != null) { node = new CurrencyNode(); node.setDescription(cNode.description); node.setPrefix(cNode.prefix); node.setSuffix(cNode.suffix); node.setScale(cNode.scale); node.setSymbol(cNode.symbol); EngineFactory.getEngine(EngineFactory.DEFAULT).addCurrency(node); } else { // Convert security to currency. For users who figured out how to push the limits of the // jGnash 1.x commodity interface SecurityNode sNode = EngineFactory.getEngine(EngineFactory.DEFAULT).getSecurity(symbol); if (sNode != null) { node = new CurrencyNode(); node.setDescription(sNode.getDescription()); node.setPrefix(sNode.getPrefix()); node.setSuffix(sNode.getSuffix()); node.setScale(sNode.getScale()); node.setSymbol(sNode.getSymbol()); EngineFactory.getEngine(EngineFactory.DEFAULT).addCurrency(node); } else { logger.log(Level.SEVERE, "Bad file, currency " + symbol + " not mapped", new Exception()); } } } // Put the currency in the cache. currencyCache.put(currency, node); return node; }
private void initComponents() { final Resource rb = Resource.get(); setTitle(rb.getString("Title.DefTranNum")); okButton = new JButton(rb.getString("Button.Ok")); cancelButton = new JButton(rb.getString("Button.Cancel")); insertButton = new JButton(rb.getString("Button.Insert")); removeButton = new JButton(rb.getString("Button.Remove")); upButton = new JButton(Resource.getIcon("/jgnash/resource/stock_up-16.png")); downButton = new JButton(Resource.getIcon("/jgnash/resource/stock_down-16.png")); insertButton.addActionListener(this); cancelButton.addActionListener(this); okButton.addActionListener(this); removeButton.addActionListener(this); upButton.addActionListener(this); downButton.addActionListener(this); model = new DefaultListModel<>(); final List<String> items = EngineFactory.getEngine(EngineFactory.DEFAULT).getTransactionNumberList(); for (String s : items) { model.addElement(s); } list = new JList<>(model); entryField = new JTextFieldEx(10); }
@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; }
@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); }
private void initComponents() { accountCombo = new AccountListComboBox(); helpPane = new JTextPane(); helpPane.setEditable(false); helpPane.setEditorKit(new StyledEditorKit()); helpPane.setBackground(getBackground()); helpPane.setText(TextResource.getString("QifOne.txt")); /* Create the combo for date format selection */ String[] formats = {QifUtils.US_FORMAT, QifUtils.EU_FORMAT}; dateFormatCombo = new JComboBox<>(formats); dateFormatCombo.addActionListener(this); dateFormatCombo.setSelectedIndex(pref.getInt(DATE_FORMAT, 0)); accountCombo.addActionListener(this); /* Try a set the combobox to the last selected account */ String lastAccount = pref.get(LAST_ACCOUNT, ""); Account last = EngineFactory.getEngine(EngineFactory.DEFAULT).getAccountByUuid(lastAccount); if (last != null) { setAccount(last); } }
public static void setUpdateOnStartup(final boolean update) { final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT); if (engine != null) { engine.putBoolean(UPDATE_ON_STARTUP, update); } }
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("======================================================"); }
@FXML private void updateCurrencies() { final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT); Objects.requireNonNull(engine); engine.startExchangeRateUpdate(0); }
void scrollToTop() { RootAccount rootAccount = EngineFactory.getEngine(EngineFactory.DEFAULT).getRootAccount(); if (rootAccount != null) { tree.scrollPathToVisible(new TreePath(rootAccount)); // scroll to the top } }
@FXML private void handleExitAction() { if (EngineFactory.getEngine(EngineFactory.DEFAULT) != null) { CloseFileTask.initiateShutdown(); } else { Platform.exit(); } }
@FXML private void updateSecurities() { final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT); Objects.requireNonNull(engine); engine.startSecuritiesUpdate(0); }
@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")); } } }
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; }
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); } }
private void okAction() { final ListModel<String> listModel = list.getModel(); final int size = listModel.getSize(); final List<String> items = new ArrayList<>(); for (int i = 0; i < size; i++) { items.add(listModel.getElementAt(i)); } EngineFactory.getEngine(EngineFactory.DEFAULT).setTransactionNumberList(items); close(); }
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; }
private List<Transaction> _getPrintableTransactions() { List<Transaction> l = new ArrayList<>(); for (Transaction t : EngineFactory.getEngine(EngineFactory.DEFAULT).getTransactions()) { if (PRINT.equalsIgnoreCase(t.getNumber())) { l.add(t); } } Collections.sort(l); // use natural sort order return l; }
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"); }
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); } } }
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); } }
@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(); } }); } }
@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); } }
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); } }
/** * 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; }
@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; }
@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); }
@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; }
@FXML private void handleCloseAction() { if (EngineFactory.getEngine(EngineFactory.DEFAULT) != null) { CloseFileTask.initiateFileClose(); } }