Example usage for java.math BigDecimal ZERO

List of usage examples for java.math BigDecimal ZERO

Introduction

In this page you can find the example usage for java.math BigDecimal ZERO.

Prototype

BigDecimal ZERO

To view the source code for java.math BigDecimal ZERO.

Click Source Link

Document

The value 0, with a scale of 0.

Usage

From source file:com.sasav.blackjack.service.AccountMaster.java

public AccountTransaction createTransactionForUser(String username) {
    Account account = accountDao.getAccountByUsername(username);
    if (account != null) {
        return new AccountTransaction(account, BigDecimal.ZERO, TransactionType.BLANK);
    } else {/*from w w  w. j ava 2  s  .  co  m*/
        return null;
    }

}

From source file:org.ng200.openolympus.services.SolutionService.java

public BigDecimal getSolutionScore(final Solution solution) {
    if (solution == null) {
        return BigDecimal.ZERO;
    }//from  ww  w.  ja  v  a2  s  .c  o m
    return this.getVerdicts(solution).stream().map((verdict) -> verdict.getScore()).reduce((x, y) -> x.add(y))
            .orElse(BigDecimal.ZERO);
}

From source file:br.ufac.sion.service.retorno.ArquivoRetornoCaixaService.java

private void carregarTitulos(ArquivoRetornoCaixa arquivoRetorno) {
    Map<Integer, Collection<SegmentoT>> titulosPorOcorrencia = arquivoRetorno
            .getTransacoesPorCodigoDeOcorrencia();
    BigDecimal valorTotal = BigDecimal.ZERO;
    int totalTitulosPagos = 0;
    for (SegmentoT t : titulosPorOcorrencia.get(SegmentoU.LIQUIDACAO)) {
        br.ufac.sion.model.Boleto cobranca = this.boletoFacade.findByNossoNumero(t.getNossoNumero());
        if (cobranca != null) {
            if (t.getSegmentoU().getValorPago().compareTo(cobranca.getValor()) >= 0) {
                cobranca.getSacado().setStatus(SituacaoInscricao.CONFIRMADA);
                cobranca.getSacado()//from   ww  w  .j a v  a 2 s  .co m
                        .setJustificativaStatus("Confirmao automtica (via arquivo de retorno)");
                cobranca.getSacado().setDataJustificativaStatus(LocalDateTime.now());
                cobranca.setSituacao(SituacaoBoleto.PAGO);
                cobranca.setDataPagamento(
                        DateConversor.convertDateToLocalDate(t.getSegmentoU().getDataOcorrencia()));
                cobranca.setValorPago(t.getSegmentoU().getValorPago());
                cobranca.setArquivo(ar);
                this.ard.getIncricoesConfirmadas().add(cobranca.getSacado());
                totalTitulosPagos++;
            }
        }
        valorTotal.add(t.getValor());
    }
    this.ard.setTotalTitulosPagos(totalTitulosPagos);
    this.ard.setValorTotalEmCobrancas(valorTotal);
}

From source file:com.opensourcestrategies.financials.accounts.GLAccountInTree.java

/**
 * Gets the balance of this GL account children GL accounts.
 * @return a <code>BigDecimal</code> value
 */// w w  w.  j av a  2s  . c o m
public BigDecimal getBalanceOfChildren() {
    BigDecimal balanceOfChildren = BigDecimal.ZERO;
    for (GLAccountInTree childAccount : childAccounts) {
        balanceOfChildren = balanceOfChildren.add(getBalanceOfChildrenRec(childAccount));
    }
    return balanceOfChildren.setScale(AccountsHelper.decimals, AccountsHelper.rounding);
}

From source file:com.benfante.minimark.po.FixedAnswerFilling.java

@Transient
public BigDecimal getNotNullWeight() {
    // return this.getWeight();
    return this.getWeight() != null ? this.getWeight() : BigDecimal.ZERO;
}

From source file:lcn.module.batch.web.guide.service.TradeWriter.java

@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
    if (executionContext.containsKey(TOTAL_AMOUNT_KEY)) {
        this.totalPrice = (BigDecimal) executionContext.get(TOTAL_AMOUNT_KEY);
    } else {/* w  ww . j av  a2s.  com*/
        this.totalPrice = BigDecimal.ZERO;
    }
}

From source file:jgnash.convert.exportantur.csv.CsvExport.java

public static void exportAccount(final Account account, final LocalDate startDate, final LocalDate endDate,
        final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);

    // force a correct file extension
    final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".csv";

    final CSVFormat csvFormat = CSVFormat.EXCEL.withQuoteMode(QuoteMode.ALL);

    try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
            Files.newOutputStream(Paths.get(fileName)), StandardCharsets.UTF_8);
            final CSVPrinter writer = new CSVPrinter(new BufferedWriter(outputStreamWriter), csvFormat)) {

        outputStreamWriter.write('\ufeff'); // write UTF-8 byte order mark to the file for easier imports

        writer.printRecord("Account", "Number", "Debit", "Credit", "Balance", "Date", "Timestamp", "Memo",
                "Payee", "Reconciled");

        // write the transactions
        final List<Transaction> transactions = account.getTransactions(startDate, endDate);

        final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2).toFormatter();

        final DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendLiteral('-').appendValue(MONTH_OF_YEAR, 2).appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2).appendLiteral(' ').appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2)
                .toFormatter();/*from w  w  w.java 2 s  .  co  m*/

        for (final Transaction transaction : transactions) {
            final String date = dateTimeFormatter.format(transaction.getLocalDate());

            final String timeStamp = timestampFormatter.format(transaction.getTimestamp());

            final String credit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) < 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String debit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) > 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String balance = account.getBalanceAt(transaction).toPlainString();

            final String reconciled = transaction.getReconciled(account) == ReconciledState.NOT_RECONCILED
                    ? Boolean.FALSE.toString()
                    : Boolean.TRUE.toString();

            writer.printRecord(account.getName(), transaction.getNumber(), debit, credit, balance, date,
                    timeStamp, transaction.getMemo(), transaction.getPayee(), reconciled);
        }
    } catch (final IOException e) {
        Logger.getLogger(CsvExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:com.griddynamics.jagger.engine.e1.scenario.DefaultWorkloadSuggestionMaker.java

@Override
public WorkloadConfiguration suggest(BigDecimal desiredTps, NodeTpsStatistics statistics, int maxThreads) {
    log.debug("Going to suggest workload configuration. desired tps {}. statistics {}", desiredTps, statistics);

    Table<Integer, Integer, Pair<Long, BigDecimal>> threadDelayStats = statistics.getThreadDelayStats();

    if (areEqual(desiredTps, BigDecimal.ZERO)) {
        return WorkloadConfiguration.with(0, 0);
    }//from w  w  w .j  av a2 s.  c  o m

    if (threadDelayStats.isEmpty()) {
        throw new IllegalArgumentException("Cannot suggest workload configuration");
    }

    if (!threadDelayStats.contains(CALIBRATION_CONFIGURATION.getThreads(),
            CALIBRATION_CONFIGURATION.getDelay())) {
        log.debug("Statistics is empty. Going to return calibration info.");
        return CALIBRATION_CONFIGURATION;
    }
    if (threadDelayStats.size() == 2 && areEqual(threadDelayStats.get(1, 0).getSecond(), BigDecimal.ZERO)) {
        log.warn("No calibration info. Going to retry.");
        return CALIBRATION_CONFIGURATION;
    }

    Map<Integer, Pair<Long, BigDecimal>> noDelays = threadDelayStats.column(0);

    log.debug("Calculate next thread count");
    Integer threadCount = findClosestPoint(desiredTps, noDelays);

    if (threadCount == 0) {
        threadCount = 1;
    }

    if (threadCount > maxThreads) {
        log.warn("{} calculated max {} allowed", threadCount, maxThreads);
        threadCount = maxThreads;
    }

    int currentThreads = statistics.getCurrentWorkloadConfiguration().getThreads();
    int diff = threadCount - currentThreads;
    if (diff > maxDiff) {
        log.debug("Increasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        return WorkloadConfiguration.with(currentThreads + maxDiff, 0);
    }

    diff = currentThreads - threadCount;
    if (diff > maxDiff) {
        log.debug("Decreasing to {} is required current thread count is {} max allowed diff is {}",
                new Object[] { threadCount, currentThreads, maxDiff });
        if ((currentThreads - maxDiff) > 1) {
            return WorkloadConfiguration.with(currentThreads - maxDiff, 0);
        } else {
            return WorkloadConfiguration.with(1, 0);
        }
    }

    if (!threadDelayStats.contains(threadCount, 0)) {
        return WorkloadConfiguration.with(threadCount, 0);
    }

    // <delay, <timestamp,tps>>
    Map<Integer, Pair<Long, BigDecimal>> delays = threadDelayStats.row(threadCount);

    // not enough statistics to calculate
    if (delays.size() == 1) {
        int delay = 0;
        BigDecimal tpsFromStat = delays.get(0).getSecond();

        // try to guess
        // tpsFromStat can be zero if no statistics was captured till this time
        if ((tpsFromStat.compareTo(BigDecimal.ZERO) > 0) && (desiredTps.compareTo(BigDecimal.ZERO) > 0)) {

            BigDecimal oneSecond = new BigDecimal(TimeUtils.secondsToMillis(1));
            BigDecimal result = oneSecond.multiply(new BigDecimal(threadCount)).divide(desiredTps, 3,
                    BigDecimal.ROUND_HALF_UP);
            result = result.subtract(oneSecond.multiply(new BigDecimal(threadCount)).divide(tpsFromStat, 3,
                    BigDecimal.ROUND_HALF_UP));

            delay = result.intValue();
        }
        // to have some non zero point in statistics
        if (delay == 0) {
            delay = MIN_DELAY;
        }

        delay = checkDelayInRange(delay);
        return WorkloadConfiguration.with(threadCount, delay);
    }

    log.debug("Calculate next delay");
    Integer delay = findClosestPoint(desiredTps, threadDelayStats.row(threadCount));

    delay = checkDelayInRange(delay);
    return WorkloadConfiguration.with(threadCount, delay);

}

From source file:com.nabla.project.visma.House.java

/**
 * Validate immutable data like BigDecimal.
 * It raise the exception IllegalArgumentException when arguments are wrong
 *//*  ww  w. j  av a  2s . c o m*/
private void validateState() {
    if (null == this.price) // NOPMD
    {
        throw new IllegalArgumentException("Price cannot be null");
    }
    if (this.price.compareTo(BigDecimal.ZERO) <= 0) // NOPMD
    {
        throw new IllegalArgumentException("Amount must not be negatif or zero");
    }
}

From source file:mobi.nordpos.catalog.action.ProductCreateActionBean.java

public Resolution add() {
    Product product = getProduct();// w  w  w . j  av  a 2 s .c o m
    product.setId(UUID.randomUUID().toString());
    try {
        productPersist.init(getDataBaseConnection());
        taxPersist.init(getDataBaseConnection());
        product.setTax(taxPersist.read(product.getTaxCategory().getId()));
        BigDecimal taxRate = product.getTax().getRate();

        if (getIsTaxInclude() && taxRate != BigDecimal.ZERO) {
            BigDecimal bdTaxRateMultiply = taxRate.add(BigDecimal.ONE);
            product.setPriceSell(product.getPriceSell().divide(bdTaxRateMultiply, MathContext.DECIMAL64));
        }

        getContext().getMessages().add(new SimpleMessage(getLocalizationKey("message.Product.added"),
                productPersist.add(product).getName(), product.getProductCategory().getName()));
    } catch (SQLException ex) {
        getContext().getValidationErrors().addGlobalError(new SimpleError(ex.getMessage()));
        return getContext().getSourcePageResolution();
    }
    return new ForwardResolution(CategoryProductListActionBean.class).addParameter("category.id",
            product.getProductCategory().getId());
}