Example usage for java.math BigDecimal add

List of usage examples for java.math BigDecimal add

Introduction

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

Prototype

public BigDecimal add(BigDecimal augend) 

Source Link

Document

Returns a BigDecimal whose value is (this + augend) , and whose scale is max(this.scale(), augend.scale()) .

Usage

From source file:net.sourceforge.fenixedu.domain.credits.util.DepartmentCreditsPoolBean.java

@Atomic
public void editUnitCredits() {
    BigDecimal newAssignedCredits = BigDecimal.ZERO;
    for (DepartmentExecutionCourse departmentExecutionCourse : otherDepartmentSharedExecutionCourses) {
        BigDecimal newExecutionCourseCLE = departmentExecutionCourse.getDepartmentEffectiveLoad()
                .multiply(departmentExecutionCourse.getUnitCreditValue());
        newAssignedCredits = newAssignedCredits.add(newExecutionCourseCLE);
    }//from   w  ww  .  j  a  v  a 2s .c om

    for (DepartmentExecutionCourse departmentExecutionCourse : departmentSharedExecutionCourses) {
        newAssignedCredits = setExecutionCourseUnitCredit(departmentExecutionCourse,
                getCanEditSharedUnitCredits(), newAssignedCredits, true);
    }
    for (DepartmentExecutionCourse departmentExecutionCourse : departmentExecutionCourses) {
        newAssignedCredits = setExecutionCourseUnitCredit(departmentExecutionCourse, getCanEditUnitCredits(),
                newAssignedCredits, false);
    }
    if (newAssignedCredits.compareTo(getDepartmentCreditsPool().getCreditsPool()) > 0) {
        throw new DomainException("label.excededDepartmentCreditsPool",
                getDepartmentCreditsPool().getCreditsPool().toString(), newAssignedCredits.toString());
    }
    setValues();
}

From source file:com.gst.portfolio.shareaccounts.service.ShareAccountWritePlatformServiceJpaRepositoryImpl.java

private Map<String, Object> populateJournalEntries(final ShareAccount account,
        final Set<ShareAccountTransaction> transactions) {
    final Map<String, Object> accountingBridgeData = new HashMap<>();
    Boolean cashBasedAccounting = account.getShareProduct().getAccountingType().intValue() == 2 ? Boolean.TRUE
            : Boolean.FALSE;// www. jav  a2s .  com
    accountingBridgeData.put("cashBasedAccountingEnabled", cashBasedAccounting);
    accountingBridgeData.put("accrualBasedAccountingEnabled", Boolean.FALSE);
    accountingBridgeData.put("shareAccountId", account.getId());
    accountingBridgeData.put("shareProductId", account.getShareProduct().getId());
    accountingBridgeData.put("officeId", account.getOfficeId());
    MonetaryCurrency currency = account.getCurrency();
    final CurrencyData currencyData = new CurrencyData(currency.getCode(), "", currency.getDigitsAfterDecimal(),
            currency.getCurrencyInMultiplesOf(), "", "");
    accountingBridgeData.put("currency", currencyData);
    final List<Map<String, Object>> newTransactionsMap = new ArrayList<>();
    accountingBridgeData.put("newTransactions", newTransactionsMap);

    for (ShareAccountTransaction transaction : transactions) {
        final Map<String, Object> transactionDto = new HashMap<>();
        transactionDto.put("officeId", account.getOfficeId());
        transactionDto.put("id", transaction.getId());
        transactionDto.put("date", new LocalDate(transaction.getPurchasedDate()));
        final Integer status = transaction.getTransactionStatus();
        final ShareAccountTransactionEnumData statusEnum = new ShareAccountTransactionEnumData(
                status.longValue(), null, null);
        final Integer type = transaction.getTransactionType();
        final ShareAccountTransactionEnumData typeEnum = new ShareAccountTransactionEnumData(type.longValue(),
                null, null);
        transactionDto.put("status", statusEnum);
        transactionDto.put("type", typeEnum);
        if (transaction.isPurchaseRejectedTransaction() || transaction.isRedeemTransaction()) {
            BigDecimal amount = transaction.amount();
            if (transaction.chargeAmount() != null) {
                amount = amount.add(transaction.chargeAmount());
            }
            transactionDto.put("amount", amount);
        } else {
            transactionDto.put("amount", transaction.amount());
        }

        transactionDto.put("chargeAmount", transaction.chargeAmount());
        transactionDto.put("paymentTypeId", null); // FIXME::make it cash
                                                   // payment
        if (transaction.getChargesPaidBy() != null && !transaction.getChargesPaidBy().isEmpty()) {
            final List<Map<String, Object>> chargesPaidData = new ArrayList<>();
            transactionDto.put("chargesPaid", chargesPaidData);
            Set<ShareAccountChargePaidBy> chargesPaidBySet = transaction.getChargesPaidBy();
            for (ShareAccountChargePaidBy chargesPaidBy : chargesPaidBySet) {
                Map<String, Object> chargesPaidDto = new HashMap<>();
                chargesPaidDto.put("chargeId", chargesPaidBy.getChargeId());
                chargesPaidDto.put("sharesChargeId", chargesPaidBy.getShareChargeId());
                chargesPaidDto.put("amount", chargesPaidBy.getAmount());
                chargesPaidData.add(chargesPaidDto);
            }
        }
        newTransactionsMap.add(transactionDto);
    }
    return accountingBridgeData;
}

From source file:com.osafe.events.CheckOutEvents.java

public static String calcLoyaltyTax(HttpServletRequest request, HttpServletResponse response) {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);

    String isTaxedOnStore = (String) request.getAttribute("isTaxedOnStore");
    GenericValue shipAddress = null;/*from   www.ja va2  s  .c  om*/
    if (UtilValidate.isNotEmpty(isTaxedOnStore) && "Y".equalsIgnoreCase(isTaxedOnStore)) {
        shipAddress = (GenericValue) request.getAttribute("taxedStoreAddress");
    }

    if (UtilValidate.isEmpty(cart.getShippingContactMechId()) && cart.getBillingAddress() == null
            && shipAddress == null) {
        return "success";
    }

    CheckOutHelper checkOutHelper = new CheckOutHelper(dispatcher, delegator, cart);
    BigDecimal orderAdjustmentOtherAmount = BigDecimal.ZERO;
    List<GenericValue> loyaltyAdjustments = EntityUtil.filterByAnd(cart.getAdjustments(),
            UtilMisc.toMap("orderAdjustmentTypeId", "LOYALTY_POINTS"));
    if (UtilValidate.isEmpty(loyaltyAdjustments)) {
        return "success";

    }

    BigDecimal loyaltyAdjTotal = BigDecimal.ZERO;

    Iterator<GenericValue> loyaltyAdjIter = loyaltyAdjustments.iterator();
    while (loyaltyAdjIter.hasNext()) {
        GenericValue loyaltyAdjustment = loyaltyAdjIter.next();

        if (UtilValidate.isNotEmpty(loyaltyAdjustment)) {
            BigDecimal amount = loyaltyAdjustment.getBigDecimal("amount").setScale(taxCalcScale, taxRounding);
            loyaltyAdjTotal = loyaltyAdjTotal.add(amount);
        }
    }

    if (loyaltyAdjTotal.compareTo(BigDecimal.ZERO) == 0) {
        return "success";

    }

    int shipGroups = cart.getShipGroupSize();
    for (int i = 0; i < shipGroups; i++) {
        Map shoppingCartItemIndexMap = new HashMap();
        Map serviceContext = null;
        ShoppingCart.CartShipInfo csi = cart.getShipInfo(i);
        if (shipAddress == null) {
            shipAddress = cart.getShippingAddress(i);
            // Debug.logInfo("====== makeTaxContext set shipAddress to cart.getShippingAddress(shipGroup): " + shipAddress, module);
        }

        try {

            int totalItems = csi.shipItemInfo.size();

            List product = new ArrayList(totalItems);
            List amount = new ArrayList(totalItems);
            List price = new ArrayList(totalItems);
            List shipAmt = new ArrayList(totalItems);

            Iterator<ShoppingCartItem> it = csi.shipItemInfo.keySet().iterator();
            for (int itemIdx = 0; itemIdx < totalItems; itemIdx++) {
                ShoppingCartItem cartItem = it.next();
                ShoppingCart.CartShipInfo.CartShipItemInfo itemInfo = csi.getShipItemInfo(cartItem);
                product.add(i, cartItem.getProduct());
                amount.add(i, cartItem.getItemSubTotal(itemInfo.quantity));
                price.add(i, cartItem.getBasePrice());
                shipAmt.add(i, BigDecimal.ZERO); // no per item shipping yet
                shoppingCartItemIndexMap.put(Integer.valueOf(itemIdx), cartItem);
            }

            serviceContext = UtilMisc.toMap("productStoreId", cart.getProductStoreId());
            serviceContext.put("payToPartyId", cart.getBillFromVendorPartyId());
            serviceContext.put("billToPartyId", cart.getBillToCustomerPartyId());
            serviceContext.put("itemProductList", product);
            serviceContext.put("itemAmountList", amount);
            serviceContext.put("itemPriceList", price);
            serviceContext.put("shippingAddress", shipAddress);
            serviceContext.put("orderLoyaltyAmount", loyaltyAdjTotal);
            Map serviceResult = null;

            try {
                serviceResult = dispatcher.runSync("calcAdjustmentTax", serviceContext);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
            }

            if (ServiceUtil.isError(serviceResult)) {
                Debug.logError(ServiceUtil.getErrorMessage(serviceResult), module);
                return "success";
            }

            // the adjustments (returned in order) from taxware.
            List orderAdj = (List) serviceResult.get("orderAdjustments");
            csi.shipTaxAdj.addAll(orderAdj);

        } catch (Exception e) {
            Debug.logError(e, module);
        }

    }
    return "success";
}

From source file:ddf.catalog.validation.impl.validator.RangeValidator.java

/**
 * Creates a {@code RangeValidator} with an <strong>inclusive</strong> range and the provided
 * epsilon./*  w  w w  . j av a  2  s.c  o  m*/
 * <p>
 * Uses the provided epsilon on both sides of the range to account for floating point
 * representation inaccuracies, so the range is really [min - epsilon, max + epsilon].
 *
 * @param min     the minimum allowable value (inclusive), cannot be null
 * @param max     the maximum allowable value (inclusive), cannot be null and must be greater
 *                than {@code min}
 * @param epsilon the epsilon value, cannot be null and must be positive
 * @throws IllegalArgumentException if {@code max} is not greater than {@code min},
 *                                  {@code epsilon} is not positive, or if any argument is null
 */
public RangeValidator(final BigDecimal min, final BigDecimal max, final BigDecimal epsilon) {
    Preconditions.checkArgument(min != null, "The minimum cannot be null.");
    Preconditions.checkArgument(max != null, "The maximum cannot be null.");
    Preconditions.checkArgument(epsilon != null, "The epsilon cannot be null.");
    Preconditions.checkArgument(min.compareTo(max) == -1, "The maximum must be greater than the minimum.");
    Preconditions.checkArgument(epsilon.compareTo(BigDecimal.ZERO) == 1, "The epsilon must be greater than 0.");

    this.min = min.subtract(epsilon);
    this.max = max.add(epsilon);
}

From source file:com.siapa.managedbean.DetalleCompraAlimentoManagedBean.java

public BigDecimal calcularTotal() {
    BigDecimal total1 = BigDecimal.ZERO;
    BigDecimal imp = BigDecimal.ZERO;
    if (detalleCompraAlimento != null && detalleCompraAlimento.getCantDetalleCompraAlimento() != null) {
        if (detalleCompraAlimento.getPrecioDetalleCompraAlimento() != null) {
            if (detalleCompraAlimento.getImpuestoDetCompraAlimento() != null) {

                total1 = total1.add((detalleCompraAlimento.getCantDetalleCompraAlimento()
                        .multiply(detalleCompraAlimento.getPrecioDetalleCompraAlimento()))
                                .multiply(detalleCompraAlimento.getImpuestoDetCompraAlimento()
                                        .divide(new BigDecimal(100)).add(new BigDecimal(1)))
                                .setScale(2, BigDecimal.ROUND_HALF_UP));
            }// ww w.j av a 2  s .c  o  m
        }
    }
    return total1;
}

From source file:churashima.action.manage.ReportAction.java

@Execute(validator = false)
public String attendancePersonal() {
    String ym = reportForm.ym;//from w  w w  .j  av  a  2s  .c  o  m

    int year = Integer.parseInt(ym.substring(0, 4));
    int month = Integer.parseInt(ym.substring(4));

    Calendar calFrom = Calendar.getInstance();
    calFrom.set(Calendar.YEAR, year);
    calFrom.set(Calendar.MONTH, month - 1);
    calFrom.set(Calendar.DAY_OF_MONTH, 1);
    Calendar calTo = Calendar.getInstance();
    calTo.set(Calendar.YEAR, year);
    calTo.set(Calendar.MONTH, month);
    calTo.set(Calendar.DAY_OF_MONTH, 1);

    WorkDao workDao = SingletonS2Container.getComponent(WorkDao.class);
    List<ReportDto> reportDtoList = workDao.selectForReportAttendancePersonal(reportForm.kind,
            calFrom.getTime(), calTo.getTime(), reportForm.userId);

    BigDecimal workHourTotalPersonal = BigDecimal.valueOf(0);
    BigDecimal overHourTotalPersonal = BigDecimal.valueOf(0);
    BigDecimal overHourMorningTotalPersonal = BigDecimal.valueOf(0);
    BigDecimal overHourEveningTotalPersonal = BigDecimal.valueOf(0);
    BigDecimal overHourNightTotalPersonal = BigDecimal.valueOf(0);

    for (ReportDto dto : reportDtoList) {
        workHourTotalPersonal = workHourTotalPersonal.add(dto.workHourTotal);
        overHourTotalPersonal = overHourTotalPersonal.add(dto.overHourTotal);
        overHourMorningTotalPersonal = overHourMorningTotalPersonal.add(dto.overHourMorningTotal);
        overHourEveningTotalPersonal = overHourEveningTotalPersonal.add(dto.overHourEveningTotal);
        overHourNightTotalPersonal = overHourNightTotalPersonal.add(dto.overHourNightTotal);
    }

    reportForm.workHourTotalPersonal = workHourTotalPersonal;
    reportForm.overHourTotalPersonal = overHourTotalPersonal;
    reportForm.overHourMorningTotalPersonal = overHourMorningTotalPersonal;
    reportForm.overHourEveningTotalPersonal = overHourEveningTotalPersonal;
    reportForm.overHourNightTotalPersonal = overHourNightTotalPersonal;

    // ?????
    calFrom.add(Calendar.MONTH, -1);
    calTo.add(Calendar.MONTH, -1);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
    int count = workDao.selectForReportExist(reportForm.kind, calFrom.getTime(), calTo.getTime(),
            reportForm.userId);
    if (count > 0) {
        reportForm.ymBefore = sdf.format(calFrom.getTime());
    } else {
        reportForm.ymBefore = null;
    }

    // ????
    calFrom.add(Calendar.MONTH, +2);
    calTo.add(Calendar.MONTH, +2);
    count = workDao.selectForReportExist(reportForm.kind, calFrom.getTime(), calTo.getTime(),
            reportForm.userId);
    if (count > 0) {
        reportForm.ymNext = sdf.format(calFrom.getTime());
    } else {
        reportForm.ymNext = null;
    }

    reportForm.reportDtoList = reportDtoList;

    return "attendancePersonalReport.jsp";
}

From source file:com.autentia.tnt.manager.billing.BillManager.java

public List<BillBreakDown> getAllBitacoreBreakDowns(Date start, Date end, Project project) {

    final List<BillBreakDown> desgloses = new ArrayList<BillBreakDown>();

    ActivityDAO activityDAO = ActivityDAO.getDefault();
    ActivitySearch actSearch = new ActivitySearch();
    actSearch.setBillable(new Boolean(true));
    actSearch.setStartStartDate(start);/*from  w ww. j  ava 2  s.  c o  m*/
    actSearch.setEndStartDate(end);

    List<Activity> actividadesTotal = new ArrayList<Activity>();
    Hashtable user_roles = new Hashtable();

    ProjectRoleDAO projectRoleDAO = ProjectRoleDAO.getDefault();
    ProjectRoleSearch prjRolSearch = new ProjectRoleSearch();
    prjRolSearch.setProject(project);
    List<ProjectRole> roles = projectRoleDAO.search(prjRolSearch, new SortCriteria("id", false));
    for (ProjectRole proyRole : roles) {
        actSearch.setRole(proyRole);
        List<Activity> actividades = activityDAO.search(actSearch, new SortCriteria("startDate", false));
        actividadesTotal.addAll(actividades);
    }

    for (Activity act : actividadesTotal) {
        String key = act.getRole().getId().toString() + act.getUser().getId().toString();

        if (!user_roles.containsKey(key)) {
            Hashtable value = new Hashtable();
            value.put("ROLE", act.getRole());
            value.put("USER", act.getUser());
            user_roles.put(key, value);
        }
    }

    Enumeration en = user_roles.keys();

    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        Hashtable pair = (Hashtable) user_roles.get(key);
        actSearch.setBillable(new Boolean(true));
        actSearch.setStartStartDate(start);
        actSearch.setEndStartDate(end);

        ProjectRole pR = (ProjectRole) pair.get("ROLE");
        User u = (User) pair.get("USER");
        actSearch.setRole(pR);
        actSearch.setUser(u);
        List<Activity> actividadesUsuarioRol = activityDAO.search(actSearch,
                new SortCriteria("startDate", false));

        BillBreakDown brd = new BillBreakDown();
        brd.setConcept("Imputaciones (usuario - rol): " + u.getName() + " - " + pR.getName());
        brd.setAmount(pR.getCostPerHour());

        IvaApplicator.applyIvaToTaxableObject(start, brd);

        BigDecimal unitsTotal = new BigDecimal(0);
        for (Activity act : actividadesUsuarioRol) {
            BigDecimal unitsActual = new BigDecimal(act.getDuration());
            unitsActual = unitsActual.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
            unitsTotal = unitsTotal.add(unitsActual);
        }
        brd.setUnits(unitsTotal);
        brd.setSelected(true);
        desgloses.add(brd);
    }

    ProjectCostDAO prjCostDAO = ProjectCostDAO.getDefault();
    ProjectCostSearch prjCostSearch = new ProjectCostSearch();
    prjCostSearch.setProject(project);
    List<ProjectCost> costes = prjCostDAO.search(prjCostSearch, new SortCriteria("id", false));
    for (ProjectCost proyCost : costes) {
        BillBreakDown brd = new BillBreakDown();
        brd.setConcept("Coste: " + proyCost.getName());
        brd.setUnits(new BigDecimal(1));
        brd.setAmount(proyCost.getCost());

        IvaApplicator.applyIvaToTaxableObject(start, brd);

        brd.setSelected(true);
        desgloses.add(brd);
    }

    return desgloses;

}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.PolygonZone.java

public PolarCoordinate getCenterOfGravity() {
    BigDecimal x = new BigDecimal(0), y = new BigDecimal(0);
    BigDecimal doubleArea = new BigDecimal(0);

    for (int k = 0, l = vertices.length - 1; k < l; ++k) {
        BigDecimal ax = new BigDecimal(vertices[k].x);
        BigDecimal ay = new BigDecimal(vertices[k].y);
        BigDecimal bx = new BigDecimal(vertices[k + 1].x);
        BigDecimal by = new BigDecimal(vertices[k + 1].y);
        BigDecimal t = ax.multiply(by).subtract(bx.multiply(ay));
        x = x.add(ax.add(bx).multiply(t));
        y = y.add(ay.add(by).multiply(t));
        doubleArea = doubleArea.add(ax.multiply(by).subtract(bx.multiply(ay)));
    }//  ww  w .  ja va  2  s.c  o  m

    double sixTimesArea = 3.0 * doubleArea.doubleValue();
    return new PolarCoordinate(x.doubleValue() / sixTimesArea, y.doubleValue() / sixTimesArea, 0);
}

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  ww  w  .  j  a  v a 2  s  .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);
}

From source file:org.key2gym.business.services.CashServiceBean.java

@Override
public BigDecimal getCashByDate(DateMidnight date) throws SecurityViolationException {

    if (date == null) {
        throw new NullPointerException("The date is null."); //NOI18N
    }/*  w w  w .j a  v a  2s.  co  m*/

    if (!date.equals(DateMidnight.now())) {
        if (!callerHasRole(SecurityRoles.MANAGER)) {
            throw new SecurityViolationException(getString("Security.Access.Denied"));
        }
    } else {
        if (!callerHasAnyRole(SecurityRoles.JUNIOR_ADMINISTRATOR, SecurityRoles.SENIOR_ADMINISTRATOR)) {
            throw new SecurityViolationException(getString("Security.Access.Denied"));
        }
    }

    BigDecimal cash = (BigDecimal) em.createNamedQuery("OrderEntity.sumPaymentsForDateRecorded") //NOI18N
            .setParameter("dateRecorded", date.toDate()) //NOI18N
            .getSingleResult();

    /*
     * The sum aggregate function returns null, when there is not 
     * any orders.
     */
    if (cash == null) {
        cash = BigDecimal.ZERO;
    }

    CashAdjustment adjustment = em.find(CashAdjustment.class, date.toDate());

    if (adjustment != null) {
        cash = cash.add(adjustment.getAmount());
    }

    return cash;
}