Example usage for java.math RoundingMode HALF_UP

List of usage examples for java.math RoundingMode HALF_UP

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_UP.

Prototype

RoundingMode HALF_UP

To view the source code for java.math RoundingMode HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Utils.java

public static String formatSize(Integer size) {
    String formattedFileSize = "";
    if (size != null) {
        BigDecimal kb = BigDecimal.valueOf(1024);
        BigDecimal mb = BigDecimal.valueOf(1048576);
        BigDecimal fileSizeBD = BigDecimal.valueOf(size);
        if (size > 999999) {
            formattedFileSize = fileSizeBD.divide(mb, 2, RoundingMode.HALF_UP).toPlainString();
            formattedFileSize += " MB";
        } else if (size > 999) {
            formattedFileSize = fileSizeBD.divide(kb, 2, RoundingMode.HALF_UP).toPlainString();
            formattedFileSize += " KB";
        } else {//ww w.j  a v  a  2  s.  co  m
            formattedFileSize = fileSizeBD.toPlainString();
            formattedFileSize += " B";
        }
    }
    return formattedFileSize;
}

From source file:org.kuali.kfs.module.tem.service.impl.AccountingDistributionServiceImpl.java

@SuppressWarnings("deprecation")
@Override/*from   ww w  .j a  va2s.  c o m*/
public List<TemSourceAccountingLine> distributionToSouceAccountingLines(
        List<TemDistributionAccountingLine> distributionAccountingLines,
        List<AccountingDistribution> accountingDistributionList, KualiDecimal sourceAccountingLinesTotal,
        KualiDecimal expenseLimit) {
    List<TemSourceAccountingLine> sourceAccountingList = new ArrayList<TemSourceAccountingLine>();
    Map<String, AccountingDistribution> distributionMap = new HashMap<String, AccountingDistribution>();
    KualiDecimal total = KualiDecimal.ZERO;
    int distributionTargetCount = 0;
    boolean useExpenseLimit = false;
    for (AccountingDistribution accountDistribution : accountingDistributionList) {
        if (accountDistribution.getSelected()) {
            total = total.add(accountDistribution.getRemainingAmount());
            distributionTargetCount += 1;
        }
    }

    if (expenseLimit != null && expenseLimit.isPositive()) {
        KualiDecimal expenseLimitTotal = new KualiDecimal(expenseLimit.bigDecimalValue());
        // do we have any accounting line amount to subtract from the expense limit?
        if (sourceAccountingLinesTotal != null && sourceAccountingLinesTotal.isGreaterThan(KualiDecimal.ZERO)) {
            expenseLimitTotal = expenseLimitTotal.subtract(sourceAccountingLinesTotal);
        }
        if (expenseLimitTotal.isLessThan(total)) {
            total = expenseLimitTotal;
            useExpenseLimit = true;
        }
    }

    if (total.isGreaterThan(KualiDecimal.ZERO)) {
        for (AccountingDistribution accountingDistribution : accountingDistributionList) {
            List<TemSourceAccountingLine> tempSourceAccountingList = new ArrayList<TemSourceAccountingLine>();
            if (accountingDistribution.getSelected()) {
                for (TemDistributionAccountingLine accountingLine : distributionAccountingLines) {
                    TemSourceAccountingLine newLine = new TemSourceAccountingLine();
                    try {
                        BeanUtils.copyProperties(newLine, accountingLine);
                    } catch (IllegalAccessException ex) {
                        ex.printStackTrace();
                    } catch (InvocationTargetException ex) {
                        ex.printStackTrace();
                    }
                    BigDecimal distributionAmount = (distributionTargetCount > 1)
                            ? accountingDistribution.getRemainingAmount().bigDecimalValue()
                            : total.bigDecimalValue();
                    BigDecimal product = accountingLine.getAccountLinePercent().multiply(distributionAmount);
                    product = product.divide(new BigDecimal(100), 5, RoundingMode.HALF_UP);
                    BigDecimal lineAmount = product.divide(total.bigDecimalValue(), 5, RoundingMode.HALF_UP);

                    newLine.setAmount(new KualiDecimal(product));
                    newLine.setCardType(accountingDistribution.getCardType());
                    Map<String, Object> fieldValues = new HashMap<String, Object>();
                    fieldValues.put(KFSPropertyConstants.FINANCIAL_OBJECT_CODE,
                            accountingDistribution.getObjectCode());
                    fieldValues.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE,
                            newLine.getChartOfAccountsCode());
                    fieldValues.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR,
                            SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear());
                    ObjectCode objCode = getBusinessObjectService().findByPrimaryKey(ObjectCode.class,
                            fieldValues);
                    newLine.setObjectCode(objCode);
                    newLine.setFinancialObjectCode(accountingDistribution.getObjectCode());
                    tempSourceAccountingList.add(newLine);
                }
                if (useExpenseLimit) {
                    sourceAccountingList.addAll(tempSourceAccountingList); //we just adjusted the accounting lines for the expense...let's not readjust
                } else {
                    sourceAccountingList.addAll(adjustValues(tempSourceAccountingList,
                            accountingDistribution.getRemainingAmount()));
                }
            }
        }
    }
    return sourceAccountingList;
}

From source file:org.libreplan.business.test.orders.entities.OrderElementTest.java

private Division division(int numberOfDecimals) {
    return new Division(new MathContext(numberOfDecimals, RoundingMode.HALF_UP));
}

From source file:nl.b3p.kaartenbalie.struts.WfsPricingAction.java

public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    request.setAttribute("id", request.getParameter("id"));
    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }//from   ww w  .ja v  a 2s  .co m
    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    Date validFrom = FormUtils.FormStringToDate(dynaForm.getString("validFrom"), null);
    Date validUntil = FormUtils.FormStringToDate(dynaForm.getString("validUntil"), null);
    if (validUntil != null && validFrom != null) {
        if (validUntil.before(validFrom)) {
            prepareMethod(dynaForm, request, EDIT, LIST);
            addAlternateMessage(mapping, request, START_END_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
    }
    LayerPricing lp = getLayerPricing(dynaForm, request, true);
    if (lp == null) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setValidFrom(validFrom);
    lp.setValidUntil(validUntil);

    WfsLayer layer = null;
    String id = FormUtils.nullIfEmpty(getLayerID(dynaForm));
    if (id != null) {
        layer = getWfsLayerByUniqueName(id);
    }
    if (layer == null || layer.getName() == null || layer.getName().trim().length() == 0) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, LAYER_PLACEHOLDER_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    lp.setServerProviderPrefix(layer.getSpAbbr());
    lp.setLayerName(layer.getName());
    lp.setPlanType(FormUtils.StringToInt(dynaForm.getString("planType")));
    String service = dynaForm.getString("service");
    String operation = null;
    if (service != null && service.equalsIgnoreCase("WMS")) {
        operation = dynaForm.getString("operationWMS");
    } else if (service != null && service.equalsIgnoreCase("WFS")) {
        operation = dynaForm.getString("operationWFS");
    } else {
        service = null;
    }
    if (operation != null && operation.trim().length() == 0) {
        operation = null;
    }
    lp.setService(service);
    lp.setOperation(operation);
    BigDecimal minScale = FormUtils.bdValueNull(dynaForm.getString("minScale"));
    BigDecimal maxScale = FormUtils.bdValueNull(dynaForm.getString("maxScale"));
    String projection = dynaForm.getString("projection");
    if (projection != null && projection.trim().length() == 0) {
        projection = null;
    }
    if (projection != null && (minScale != null || maxScale != null)) {
        boolean scaleOK = false;
        if (minScale != null && minScale.doubleValue() > 0) {
            if (maxScale != null && maxScale.doubleValue() > 0) {
                if (maxScale.compareTo(minScale) > 0) {
                    scaleOK = true;
                }
            }
        }
        if (!scaleOK) {
            prepareMethod(dynaForm, request, LIST, EDIT);
            addAlternateMessage(mapping, request, SCALE_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
        if (minScale != null) {
            lp.setMinScale(minScale.setScale(2, RoundingMode.HALF_UP));
        }
        if (maxScale != null) {
            lp.setMaxScale(maxScale.setScale(2, RoundingMode.HALF_UP));
        }
        lp.setProjection(projection);
    }
    BigDecimal unitPrice = FormUtils.bdValueNull(dynaForm.getString("unitPrice"));
    /* 
     * || door && vervangen. Price is namelijk verplicht en dus nooit null
     * en hij kwam dus altijd door de check. Ook als het bedrag 0 was.
     */
    if (unitPrice != null && unitPrice.doubleValue() > 0.0) {
        lp.setUnitPrice(unitPrice.setScale(2, RoundingMode.HALF_UP));
    } else {
        lp.setLayerIsFree(Boolean.TRUE);
    }
    em.persist(lp);
    return super.save(mapping, dynaForm, request, response);
}

From source file:nl.b3p.kaartenbalie.struts.WmsPricingAction.java

public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    request.setAttribute("id", request.getParameter("id"));
    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }/*ww w . ja v a 2 s.  c o m*/
    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    Date validFrom = FormUtils.FormStringToDate(dynaForm.getString("validFrom"), null);
    Date validUntil = FormUtils.FormStringToDate(dynaForm.getString("validUntil"), null);
    if (validUntil != null && validFrom != null) {
        if (validUntil.before(validFrom)) {
            prepareMethod(dynaForm, request, EDIT, LIST);
            addAlternateMessage(mapping, request, START_END_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
    }
    LayerPricing lp = getLayerPricing(dynaForm, request, true);
    if (lp == null) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setValidFrom(validFrom);
    lp.setValidUntil(validUntil);

    Layer layer = null;
    String id = FormUtils.nullIfEmpty(getLayerID(dynaForm));
    if (id != null) {
        layer = getLayerByUniqueName(id);
    }
    if (layer == null || layer.getName() == null || layer.getName().trim().length() == 0) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, LAYER_PLACEHOLDER_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setServerProviderPrefix(layer.getSpAbbr());
    lp.setLayerName(layer.getName());
    lp.setPlanType(FormUtils.StringToInt(dynaForm.getString("planType")));
    String service = dynaForm.getString("service");
    String operation = null;
    if (service != null && service.equalsIgnoreCase("WMS")) {
        operation = dynaForm.getString("operationWMS");
    } else if (service != null && service.equalsIgnoreCase("WFS")) {
        operation = dynaForm.getString("operationWFS");
    } else {
        service = null;
    }
    if (operation != null && operation.trim().length() == 0) {
        operation = null;
    }
    lp.setService(service);
    lp.setOperation(operation);
    BigDecimal minScale = FormUtils.bdValueNull(dynaForm.getString("minScale"));
    BigDecimal maxScale = FormUtils.bdValueNull(dynaForm.getString("maxScale"));
    String projection = dynaForm.getString("projection");
    if (projection != null && projection.trim().length() == 0) {
        projection = null;
    }
    if (projection != null && (minScale != null || maxScale != null)) {
        boolean scaleOK = false;
        if (minScale != null && minScale.doubleValue() > 0) {
            if (maxScale != null && maxScale.doubleValue() > 0) {
                if (maxScale.compareTo(minScale) > 0) {
                    scaleOK = true;
                }
            }
        }
        if (!scaleOK) {
            prepareMethod(dynaForm, request, LIST, EDIT);
            addAlternateMessage(mapping, request, SCALE_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
        if (minScale != null) {
            lp.setMinScale(minScale.setScale(2, RoundingMode.HALF_UP));
        }
        if (maxScale != null) {
            lp.setMaxScale(maxScale.setScale(2, RoundingMode.HALF_UP));
        }
        lp.setProjection(projection);
    }
    BigDecimal unitPrice = FormUtils.bdValueNull(dynaForm.getString("unitPrice"));
    /* 
     * || door && vervangen. Price is namelijk verplicht en dus nooit null
     * en hij kwam dus altijd door de check. Ook als het bedrag 0 was.
     */
    if (unitPrice != null && unitPrice.doubleValue() > 0.0) {
        lp.setUnitPrice(unitPrice.setScale(2, RoundingMode.HALF_UP));
    } else {
        lp.setLayerIsFree(Boolean.TRUE);
    }
    em.persist(lp);
    prepareMethod(dynaForm, request, LIST, EDIT);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}

From source file:org.sputnikdev.bluetooth.gattparser.FieldHolder.java

/**
 * Returns a BigInteger representation of the field or a default value in case if the field cannot
 * be converted to a BigInteger.//from   w ww . j a va 2s .co  m
 * @param def the default value to be returned if an error occurs converting the field
 * @return a BigInteger representation of the field
 */
public BigInteger getBigInteger(BigInteger def) {
    BigDecimal result = new BigDecimalConverter(null).convert(BigDecimal.class, prepareValue());
    return result != null
            ? result.multiply(BigDecimal.valueOf(getMultiplier())).add(BigDecimal.valueOf(getOffset()))
                    .setScale(0, RoundingMode.HALF_UP).toBigInteger()
            : def;
}

From source file:py.una.pol.karaku.math.MathContextProvider.java

@PostConstruct
void post() {//from w ww . j av  a2s  .  c  om

    scale = Integer.valueOf(pu.get(KARAKU_MATH_ROUNDING_SCALE, "4"));
    precision = Integer.valueOf(pu.get(KARAKU_MATH_ROUNDING_PRECISION, "0"));
    rm = RoundingMode.valueOf(pu.get(KARAKU_MATH_ROUNDING_MODE, RoundingMode.HALF_UP.toString()));
    log.info("Math Context initialized with a scale of {} and a round mode: {}", scale, rm);
}

From source file:at.fh.swenga.firefighters.controller.FireFighterController.java

@RequestMapping(value = { "/", "index" })
public String index(Model model, HttpServletRequest request) {

    if (request.isUserInRole("ROLE_GLOBAL_ADMIN")) {
        List<FireBrigadeModel> fireBrigades = fireBrigadeRepository.findAll();
        model.addAttribute("fireBrigades", fireBrigades);
        float males = fireFighterRepository.countByGender("m");
        float females = fireFighterRepository.countByGender("w");
        float sumFighters = males + females;
        float percentFem = females / sumFighters * 100;
        float percentMal = males / sumFighters * 100;
        percentFem = BigDecimal.valueOf(percentFem).setScale(2, RoundingMode.HALF_UP).floatValue();
        percentMal = BigDecimal.valueOf(percentMal).setScale(2, RoundingMode.HALF_UP).floatValue();
        model.addAttribute("males", percentMal);
        model.addAttribute("females", percentFem);
        model.addAttribute("sumFighters", sumFighters);
        List<Object[]> topFireBrigades = fireFighterRepository.groupByFireBrigade();
        Map<String, BigInteger> topFireBrigadesMap = topFireBrigades.stream().collect(Collectors.toMap(
                a -> (String) fireBrigadeRepository.findById((int) a[1]).getName(), a -> (BigInteger) a[0]));
        Map<String, BigInteger> sortedTopFireBrigadesMap = MapUtil.sortByValue(topFireBrigadesMap);
        model.addAttribute("sortedTopFireBrigades", sortedTopFireBrigadesMap);

    } else if (!request.isUserInRole("ROLE_GLOBAL_ADMIN")
            && (request.isUserInRole("ROLE_ADMIN") || request.isUserInRole("ROLE_USER"))) {
        List<FireFighterModel> fireFighters = fireFighterRepository.findByFireBrigade(getSessionFireBrigade());
        model.addAttribute("fireFighters", fireFighters);
    }/*from ww  w  .ja va2s  .  co m*/
    return "index";
}

From source file:org.kuali.coeus.common.budget.impl.calculator.LineItemCalculator.java

@Override
public void populateApplicableCosts(Boundary boundary) {
    int totalNumOfDays = dateTimeService.dateDiff(this.bli.getStartDate(), this.bli.getEndDate(), true);
    int boundaryNumOfDays = boundary.getNumberOfDays();

    List<BudgetPersonnelDetails> personnelDetailsList = bli.getBudgetPersonnelDetailsList();
    ScaleTwoDecimal salaryRequested = ScaleTwoDecimal.ZERO;
    ScaleTwoDecimal costSharingRequested = ScaleTwoDecimal.ZERO;
    if (!personnelDetailsList.isEmpty()) {
        for (BudgetPersonnelDetails budgetPersonnelDetails : personnelDetailsList) {
            budgetCalculationService.calculateBudgetLineItem(budget, budgetPersonnelDetails);
            salaryRequested = salaryRequested.add(budgetPersonnelDetails.getSalaryRequested());
            costSharingRequested = costSharingRequested.add(budgetPersonnelDetails.getCostSharingAmount());
        }/*from   ww  w. j a  va 2 s  .c  om*/
        bli.setLineItemCost(salaryRequested);
        bli.setCostSharingAmount(costSharingRequested);
    } else {
        ScaleTwoDecimal lineItemCost = bli.getLineItemCost();
        ScaleTwoDecimal lineItemCostSharing = bli.getCostSharingAmount();
        boundary.setApplicableCost(lineItemCost == null ? ScaleTwoDecimal.ZERO
                : new ScaleTwoDecimal(
                        lineItemCost.bigDecimalValue().multiply(((new BigDecimal(boundaryNumOfDays))))
                                .divide(new BigDecimal(totalNumOfDays), 2, RoundingMode.HALF_UP)));
        boundary.setApplicableCostSharing(
                lineItemCostSharing == null ? ScaleTwoDecimal.ZERO
                        : new ScaleTwoDecimal(lineItemCostSharing.bigDecimalValue()
                                .multiply(((new BigDecimal(boundaryNumOfDays))))
                                .divide(new BigDecimal(totalNumOfDays), 2, RoundingMode.HALF_UP)));
    }
}

From source file:org.openbravo.common.actionhandler.SetNewBPCurrency.java

@Override
protected JSONObject doExecute(Map<String, Object> parameters, String content) {

    JSONObject jsonRequest = null;/*w w  w .j  a  va2s.  c  o m*/
    OBContext.setAdminMode(true);
    try {
        jsonRequest = new JSONObject(content);
        JSONObject params = jsonRequest.getJSONObject("_params");
        final String strOrgId = jsonRequest.getString("inpadOrgId");
        final String strFromCurrencyId = jsonRequest.getString("inpbpCurrencyId");
        final String strToCurrencyId = params.getString("C_Currency_ID");
        final String strRate = params.getString("Rate");
        final String strAmount = params.getString("Foreign_Amount");
        final boolean strSetAmount = params.getBoolean("Amount");
        final boolean strUseDefaultConversion = params.getBoolean("Default_Conversion_Rate");
        final String strBpartnerId = jsonRequest.getString("C_BPartner_ID");
        final String glItemId = params.getString("c_glitem_id");
        BigDecimal creditUsed = BigDecimal.ZERO;
        BigDecimal rate = BigDecimal.ZERO;
        Double amount = new Double(0);
        if (strSetAmount && !"null".equals(strAmount)) {
            amount = Double.parseDouble(strAmount);
        }

        if (strUseDefaultConversion && !strSetAmount) {
            rate = getConversionRate(strOrgId, strFromCurrencyId, strToCurrencyId);
            if (rate == BigDecimal.ZERO && !strFromCurrencyId.equals(strToCurrencyId)) {
                try {
                    jsonRequest = new JSONObject();
                    String message = OBMessageUtils.messageBD("NoCurrencyConversion");
                    JSONObject errorMessage = new JSONObject();
                    errorMessage.put("severity", "error");
                    errorMessage.put("text", message);
                    jsonRequest.put("message", errorMessage);
                } catch (Exception e) {
                    OBDal.getInstance().rollbackAndClose();
                    log.error(e.getMessage(), e);
                }
                return jsonRequest;
            }
        } else {
            rate = "null".equals(strRate) ? BigDecimal.ZERO : BigDecimal.valueOf(Double.parseDouble(strRate));
        }
        BusinessPartner businessPartner = OBDal.getInstance().get(BusinessPartner.class, strBpartnerId);
        creditUsed = businessPartner.getCreditUsed();

        ScrollableResults scroll = null;
        GLItem glItem = OBDal.getInstance().get(GLItem.class, glItemId);
        Currency currency = OBDal.getInstance().get(Currency.class, strToCurrencyId);
        BigDecimal creditAmount = BigDecimal.ZERO;
        BigDecimal creditRate = BigDecimal.ONE;

        // Convert available credit automatically
        if (!StringUtils.equals(strFromCurrencyId, strToCurrencyId) && !StringUtils.isEmpty(glItemId)
                && !StringUtils.equals(glItemId, "null")) {

            // Get the rate
            if (!strSetAmount) {
                creditRate = rate;
            } else if (creditUsed.compareTo(BigDecimal.ZERO) != 0) {
                creditRate = BigDecimal.valueOf(amount).divide(creditUsed,
                        FIN_Utility.getConversionRatePrecision(RequestContext.get().getVariablesSecureApp()),
                        RoundingMode.HALF_UP);
            }

            // Loop through all payment documents which generate credit
            scroll = FinancialUtils.getPaymentsWithCredit(businessPartner.getId(), strFromCurrencyId);
            int i = 0;
            try {
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);
                    creditAmount = paymentCredit.getGeneratedCredit().subtract(paymentCredit.getUsedCredit());

                    // Create a payment to consume the credit with a glitem
                    FIN_Payment payment1 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment1.setPaymentDate(new Date());
                    payment1.setAmount(creditAmount);
                    payment1.setDocumentNo(FIN_Utility.getDocumentNo(payment1.getOrganization(),
                            payment1.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment1.setProcessed(false);
                    payment1.setPosted("N");
                    payment1.setDescription(null);
                    payment1.setGeneratedCredit(BigDecimal.ZERO);
                    payment1.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to consume the credit with a glitem
                    FIN_PaymentDetail paymentDetail1 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail1.setClient(paymentCredit.getClient());
                    paymentDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentDetail1.setFinPayment(payment1);
                    paymentDetail1.setAmount(creditAmount);
                    paymentDetail1.setRefund(false);
                    paymentDetail1.setGLItem(glItem);
                    paymentDetail1.setPrepayment(false);

                    // Create a payment schedule detail to consume the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail1 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail1.setClient(paymentCredit.getClient());
                    paymentScheduleDetail1.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail1.setPaymentDetails(paymentDetail1);
                    paymentScheduleDetail1.setAmount(creditAmount);

                    // Process the payment
                    paymentDetail1.getFINPaymentScheduleDetailList().add(paymentScheduleDetail1);
                    payment1.getFINPaymentDetailList().add(paymentDetail1);
                    OBDal.getInstance().save(payment1);
                    OBDal.getInstance().save(paymentDetail1);
                    OBDal.getInstance().save(paymentScheduleDetail1);
                    FIN_PaymentProcess.doProcessPayment(payment1, "D", false, null, null);

                    // Modify description of original credit payment
                    String paymentCreditDesc = paymentCredit.getDescription() + "\n" + String.format(
                            OBMessageUtils.messageBD("APRM_CreditUsedPayment"), payment1.getDocumentNo());
                    paymentCredit.setDescription((paymentCreditDesc.length() > 255)
                            ? paymentCreditDesc.substring(0, 251).concat("...").toString()
                            : paymentCreditDesc.toString());

                    // Create a payment to refund the credit
                    FIN_Payment payment2 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment2.setPaymentDate(new Date());
                    payment2.setAmount(creditAmount.negate());
                    payment2.setDocumentNo(FIN_Utility.getDocumentNo(payment2.getOrganization(),
                            payment2.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment2.setProcessed(false);
                    payment2.setPosted("N");
                    payment2.setDescription(
                            OBMessageUtils.messageBD("APRM_RefundPayment") + ": " + payment1.getDocumentNo());
                    payment2.setGeneratedCredit(BigDecimal.ZERO);
                    payment2.setUsedCredit(creditAmount);

                    // Create a payment credit to refund the credit
                    FIN_Payment_Credit paymentCredit2 = OBProvider.getInstance().get(FIN_Payment_Credit.class);
                    paymentCredit2.setClient(paymentCredit.getClient());
                    paymentCredit2.setOrganization(paymentCredit.getOrganization());
                    paymentCredit2.setPayment(payment2);
                    paymentCredit2.setCreditPaymentUsed(paymentCredit);
                    paymentCredit2.setAmount(creditAmount);
                    paymentCredit2.setCurrency(paymentCredit.getCurrency());

                    // Create a payment detail to refund the credit
                    FIN_PaymentDetail paymentDetail2 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail2.setClient(paymentCredit.getClient());
                    paymentDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentDetail2.setFinPayment(payment2);
                    paymentDetail2.setAmount(creditAmount.negate());
                    paymentDetail2.setRefund(true);
                    paymentDetail2.setPrepayment(true);

                    // Create a payment schedule detail to refund the credit
                    FIN_PaymentScheduleDetail paymentScheduleDetail2 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail2.setClient(paymentCredit.getClient());
                    paymentScheduleDetail2.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail2.setPaymentDetails(paymentDetail2);
                    paymentScheduleDetail2.setAmount(creditAmount.negate());

                    // Process the payment
                    paymentDetail2.getFINPaymentScheduleDetailList().add(paymentScheduleDetail2);
                    payment2.getFINPaymentDetailList().add(paymentDetail2);
                    payment2.getFINPaymentCreditList().add(paymentCredit2);
                    paymentCredit.setUsedCredit(creditAmount);
                    OBDal.getInstance().save(paymentCredit);
                    OBDal.getInstance().save(payment2);
                    OBDal.getInstance().save(paymentCredit2);
                    OBDal.getInstance().save(paymentDetail2);
                    OBDal.getInstance().save(paymentScheduleDetail2);
                    FIN_PaymentProcess.doProcessPayment(payment2, "D", false, null, null);

                    i++;
                    if (i % 100 == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }

                // Set the new currency
                businessPartner.setCurrency(currency);

                // Loop through all payment documents which generate credit
                scroll.beforeFirst();
                i = 0;
                while (scroll.next()) {
                    final String paymentCreditId = (String) scroll.get()[0];
                    final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
                            paymentCreditId);

                    // Create a payment to create the credit with a glitem
                    FIN_Payment payment3 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
                    payment3.setPaymentDate(new Date());
                    payment3.setCurrency(currency);
                    payment3.setAmount(BigDecimal.ZERO);
                    payment3.setDocumentNo(FIN_Utility.getDocumentNo(payment3.getOrganization(),
                            payment3.getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
                    payment3.setProcessed(false);
                    payment3.setPosted("N");
                    payment3.setDescription(null);
                    final BigDecimal generatedCredit = creditAmount.multiply(creditRate)
                            .setScale(currency.getStandardPrecision().intValue(), RoundingMode.HALF_UP);
                    payment3.setGeneratedCredit(generatedCredit);
                    payment3.setUsedCredit(BigDecimal.ZERO);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail3 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail3.setClient(paymentCredit.getClient());
                    paymentDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentDetail3.setFinPayment(payment3);
                    paymentDetail3.setAmount(generatedCredit);
                    paymentDetail3.setRefund(false);
                    paymentDetail3.setPrepayment(true);

                    // Create a payment detail to create the credit with a glitem
                    FIN_PaymentDetail paymentDetail4 = OBProvider.getInstance().get(FIN_PaymentDetail.class);
                    paymentDetail4.setClient(paymentCredit.getClient());
                    paymentDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentDetail4.setFinPayment(payment3);
                    paymentDetail4.setAmount(generatedCredit.negate());
                    paymentDetail4.setGLItem(glItem);
                    paymentDetail4.setRefund(false);
                    paymentDetail4.setPrepayment(false);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail3 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail3.setClient(paymentCredit.getClient());
                    paymentScheduleDetail3.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail3.setPaymentDetails(paymentDetail3);
                    paymentScheduleDetail3.setAmount(generatedCredit);

                    // Create a payment schedule detail to create the credit with a glitem
                    FIN_PaymentScheduleDetail paymentScheduleDetail4 = OBProvider.getInstance()
                            .get(FIN_PaymentScheduleDetail.class);
                    paymentScheduleDetail4.setClient(paymentCredit.getClient());
                    paymentScheduleDetail4.setOrganization(paymentCredit.getOrganization());
                    paymentScheduleDetail4.setPaymentDetails(paymentDetail4);
                    paymentScheduleDetail4.setAmount(generatedCredit.negate());

                    // Process the payment
                    paymentDetail3.getFINPaymentScheduleDetailList().add(paymentScheduleDetail3);
                    paymentDetail4.getFINPaymentScheduleDetailList().add(paymentScheduleDetail4);
                    payment3.getFINPaymentDetailList().add(paymentDetail3);
                    payment3.getFINPaymentDetailList().add(paymentDetail4);
                    OBDal.getInstance().save(payment3);
                    OBDal.getInstance().save(paymentDetail3);
                    OBDal.getInstance().save(paymentDetail4);
                    OBDal.getInstance().save(paymentScheduleDetail3);
                    OBDal.getInstance().save(paymentScheduleDetail4);
                    OBDal.getInstance().save(paymentCredit);
                    FIN_PaymentProcess.doProcessPayment(payment3, "D", false, null, null);

                    i++;
                    if (i % 100 == 0) {
                        OBDal.getInstance().flush();
                        OBDal.getInstance().getSession().clear();
                    }
                }
            } finally {
                scroll.close();
            }
        }

        if (strSetAmount && creditUsed.compareTo(BigDecimal.valueOf(amount)) != 0) {
            businessPartner.setCreditUsed(BigDecimal.valueOf(amount));
        }
        if (!strToCurrencyId.equals(strFromCurrencyId) && strToCurrencyId != null
                && !"null".equals(strToCurrencyId)) {
            businessPartner.setCurrency(OBDal.getInstance().get(Currency.class, strToCurrencyId));
            if (rate.compareTo(BigDecimal.ZERO) != 0 && creditUsed.compareTo(BigDecimal.ZERO) != 0
                    && !strSetAmount) {
                businessPartner.setCreditUsed(creditUsed.multiply(rate));
            }
        }

        String messageText = OBMessageUtils.messageBD("CurrencyUpdated");
        JSONObject msg = new JSONObject();
        msg.put("severity", "success");
        msg.put("text", OBMessageUtils.parseTranslation(messageText));
        jsonRequest.put("message", msg);

    } catch (Exception e) {
        OBDal.getInstance().rollbackAndClose();
        log.error("Error in set new currency Action Handler", e);

        try {
            jsonRequest = new JSONObject();
            Throwable ex = DbUtility.getUnderlyingSQLException(e);
            String message = OBMessageUtils.translateError(ex.getMessage()).getMessage();
            JSONObject errorMessage = new JSONObject();
            errorMessage.put("severity", "error");
            errorMessage.put("text", message);
            jsonRequest.put("message", errorMessage);
        } catch (Exception e2) {
            log.error(e.getMessage(), e2);
            // do nothing, give up
        }
    } finally {
        OBContext.restorePreviousMode();
    }
    return jsonRequest;
}