Search in sources :

Example 1 with NotNull

use of jgnash.util.NotNull in project jgnash by ccavanaugh.

the class JpaCommodityDAO method getSecurities.

/*
     * @see jgnash.engine.dao.CommodityDAO#getSecurities()
     */
@Override
@NotNull
public List<SecurityNode> getSecurities() {
    List<SecurityNode> securityNodeList = Collections.emptyList();
    try {
        Future<List<SecurityNode>> future = executorService.submit(() -> {
            emLock.lock();
            try {
                final CriteriaBuilder cb = em.getCriteriaBuilder();
                final CriteriaQuery<SecurityNode> cq = cb.createQuery(SecurityNode.class);
                Root<SecurityNode> root = cq.from(SecurityNode.class);
                cq.select(root);
                TypedQuery<SecurityNode> q = em.createQuery(cq);
                return stripMarkedForRemoval(new ArrayList<>(q.getResultList()));
            } finally {
                emLock.unlock();
            }
        });
        securityNodeList = future.get();
    } catch (final InterruptedException | ExecutionException e) {
        logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
    return securityNodeList;
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) SecurityNode(jgnash.engine.SecurityNode) ArrayList(java.util.ArrayList) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) NotNull(jgnash.util.NotNull)

Example 2 with NotNull

use of jgnash.util.NotNull in project jgnash by ccavanaugh.

the class DecimalTextField method evaluateInput.

/**
     * BigDecimal and the interpreter cannot parse ',' in string
     * representations of decimals. This method will replace any ',' with '.'
     * and then try parsing with BigDecimal. If this fails, then it is assumed
     * that the user has used mathematical operators and then evaluates the
     * string as a mathematical expression.
     *
     * @return A string representation of the resulting decimal
     */
@NotNull
private String evaluateInput() {
    String text = getText();
    if (text == null || text.isEmpty()) {
        return "";
    }
    // strip out any group separators (This could be '.' for certain locales)
    final StringBuilder temp = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c != group) {
            temp.append(c);
        }
    }
    text = temp.toString();
    // replace any ',' with periods so that it javascript parses it correctly
    if (fraction == ',') {
        text = text.replace(',', '.');
    }
    try {
        return new BigDecimal(text).toString();
    } catch (final NumberFormatException nfe) {
        try {
            final Object o = jsEngine.eval(text);
            if (o instanceof Number) {
                // scale the number
                final BigDecimal value = new BigDecimal(o.toString()).setScale(scale.get(), MathConstants.roundingMode);
                decimal.set(value);
                return value.toString();
            }
        } catch (final ScriptException ex) {
            return "";
        }
    }
    return "";
}
Also used : ScriptException(javax.script.ScriptException) BigDecimal(java.math.BigDecimal) NotNull(jgnash.util.NotNull)

Example 3 with NotNull

use of jgnash.util.NotNull in project jgnash by ccavanaugh.

the class Engine method addSecurityHistoryEvent.

/**
     * Add a SecurityHistoryNode node to a SecurityNode.  If the SecurityNode already contains
     * an equivalent SecurityHistoryNode, the old SecurityHistoryNode is removed first.
     *
     * @param node         SecurityNode to add to
     * @param historyEvent SecurityHistoryNode to add
     * @return <tt>true</tt> if successful
     */
public boolean addSecurityHistoryEvent(@NotNull final SecurityNode node, @NotNull final SecurityHistoryEvent historyEvent) {
    dataLock.writeLock().lock();
    try {
        // Remove old history event if it exists, equality is used to work around hibernate optimizations
        // A defensive copy of the old events is used to prevent concurrent modification errors
        new HashSet<>(node.getHistoryEvents()).stream().filter(event -> event.equals(historyEvent)).forEach(event -> removeSecurityHistoryEvent(node, historyEvent));
        boolean status = node.addSecurityHistoryEvent(historyEvent);
        if (status) {
            status = getCommodityDAO().addSecurityHistoryEvent(node, historyEvent);
        }
        Message message;
        if (status) {
            clearCachedAccountBalance(node);
            message = new Message(MessageChannel.COMMODITY, ChannelEvent.SECURITY_HISTORY_EVENT_ADD, this);
        } else {
            message = new Message(MessageChannel.COMMODITY, ChannelEvent.SECURITY_HISTORY_EVENT_ADD_FAILED, this);
        }
        message.setObject(MessageProperty.COMMODITY, node);
        messageBus.fireEvent(message);
        return status;
    } finally {
        dataLock.writeLock().unlock();
    }
}
Also used : EngineDAO(jgnash.engine.dao.EngineDAO) CurrencyUpdateFactory(jgnash.net.currency.CurrencyUpdateFactory) ScheduledFuture(java.util.concurrent.ScheduledFuture) UpdateFactory(jgnash.net.security.UpdateFactory) TimeoutException(java.util.concurrent.TimeoutException) LockManager(jgnash.engine.concurrent.LockManager) MessageBus(jgnash.engine.message.MessageBus) BigDecimal(java.math.BigDecimal) Nullable(jgnash.util.Nullable) Future(java.util.concurrent.Future) Budget(jgnash.engine.budget.Budget) MessageProperty(jgnash.engine.message.MessageProperty) RecurringIterator(jgnash.engine.recurring.RecurringIterator) MessageChannel(jgnash.engine.message.MessageChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DefaultDaemonThreadFactory(jgnash.util.DefaultDaemonThreadFactory) Path(java.nio.file.Path) AttachmentManager(jgnash.engine.attachment.AttachmentManager) NotNull(jgnash.util.NotNull) CancellationException(java.util.concurrent.CancellationException) Collection(java.util.Collection) Set(java.util.Set) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) PendingReminder(jgnash.engine.recurring.PendingReminder) Objects(java.util.Objects) BudgetGoal(jgnash.engine.budget.BudgetGoal) List(java.util.List) LocalDate(java.time.LocalDate) Optional(java.util.Optional) Handler(java.util.logging.Handler) Message(jgnash.engine.message.Message) ConfigDAO(jgnash.engine.dao.ConfigDAO) TrashDAO(jgnash.engine.dao.TrashDAO) LocalDateTime(java.time.LocalDateTime) ResourceUtils(jgnash.util.ResourceUtils) MonthlyReminder(jgnash.engine.recurring.MonthlyReminder) Callable(java.util.concurrent.Callable) CommodityDAO(jgnash.engine.dao.CommodityDAO) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ChannelEvent(jgnash.engine.message.ChannelEvent) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) ResourceBundle(java.util.ResourceBundle) ExecutorService(java.util.concurrent.ExecutorService) DateUtils(jgnash.time.DateUtils) IOException(java.io.IOException) AccountDAO(jgnash.engine.dao.AccountDAO) TransactionDAO(jgnash.engine.dao.TransactionDAO) Reminder(jgnash.engine.recurring.Reminder) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ChronoUnit(java.time.temporal.ChronoUnit) DayOfWeek(java.time.DayOfWeek) BudgetDAO(jgnash.engine.dao.BudgetDAO) Collections(java.util.Collections) CollectionUtils(jgnash.util.CollectionUtils) RecurringDAO(jgnash.engine.dao.RecurringDAO) Message(jgnash.engine.message.Message)

Example 4 with NotNull

use of jgnash.util.NotNull in project jgnash by ccavanaugh.

the class BuyShareSlipController method modifyTransaction.

@Override
public void modifyTransaction(@NotNull final Transaction transaction) {
    if (transaction.getTransactionType() != TransactionType.BUYSHARE || !(transaction instanceof InvestmentTransaction)) {
        throw new IllegalArgumentException(resources.getString("Message.Error.InvalidTransactionType"));
    }
    clearForm();
    datePicker.setValue(transaction.getLocalDate());
    numberComboBox.setValue(transaction.getNumber());
    List<TransactionEntry> entries = transaction.getTransactionEntries();
    feePane.setTransactionEntries(((InvestmentTransaction) transaction).getInvestmentFeeEntries());
    entries.stream().filter(e -> e instanceof TransactionEntryBuyX).forEach(e -> {
        final AbstractInvestmentTransactionEntry entry = (AbstractInvestmentTransactionEntry) e;
        memoTextField.setText(e.getMemo());
        priceField.setDecimal(entry.getPrice());
        quantityField.setDecimal(entry.getQuantity());
        securityComboBox.setSecurityNode(entry.getSecurityNode());
        if (entry.getCreditAccount().equals(accountProperty().get())) {
            accountExchangePane.setSelectedAccount(entry.getDebitAccount());
            accountExchangePane.setExchangedAmount(entry.getDebitAmount().abs());
        } else {
            accountExchangePane.setSelectedAccount(entry.getCreditAccount());
            accountExchangePane.setExchangedAmount(entry.getCreditAmount());
        }
    });
    modTrans = transaction;
    modTrans = attachmentPane.modifyTransaction(modTrans);
    setReconciledState(transaction.getReconciled(accountProperty().get()));
}
Also used : FXML(javafx.fxml.FXML) BigDecimal(java.math.BigDecimal) List(java.util.List) NotNull(jgnash.util.NotNull) Transaction(jgnash.engine.Transaction) TransactionEntryBuyX(jgnash.engine.TransactionEntryBuyX) InvestmentTransaction(jgnash.engine.InvestmentTransaction) ChangeListener(javafx.beans.value.ChangeListener) TransactionEntry(jgnash.engine.TransactionEntry) AbstractInvestmentTransactionEntry(jgnash.engine.AbstractInvestmentTransactionEntry) TransactionFactory(jgnash.engine.TransactionFactory) TransactionType(jgnash.engine.TransactionType) InvestmentTransaction(jgnash.engine.InvestmentTransaction) AbstractInvestmentTransactionEntry(jgnash.engine.AbstractInvestmentTransactionEntry) TransactionEntry(jgnash.engine.TransactionEntry) AbstractInvestmentTransactionEntry(jgnash.engine.AbstractInvestmentTransactionEntry) TransactionEntryBuyX(jgnash.engine.TransactionEntryBuyX)

Example 5 with NotNull

use of jgnash.util.NotNull in project jgnash by ccavanaugh.

the class SlipController method buildTransaction.

@NotNull
@Override
public Transaction buildTransaction() {
    Transaction transaction;
    final LocalDate date = datePicker.getValue();
    if (!transactionEntries.isEmpty()) {
        // build a split transaction
        transaction = new Transaction();
        transaction.setDate(date);
        transaction.setNumber(numberComboBox.getValue());
        transaction.setMemo(Options.concatenateMemosProperty().get() ? Transaction.CONCATENATE : memoTextField.getText());
        transaction.setPayee(payeeTextField.getText());
        transaction.addTransactionEntries(transactionEntries);
    } else {
        // double entry transaction
        final int signum = amountField.getDecimal().signum();
        final Account selectedAccount;
        if (modTrans != null && modTrans.areAccountsHidden()) {
            selectedAccount = getOppositeSideAccount(modTrans);
        } else {
            selectedAccount = accountExchangePane.getSelectedAccount();
        }
        if (slipType == SlipType.DECREASE && signum >= 0 || slipType == SlipType.INCREASE && signum == -1) {
            if (hasEqualCurrencies()) {
                transaction = TransactionFactory.generateDoubleEntryTransaction(selectedAccount, account.get(), amountField.getDecimal().abs(), date, memoTextField.getText(), payeeTextField.getText(), numberComboBox.getValue());
            } else {
                transaction = TransactionFactory.generateDoubleEntryTransaction(selectedAccount, account.get(), accountExchangePane.exchangeAmountProperty().get().abs(), amountField.getDecimal().abs().negate(), date, memoTextField.getText(), payeeTextField.getText(), numberComboBox.getValue());
            }
        } else {
            if (hasEqualCurrencies()) {
                transaction = TransactionFactory.generateDoubleEntryTransaction(account.get(), selectedAccount, amountField.getDecimal().abs(), date, memoTextField.getText(), payeeTextField.getText(), numberComboBox.getValue());
            } else {
                transaction = TransactionFactory.generateDoubleEntryTransaction(account.get(), selectedAccount, amountField.getDecimal().abs(), accountExchangePane.exchangeAmountProperty().get().abs().negate(), date, memoTextField.getText(), payeeTextField.getText(), numberComboBox.getValue());
            }
        }
    }
    ReconcileManager.reconcileTransaction(account.get(), transaction, getReconciledState());
    return transaction;
}
Also used : Account(jgnash.engine.Account) Transaction(jgnash.engine.Transaction) InvestmentTransaction(jgnash.engine.InvestmentTransaction) LocalDate(java.time.LocalDate) NotNull(jgnash.util.NotNull)

Aggregations

NotNull (jgnash.util.NotNull)17 Transaction (jgnash.engine.Transaction)13 BigDecimal (java.math.BigDecimal)10 InvestmentTransaction (jgnash.engine.InvestmentTransaction)9 List (java.util.List)6 AbstractInvestmentTransactionEntry (jgnash.engine.AbstractInvestmentTransactionEntry)6 TransactionEntry (jgnash.engine.TransactionEntry)6 ChangeListener (javafx.beans.value.ChangeListener)4 FXML (javafx.fxml.FXML)4 LocalDate (java.time.LocalDate)3 ArrayList (java.util.ArrayList)3 TransactionFactory (jgnash.engine.TransactionFactory)3 TransactionType (jgnash.engine.TransactionType)3 Collections (java.util.Collections)2 Objects (java.util.Objects)2 ResourceBundle (java.util.ResourceBundle)2 ExecutionException (java.util.concurrent.ExecutionException)2 Logger (java.util.logging.Logger)2 Preferences (java.util.prefs.Preferences)2 Collectors (java.util.stream.Collectors)2