Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java

public boolean isPositive(BigDecimal value) {
    if (value == null) {
        return true;
    }// w  w w .j a  v  a 2  s.  c o m
    return value.compareTo(BigDecimal.ZERO) > 0;
}

From source file:com.ibm.soatf.component.soap.builder.SampleXmlUtil.java

private String formatDecimal(String start, SchemaType sType) {
    BigDecimal result = new BigDecimal(start);
    XmlDecimal xmlD;/* ww w.  ja  va  2 s . com*/
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
    BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
    BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null;
    boolean minInclusive = true, maxInclusive = true;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal minExcl = xmlD.getBigDecimalValue();
        if (min == null || min.compareTo(minExcl) < 0) {
            min = minExcl;
            minInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal maxExcl = xmlD.getBigDecimalValue();
        if (max == null || max.compareTo(maxExcl) > 0) {
            max = maxExcl;
            maxInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS);
    int totalDigits = -1;
    if (xmlD != null) {
        totalDigits = xmlD.getBigDecimalValue().intValue();

        StringBuilder sb = new StringBuilder(totalDigits);
        for (int i = 0; i < totalDigits; i++)
            sb.append('9');
        BigDecimal digitsLimit = new BigDecimal(sb.toString());
        if (max != null && max.compareTo(digitsLimit) > 0) {
            max = digitsLimit;
            maxInclusive = true;
        }
        digitsLimit = digitsLimit.negate();
        if (min != null && min.compareTo(digitsLimit) < 0) {
            min = digitsLimit;
            minInclusive = true;
        }
    }

    int sigMin = min == null ? 1 : result.compareTo(min);
    int sigMax = max == null ? -1 : result.compareTo(max);
    boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive;
    boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive;

    // Compute the minimum increment
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS);
    int fractionDigits = -1;
    BigDecimal increment;
    if (xmlD == null)
        increment = new BigDecimal(1);
    else {
        fractionDigits = xmlD.getBigDecimalValue().intValue();
        if (fractionDigits > 0) {
            StringBuilder sb = new StringBuilder("0.");
            for (int i = 1; i < fractionDigits; i++)
                sb.append('0');
            sb.append('1');
            increment = new BigDecimal(sb.toString());
        } else
            increment = new BigDecimal(1);
    }

    if (minOk && maxOk) {
        // OK
    } else if (minOk && !maxOk) {
        // TOO BIG
        if (maxInclusive)
            result = max;
        else
            result = max.subtract(increment);
    } else if (!minOk && maxOk) {
        // TOO SMALL
        if (minInclusive)
            result = min;
        else
            result = min.add(increment);
    } else {
        // MIN > MAX!!
    }

    // We have the number
    // Adjust the scale according to the totalDigits and fractionDigits
    int digits = 0;
    BigDecimal ONE = new BigDecimal(BigInteger.ONE);
    for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++)
        n = n.movePointLeft(1);

    if (fractionDigits > 0)
        if (totalDigits >= 0)
            result.setScale(Math.max(fractionDigits, totalDigits - digits));
        else
            result.setScale(fractionDigits);
    else if (fractionDigits == 0)
        result.setScale(0);

    return result.toString();
}

From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java

public boolean isInRange(BigDecimal value, int min, int max) {
    if (value == null) {
        return true;
    }//from w ww .j av a  2  s.  c om
    return !((value.compareTo(new BigDecimal(min)) > 0) && (value.compareTo(new BigDecimal(max)) < 0));
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractBillingController.java

@RequestMapping(value = "/make_payment", method = RequestMethod.POST)
@ResponseBody/*from  w w w .j a  v  a  2s.  c om*/
public String makePayment(@RequestParam BigDecimal amount, @RequestParam String memo,
        @RequestParam String tenantParam, HttpSession session, HttpServletResponse response) {
    logger.debug("###Entering in makePaymentInvoice(tenantId,invoiceId,form, amount,response) method @POST");
    try {
        Tenant tenant = tenantService.get(tenantParam);
        BigDecimal paymentAmount = billingPostProcessor.setScaleByCurrency(amount, tenant.getCurrency());
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            return "failed";
        }
        SalesLedgerRecord salesLedgerRecord = billingService.addPaymentOrCredit(tenant, paymentAmount,
                Type.MANUAL, memo, null);
        if (salesLedgerRecord != null && salesLedgerRecord.getPaymentTransaction().getState()
                .equals(PaymentTransaction.State.COMPLETED)) {
            response.setStatus(HttpStatus.OK.value());
            logger.debug("###Exiting makePaymentInvoice(tenantId,form ,response) method @POST");

            String message = "payment.received";
            String messageArgs = tenant.getName();
            eventService.createEvent(new Date(), tenant, message, messageArgs, Source.PORTAL, Scope.ACCOUNT,
                    Category.ACCOUNT, Severity.INFORMATION, true);

            return "success";
        }
        response.setStatus(HttpStatus.OK.value());
        logger.debug(
                "###Exiting makePaymentInvoice(tenantId,form ,response) method @POST. Failed to make the payment.");
        return "failed";

    } catch (BillingServiceException e) {
        session.setAttribute("makepayment_status", "false");
        response.setStatus(HttpStatus.OK.value());
        logger.debug(
                "###Exiting makePaymentInvoice(tenantId,form ,response) method @POST. Failed to make the payment.");
        return "failed";
    }

}

From source file:com.nkapps.billing.dao.OverpaymentDaoImpl.java

@Override
public BankStatement saveReturnState(String bankStatementId, Short returnState, BigDecimal returnSum,
        Long issuerSerialNumber, String issuerIp) throws Exception {
    Session session = getSession();/*from w w w.j a  v  a  2  s . c o m*/
    Transaction transaction = session.beginTransaction();

    BankStatement bs = (BankStatement) session.get(BankStatement.class, bankStatementId);
    String q = "SELECT COALESCE(bs.paymentSum,0) - COALESCE(bs.returnSum,0) - (SELECT COALESCE(SUM(kp.paidSum),0) FROM bs.bankStatementPayments bsp JOIN bsp.id.payment p JOIN p.keyPayments kp WHERE p.claim = 0) AS overpaymentSum"
            + " FROM BankStatement bs" + " WHERE bs = :bs";
    Query query = session.createQuery(q);
    query.setParameter("bs", bs);
    BigDecimal overpaymentSum = (BigDecimal) query.uniqueResult();

    LocalDateTime dateTime = LocalDateTime.now();

    if (returnState == 0) {
        if (bs.getReturnSum() != null) { // get all overpayment sum
            overpaymentSum = overpaymentSum.add(bs.getReturnSum());
        }
        bs.setReturnState(returnState);
        bs.setReturnSum(null);
        bs.setIssuerSerialNumber(issuerSerialNumber);
        bs.setIssuerIp(issuerIp);
        bs.setDateUpdated(dateTime);

        session.update(bs);

        returnStateRevert(session, bs, overpaymentSum, issuerSerialNumber, issuerIp, dateTime);

    } else {
        if (returnSum.compareTo(overpaymentSum) > 0) { // checking return sum must not be greater than overpayment sum
            returnSum = overpaymentSum;
        }

        bs.setReturnState(returnState);
        if (bs.getReturnSum() != null) {
            bs.setReturnSum(bs.getReturnSum().add(returnSum));
        } else {
            bs.setReturnSum(returnSum);
        }
        bs.setIssuerSerialNumber(issuerSerialNumber);
        bs.setIssuerIp(issuerIp);
        bs.setDateUpdated(dateTime);

        session.update(bs);

        returnStateCommit(session, bs, returnSum, issuerSerialNumber, issuerIp, dateTime);
    }

    transaction.commit();
    session.close();
    return bs;
}

From source file:com.centeractive.ws.builder.soap.SampleXmlUtil.java

private String formatDecimal(String start, SchemaType sType) {
    BigDecimal result = new BigDecimal(start);
    XmlDecimal xmlD;/*from   w ww  .  ja va  2  s.  c  o  m*/
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_INCLUSIVE);
    BigDecimal min = xmlD != null ? xmlD.getBigDecimalValue() : null;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_INCLUSIVE);
    BigDecimal max = xmlD != null ? xmlD.getBigDecimalValue() : null;
    boolean minInclusive = true, maxInclusive = true;
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MIN_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal minExcl = xmlD.getBigDecimalValue();
        if (min == null || min.compareTo(minExcl) < 0) {
            min = minExcl;
            minInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_MAX_EXCLUSIVE);
    if (xmlD != null) {
        BigDecimal maxExcl = xmlD.getBigDecimalValue();
        if (max == null || max.compareTo(maxExcl) > 0) {
            max = maxExcl;
            maxInclusive = false;
        }
    }
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_TOTAL_DIGITS);
    int totalDigits = -1;
    if (xmlD != null) {
        totalDigits = xmlD.getBigDecimalValue().intValue();

        StringBuffer sb = new StringBuffer(totalDigits);
        for (int i = 0; i < totalDigits; i++)
            sb.append('9');
        BigDecimal digitsLimit = new BigDecimal(sb.toString());
        if (max != null && max.compareTo(digitsLimit) > 0) {
            max = digitsLimit;
            maxInclusive = true;
        }
        digitsLimit = digitsLimit.negate();
        if (min != null && min.compareTo(digitsLimit) < 0) {
            min = digitsLimit;
            minInclusive = true;
        }
    }

    int sigMin = min == null ? 1 : result.compareTo(min);
    int sigMax = max == null ? -1 : result.compareTo(max);
    boolean minOk = sigMin > 0 || sigMin == 0 && minInclusive;
    boolean maxOk = sigMax < 0 || sigMax == 0 && maxInclusive;

    // Compute the minimum increment
    xmlD = (XmlDecimal) sType.getFacet(SchemaType.FACET_FRACTION_DIGITS);
    int fractionDigits = -1;
    BigDecimal increment;
    if (xmlD == null)
        increment = new BigDecimal(1);
    else {
        fractionDigits = xmlD.getBigDecimalValue().intValue();
        if (fractionDigits > 0) {
            StringBuffer sb = new StringBuffer("0.");
            for (int i = 1; i < fractionDigits; i++)
                sb.append('0');
            sb.append('1');
            increment = new BigDecimal(sb.toString());
        } else
            increment = new BigDecimal(1);
    }

    if (minOk && maxOk) {
        // OK
    } else if (minOk && !maxOk) {
        // TOO BIG
        if (maxInclusive)
            result = max;
        else
            result = max.subtract(increment);
    } else if (!minOk && maxOk) {
        // TOO SMALL
        if (minInclusive)
            result = min;
        else
            result = min.add(increment);
    } else {
        // MIN > MAX!!
    }

    // We have the number
    // Adjust the scale according to the totalDigits and fractionDigits
    int digits = 0;
    BigDecimal ONE = new BigDecimal(BigInteger.ONE);
    for (BigDecimal n = result; n.abs().compareTo(ONE) >= 0; digits++)
        n = n.movePointLeft(1);

    if (fractionDigits > 0)
        if (totalDigits >= 0)
            result.setScale(Math.max(fractionDigits, totalDigits - digits));
        else
            result.setScale(fractionDigits);
    else if (fractionDigits == 0)
        result.setScale(0);

    return result.toString();
}

From source file:org.efaps.esjp.accounting.transaction.Recalculate_Base.java

/**
 * Method for recalculate and return string.
 *
 * @param _parameter Parameter as passed from the eFaps API.
 * @param _docInst Instance of the document selected.
 * @return String./*from   w  ww . j  av a  2 s.  c om*/
 * @throws EFapsException on error.
 */
protected String getRecalculateInfo(final Parameter _parameter, final Instance _docInst) throws EFapsException {
    final StringBuilder html = new StringBuilder();
    final PrintQuery print = new PrintQuery(_docInst);
    print.addAttribute(CISales.DocumentSumAbstract.RateCrossTotal, CISales.DocumentSumAbstract.CrossTotal,
            CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CurrencyId,
            CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
    print.execute();

    final BigDecimal rateCross = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.RateCrossTotal);
    final BigDecimal crossTotal = print.<BigDecimal>getAttribute(CISales.DocumentSumAbstract.CrossTotal);
    final String nameDoc = print.<String>getAttribute(CISales.DocumentSumAbstract.Name);
    final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.RateCurrencyId));
    final Instance currentInst = Instance.get(CIERP.Currency.getType(),
            print.<Long>getAttribute(CISales.DocumentSumAbstract.CurrencyId));
    final CurrencyInst tarCurr = new CurrencyInst(targetCurrInst);
    final CurrencyInst curr = new CurrencyInst(currentInst);

    final PriceUtil priceUtil = new PriceUtil();
    final BigDecimal[] rates = priceUtil.getRates(_parameter, targetCurrInst, currentInst);
    final BigDecimal rate = rates[2];

    final BigDecimal newCrossTotal = rateCross.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO
            : rateCross.divide(rate, BigDecimal.ROUND_HALF_UP);
    final BigDecimal gainloss = newCrossTotal.subtract(crossTotal);

    final Map<String, String[]> map = validateInfo(_parameter, gainloss);
    final String[] accs = map.get("accs");
    final String[] check = map.get("check");

    html.append("<table>").append("<tr>").append("<td>").append(DBProperties.getProperty("Sales_Invoice.Label"))
            .append("</td>").append("<td colspan=\"2\">").append(nameDoc).append("</td>").append("</tr>")
            .append("<td>").append(DBProperties.getProperty("Sales_DocumentAbstract/RateCrossTotal.Label"))
            .append("</td>").append("<td>").append(rateCross).append(" ").append(tarCurr.getSymbol())
            .append("</td>").append("<td>").append(crossTotal).append(" ").append(curr.getSymbol())
            .append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.newTotal.Label"))
            .append("</td>").append("<td colspan=\"2\" align=\"right\">").append(newCrossTotal).append(" ")
            .append(curr.getSymbol()).append("</td>").append("</tr>").append("<tr>").append("<td>");
    if (gainloss.compareTo(BigDecimal.ZERO) == -1) {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.loss.Label"));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.gain.Label"));
    }
    html.append("</td>").append("<td colspan=\"2\" align=\"right\">").append(gainloss.abs()).append(" ")
            .append(curr.getSymbol()).append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionPositionDebit.Label")).append("</td>")
            .append("<td colspan=\"2\" align=\"right\">");
    if (checkAccounts(accs, 0, check).length() > 0) {
        html.append(checkAccounts(accs, 0, check));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.reviseConfig.Label"));
    }
    html.append("</td>").append("</tr>").append("<tr>").append("<td>")
            .append(DBProperties.getProperty("Accounting_TransactionPositionCredit.Label")).append("</td>")
            .append("<td colspan=\"2\" align=\"right\">");
    if (checkAccounts(accs, 1, check).length() > 0) {
        html.append(checkAccounts(accs, 1, check));
    } else {
        html.append(DBProperties.getProperty("Accounting_TransactionRecalculateForm.reviseConfig.Label"));
    }
    html.append("</td>").append("</tr>").append("</table>");
    return html.toString();
}

From source file:nl.strohalm.cyclos.services.groups.GroupServiceImpl.java

private Validator getAccountSettingsValidator() {
    final Validator accountSettingsValidator = new Validator("account");
    accountSettingsValidator.property("group").displayName("group").required();
    accountSettingsValidator.property("accountType").displayName("account type").required();
    accountSettingsValidator.property("initialCredit").positive();
    accountSettingsValidator.general(new GeneralValidation() {
        private static final long serialVersionUID = 1L;

        @Override/*from   w w  w .  j a  v  a 2s.  c  o  m*/
        public ValidationError validate(final Object object) {

            final MemberGroupAccountSettings mgas = (MemberGroupAccountSettings) object;
            if (mgas.getInitialCreditTransferType() != null) {
                TransferType tt = fetchService.fetch(mgas.getInitialCreditTransferType());
                BigDecimal minAmount = tt.getMinAmount();
                BigDecimal initialCredit = mgas.getInitialCredit();
                boolean initialCreditIsPossitive = initialCredit != null
                        && initialCredit.compareTo(new BigDecimal(0)) > 0;

                if (initialCreditIsPossitive && minAmount != null && (initialCredit.compareTo(minAmount) < 0)) {
                    return new ValidationError("group.account.error.minInitialCredit", initialCredit,
                            minAmount);
                }
            }
            return null;
        }
    });
    accountSettingsValidator.property("initialCreditTransferType").add(new PropertyValidation() {
        private static final long serialVersionUID = 8284432136349418154L;

        @Override
        public ValidationError validate(final Object object, final Object name, final Object value) {
            final MemberGroupAccountSettings mgas = (MemberGroupAccountSettings) object;
            final TransferType tt = fetchService.fetch((TransferType) value, TransferType.Relationships.FROM,
                    TransferType.Relationships.TO);

            final BigDecimal initialCredit = mgas.getInitialCredit();
            // When there is initial credit, there must be a transfer type
            if (initialCredit != null && (initialCredit.compareTo(BigDecimal.ZERO) == 1) && tt == null) {
                return new RequiredError();
            }
            // Must be from system to member
            if (tt != null && !(tt.isFromSystem() && !tt.isToSystem())) {
                return new InvalidError();
            }
            return null;
        }
    });
    accountSettingsValidator.property("defaultCreditLimit").required().positive();
    accountSettingsValidator.property("defaultUpperCreditLimit").positive();
    accountSettingsValidator.property("lowUnits").positive();
    accountSettingsValidator.property("lowUnitsMessage").add(new PropertyValidation() {
        private static final long serialVersionUID = -6086632981851357180L;

        @Override
        public ValidationError validate(final Object object, final Object name, final Object value) {
            final MemberGroupAccountSettings mgas = (MemberGroupAccountSettings) object;
            final BigDecimal lowUnits = mgas.getLowUnits();
            // When there are low units, the message is required
            if (lowUnits != null && (lowUnits.compareTo(BigDecimal.ZERO) == 1)
                    && StringUtils.isEmpty(mgas.getLowUnitsMessage())) {
                return new RequiredError();
            }
            return null;
        }
    });
    return accountSettingsValidator;
}

From source file:com.gst.accounting.journalentry.service.JournalEntryWritePlatformServiceJpaRepositoryImpl.java

private void checkDebitAndCreditAmounts(final SingleDebitOrCreditEntryCommand[] credits,
        final SingleDebitOrCreditEntryCommand[] debits) {
    // sum of all debits must be = sum of all credits
    BigDecimal creditsSum = BigDecimal.ZERO;
    BigDecimal debitsSum = BigDecimal.ZERO;
    for (final SingleDebitOrCreditEntryCommand creditEntryCommand : credits) {
        if (creditEntryCommand.getAmount() == null || creditEntryCommand.getGlAccountId() == null) {
            throw new JournalEntryInvalidException(
                    GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null);
        }/* ww w.jav  a 2 s  .  c  o m*/
        creditsSum = creditsSum.add(creditEntryCommand.getAmount());
    }
    for (final SingleDebitOrCreditEntryCommand debitEntryCommand : debits) {
        if (debitEntryCommand.getAmount() == null || debitEntryCommand.getGlAccountId() == null) {
            throw new JournalEntryInvalidException(
                    GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, null, null, null);
        }
        debitsSum = debitsSum.add(debitEntryCommand.getAmount());
    }
    if (creditsSum.compareTo(debitsSum) != 0) {
        throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.DEBIT_CREDIT_SUM_MISMATCH, null,
                null, null);
    }
}

From source file:org.esupportail.papercut.webportlet.EsupPapercutPortletController.java

@RequestMapping
public ModelAndView renderView(RenderRequest request, RenderResponse response) {

    ModelMap model = new ModelMap();

    model.put("htmlHeader", request.getPreferences().getValue("htmlHeader", ""));
    model.put("htmlFooter", request.getPreferences().getValue("htmlFooter", ""));
    model.put("payboxMontantMin", request.getPreferences().getValue("payboxMontantMin", "0.5"));
    model.put("payboxMontantMax", request.getPreferences().getValue("payboxMontantMax", "5.0"));
    model.put("payboxMontantStep", request.getPreferences().getValue("payboxMontantStep", "0.5"));
    model.put("payboxMontantDefaut", request.getPreferences().getValue("payboxMontantDefaut", "2.0"));

    double papercutSheetCost = Double.parseDouble(request.getPreferences().getValue("papercutSheetCost", "-1"));
    double papercutColorSheetCost = Double
            .parseDouble(request.getPreferences().getValue("papercutColorSheetCost", "-1"));

    String paperCutContext = request.getPreferences().getValue(PREF_PAPERCUT_CONTEXT, null);
    EsupPaperCutService esupPaperCutService = esupPaperCutServices.get(paperCutContext);

    String uid = getUid(request);
    String userMail = getUserMail(request);

    // check if the user can make a transaction
    int transactionNbMax = Integer.parseInt(request.getPreferences().getValue("transactionNbMax", "-1"));
    BigDecimal transactionMontantMax = new BigDecimal(
            request.getPreferences().getValue("transactionMontantMax", "-1"));
    boolean canMakeTransaction = true;

    // constraints via transactionNbMax
    if (transactionNbMax > -1) {
        long nbTransactionsNotArchived = PayboxPapercutTransactionLog
                .countFindPayboxPapercutTransactionLogsByUidEqualsAndPaperCutContextEqualsAndArchived(uid,
                        paperCutContext, false);
        if (transactionNbMax <= nbTransactionsNotArchived) {
            canMakeTransaction = false;/*from  w w  w  .j av a 2s.c  o m*/
        }
    }

    BigDecimal payboxMontantMin = new BigDecimal(request.getPreferences().getValue("payboxMontantMin", "0.5"));
    BigDecimal payboxMontantMax = new BigDecimal(request.getPreferences().getValue("payboxMontantMax", "5.0"));
    BigDecimal payboxMontantStep = new BigDecimal(
            request.getPreferences().getValue("payboxMontantStep", "0.5"));
    BigDecimal payboxMontantDefaut = new BigDecimal(
            request.getPreferences().getValue("payboxMontantDefaut", "2.0"));
    // constraints on the slider via transactionMontantMax
    if (canMakeTransaction && transactionMontantMax.intValue() > -1) {
        List<PayboxPapercutTransactionLog> transactionsNotArchived = PayboxPapercutTransactionLog
                .findPayboxPapercutTransactionLogsByUidEqualsAndPaperCutContextEqualsAndArchived(uid,
                        paperCutContext, false)
                .getResultList();
        BigDecimal montantTotalTransactionsNotArchived = new BigDecimal("0");
        for (PayboxPapercutTransactionLog txLog : transactionsNotArchived) {
            montantTotalTransactionsNotArchived = montantTotalTransactionsNotArchived
                    .add(new BigDecimal(txLog.getMontant()));
        }
        transactionMontantMax = transactionMontantMax.multiply(new BigDecimal("100"))
                .subtract(montantTotalTransactionsNotArchived);
        if (transactionMontantMax.doubleValue() < payboxMontantMax.doubleValue() * 100) {
            payboxMontantMax = transactionMontantMax.divide(payboxMontantStep).multiply(payboxMontantStep);
            payboxMontantMax = payboxMontantMax.divide(new BigDecimal("100"));
            if (payboxMontantDefaut.compareTo(payboxMontantMax) == 1) {
                payboxMontantDefaut = payboxMontantMax;
            }
            if (payboxMontantMax.compareTo(payboxMontantMin) == -1) {
                canMakeTransaction = false;
            }
            model.put("payboxMontantMax", payboxMontantMax.doubleValue());
            model.put("payboxMontantDefaut", payboxMontantDefaut.doubleValue());
        }
    }

    // generation de l'ensemble des payboxForm :  payboxMontantMin -> payboxMontantMax par pas de payboxMontantStep
    String portletContextPath = ((RenderResponse) response).createRenderURL().toString();
    Map<Integer, PayBoxForm> payboxForms = new HashMap<Integer, PayBoxForm>();
    for (BigDecimal montant = payboxMontantMin; montant.compareTo(payboxMontantMax) <= 0; montant = montant
            .add(payboxMontantStep)) {
        PayBoxForm payBoxForm = esupPaperCutService.getPayBoxForm(uid, userMail, montant.doubleValue(),
                paperCutContext, portletContextPath);
        if (papercutSheetCost > 0) {
            int nbSheets = (int) (montant.doubleValue() / papercutSheetCost);
            payBoxForm.setNbSheets(nbSheets);
        }
        if (papercutColorSheetCost > 0) {
            int nbColorSheets = (int) (montant.doubleValue() / papercutColorSheetCost);
            payBoxForm.setNbColorSheets(nbColorSheets);
        }

        payboxForms.put(montant.multiply(new BigDecimal(100)).intValue(), payBoxForm);
    }
    Map<Integer, PayBoxForm> sortedMap = new TreeMap<Integer, PayBoxForm>(payboxForms);

    model.put("payboxForms", sortedMap);
    model.put("payboxMontantDefautCents", payboxMontantDefaut.multiply(new BigDecimal(100)).intValue());

    model.put("canMakeTransaction", canMakeTransaction);

    UserPapercutInfos userPapercutInfos = esupPaperCutService.getUserPapercutInfos(uid);
    model.put("userPapercutInfos", userPapercutInfos);

    boolean isAdmin = isAdmin(request);
    boolean isManager = isManager(request);
    model.put("isAdmin", isAdmin);
    model.put("isManager", isManager);
    model.put("active", "home");
    return new ModelAndView(getViewName(request, "index"), model);
}