Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_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:net.sourceforge.fenixedu.domain.Teacher.java

public BigDecimal getProjectsTutorialsCredits(ExecutionYear executionYear) {
    BigDecimal result = BigDecimal.ZERO;
    for (ExecutionSemester executionSemester : executionYear.getExecutionPeriodsSet()) {
        TeacherService teacherService = getTeacherServiceByExecutionPeriod(executionSemester);
        if (teacherService != null) {
            for (DegreeProjectTutorialService degreeProjectTutorialService : teacherService
                    .getDegreeProjectTutorialServices()) {
                result = result.add(degreeProjectTutorialService.getDegreeProjectTutorialServiceCredits());
            }//from  www .  ja v a2 s .  c o  m
        }
    }
    return result.setScale(2, BigDecimal.ROUND_HALF_UP);
}

From source file:controllers.core.PortfolioEntryPlanningController.java

/**
 * Display the details of a planning package.
 * /*from w  w w. j  a v  a2  s  . c o  m*/
 * @param id
 *            the portfolio entry id
 * @param planningPackageId
 *            the planning package id
 */
@With(CheckPortfolioEntryExists.class)
@Dynamic(IMafConstants.PORTFOLIO_ENTRY_DETAILS_DYNAMIC_PERMISSION)
public Result viewPackage(Long id, Long planningPackageId) {

    // get the portfolio entry
    PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(id);

    // get the planning package
    PortfolioEntryPlanningPackage planningPackage = PortfolioEntryPlanningPackageDao
            .getPEPlanningPackageById(planningPackageId);

    // construct the corresponding form data (for the custom attributes)
    PortfolioEntryPlanningPackageFormData portfolioEntryPlanningPackageFormData = new PortfolioEntryPlanningPackageFormData(
            planningPackage);

    // security: the portfolioEntry must be related to the object
    if (!planningPackage.portfolioEntry.id.equals(id)) {
        return forbidden(views.html.error.access_forbidden.render(""));
    }

    // get the allocated resources' days
    BigDecimal allocatedResourcesDays = PortfolioEntryResourcePlanDAO
            .getPEPlanAllocatedActorAsDaysByPlanningPackage(planningPackage)
            .add(PortfolioEntryResourcePlanDAO
                    .getPEResourcePlanAllocatedOrgUnitAsDaysByPlanningPackage(planningPackage))
            .add(PortfolioEntryResourcePlanDAO
                    .getPEResourcePlanAllocatedCompetencyAsDaysByPlanningPackage(planningPackage));

    // get the timesheets' days
    BigDecimal timesheetsDays = TimesheetDao.getTimesheetLogAsTotalHoursByPEPlanningPackage(planningPackage)
            .divide(TimesheetDao.getTimesheetReportHoursPerDay(this.getPreferenceManagerPlugin()),
                    BigDecimal.ROUND_HALF_UP);

    /*
     * Get the attachments
     */

    // authorize the attachments
    FileAttachmentHelper.getFileAttachmentsForDisplay(PortfolioEntryPlanningPackage.class, planningPackageId,
            getAttachmentManagerPlugin(), getUserSessionManagerPlugin());

    // create the table
    List<Attachment> attachments = Attachment
            .getAttachmentsFromObjectTypeAndObjectId(PortfolioEntryPlanningPackage.class, planningPackageId);

    List<AttachmentListView> attachmentsListView = new ArrayList<AttachmentListView>();
    for (Attachment attachment : attachments) {
        attachmentsListView
                .add(new AttachmentListView(attachment, controllers.core.routes.PortfolioEntryPlanningController
                        .deletePackageAttachment(id, planningPackageId, attachment.id).url()));
    }

    Set<String> hideColumns = new HashSet<String>();
    if (!getSecurityService().dynamic("PORTFOLIO_ENTRY_EDIT_DYNAMIC_PERMISSION", "")) {
        hideColumns.add("removeActionLink");
    }

    Table<AttachmentListView> attachmentsTable = this.getTableProvider().get().attachment.templateTable
            .fill(attachmentsListView, hideColumns);

    return ok(views.html.core.portfolioentryplanning.package_view.render(portfolioEntry, planningPackage,
            portfolioEntryPlanningPackageFormData, allocatedResourcesDays, timesheetsDays, attachmentsTable));
}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private void addPlatform(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole) {
    double platformAmount = 0;
    long tradeId = trade.getId();
    long detailId = detail.getId();
    BigDecimal bg = new BigDecimal(getDaysRuleRate(divsionRuleRole.getRule(), trade) * trade.getLoanedAmount());
    platformAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    platformAmount = Math.floor(platformAmount);
    // /*from   ww  w. ja v a  2  s. com*/
    if (platformAmount > 0) {
        UserBaseInfoDO profitUser = userBaseInfoManager
                .queryByAccountId(AppConstantsUtil.getProfitSharingAccount());
        tradeDetailDao.addTradeDetail(new TradeDetail(profitUser.getUserId(), tradeId, (long) platformAmount, 7,
                divsionRuleRole.getPhase(), String.valueOf(detailId)));
    }
}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private void addInvestor(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole) {
    double investAmount = 0;
    long tradeId = trade.getId();
    long detailId = detail.getId();
    BigDecimal bg = new BigDecimal(getDaysRuleRate(divsionRuleRole.getRule(), trade) * detail.getAmount());
    investAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    investAmount = Math.floor(investAmount);
    // //from ww w  . j a  va  2s.  co  m
    if (investAmount > 0)
        tradeDetailDao.addTradeDetail(new TradeDetail(detail.getUserId(), tradeId, (long) investAmount, 12,
                divsionRuleRole.getPhase(), String.valueOf(detailId)));
}

From source file:org.egov.collection.service.elasticsearch.CollectionDocumentElasticSearchService.java

/**
 * Prepares month-wise collections for 3 consecutive years - from current
 * year//from www . j a  v  a2s.com
 *
 * @param collectionDashBoardRequest
 * @return List
 */
public List<CollectionDashBoardTrend> getMonthwiseCollectionDetails(
        final CollectionDashBoardRequest collectionDashBoardRequest, final List<String> serviceDetail,
        final CFinancialYear financialYear) {
    final List<CollectionDashBoardTrend> collTrendsList = new ArrayList<>();
    CollectionDashBoardTrend collTrend;
    Date fromDate;
    Date toDate;
    Date dateForMonth;
    String[] dateArr;
    Integer month;
    Sum aggregateSum;
    Date finYearStartDate = financialYear.getStartingDate();
    Date finYearEndDate = financialYear.getEndingDate();
    final Map<Integer, String> monthValuesMap = DateUtils.getAllMonthsWithFullNames();
    String monthName;
    final List<Map<String, BigDecimal>> yearwiseMonthlyCollList = new ArrayList<>();
    Map<String, BigDecimal> monthwiseColl;
    /**
     * For month-wise collections between the date ranges if dates are sent
     * in the request, consider fromDate and toDate+1 , else calculate from
     * current year start date till current date+1 day
     */
    if (StringUtils.isNotBlank(collectionDashBoardRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDashBoardRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDashBoardRequest.getFromDate(), DATE_FORMAT_YYYYMMDD);
        toDate = org.apache.commons.lang3.time.DateUtils
                .addDays(DateUtils.getDate(collectionDashBoardRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
    } else {
        fromDate = DateUtils.startOfDay(financialYear.getStartingDate());
        toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    }
    Long startTime = System.currentTimeMillis();
    for (int count = 0; count <= 2; count++) {
        monthwiseColl = new LinkedHashMap<>();
        final Aggregations collAggr = getMonthwiseCollectionsForConsecutiveYears(collectionDashBoardRequest,
                fromDate, toDate, serviceDetail);
        final Histogram dateaggs = collAggr.get(DATE_AGG);

        for (final Histogram.Bucket entry : dateaggs.getBuckets()) {
            dateArr = entry.getKeyAsString().split("T");
            dateForMonth = DateUtils.getDate(dateArr[0], DATE_FORMAT_YYYYMMDD);
            month = Integer.valueOf(dateArr[0].split("-", 3)[1]);
            monthName = monthValuesMap.get(month);
            aggregateSum = entry.getAggregations().get("current_total");
            // If the total amount is greater than 0 and the month belongs
            // to respective financial year, add values to the map
            if (DateUtils.between(dateForMonth, finYearStartDate, finYearEndDate)
                    && BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)
                            .compareTo(BigDecimal.ZERO) > 0)
                monthwiseColl.put(monthName,
                        BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        }
        yearwiseMonthlyCollList.add(monthwiseColl);

        /**
         * If dates are passed in request, get result for the date range,
         * else get results for entire financial year
         */
        if (StringUtils.isNotBlank(collectionDashBoardRequest.getFromDate())
                && StringUtils.isNotBlank(collectionDashBoardRequest.getToDate())) {
            fromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1);
            toDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1);
        } else {
            fromDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearStartDate, -1);
            toDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearEndDate, -1);
        }
        finYearStartDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearStartDate, -1);
        finYearEndDate = org.apache.commons.lang3.time.DateUtils.addYears(finYearEndDate, -1);
    }
    Long timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken by getMonthwiseCollectionsForConsecutiveYears() for 3 consecutive years is : "
                + timeTaken + MILLISECS);

    startTime = System.currentTimeMillis();
    /**
     * If dates are passed in request, get result for the date range, else
     * get results for all 12 months
     */
    if (StringUtils.isBlank(collectionDashBoardRequest.getFromDate())
            && StringUtils.isBlank(collectionDashBoardRequest.getToDate()))
        for (final Map.Entry<Integer, String> entry : DateUtils.getAllFinancialYearMonthsWithFullNames()
                .entrySet()) {
            collTrend = new CollectionDashBoardTrend();
            collTrend.setMonth(entry.getValue());
            collTrend.setCyColl(
                    yearwiseMonthlyCollList.get(0).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(0).get(collTrend.getMonth()));
            collTrend.setLyColl(
                    yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()));
            collTrend.setPyColl(
                    yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()));
            collTrendsList.add(collTrend);
        }
    else
        for (final Map.Entry<String, BigDecimal> entry : yearwiseMonthlyCollList.get(0).entrySet()) {
            collTrend = new CollectionDashBoardTrend();
            collTrend.setMonth(entry.getKey());
            collTrend.setCyColl(entry.getValue());
            collTrend.setLyColl(
                    yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(1).get(collTrend.getMonth()));
            collTrend.setPyColl(
                    yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()) == null ? BigDecimal.ZERO
                            : yearwiseMonthlyCollList.get(2).get(collTrend.getMonth()));
            collTrendsList.add(collTrend);
        }
    timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug(
                "Time taken setting values in getMonthwiseCollectionDetails() is : " + timeTaken + MILLISECS);
    return collTrendsList;
}

From source file:cz.cuni.mff.spl.evaluator.statistics.KolmogorovSmirnovTestFlag.java

/**
 * Calculates the exact value of {@code P(D_n < d)} using the method described in [1] (reference
 * in class javadoc above) and {@link org.apache.commons.math3.fraction.BigFraction} (see
 * above).//from   ww  w.ja  va  2s  .c  o  m
 *
 * @param d statistic
 * @param n sample size
 * @return the two-sided probability of \(P(D_n < d)\)
 * @throws MathArithmeticException if algorithm fails to convert {@code h} to a
 *         {@link org.apache.commons.math3.fraction.BigFraction} in expressing {@code d} as \((k
 *         - h) / m\) for integer {@code k, m} and \(0 \le h < 1\).
 */
private double exactK(double d, int n) throws MathArithmeticException {

    final int k = (int) Math.ceil(n * d);

    final FieldMatrix<BigFraction> H = this.createExactH(d, n);
    final FieldMatrix<BigFraction> Hpower = H.power(n);

    BigFraction pFrac = Hpower.getEntry(k - 1, k - 1);

    for (int i = 1; i <= n; ++i) {
        pFrac = pFrac.multiply(i).divide(n);
    }

    /*
     * BigFraction.doubleValue converts numerator to double and the denominator to double and
     * divides afterwards. That gives NaN quite easy. This does not (scale is the number of
     * digits):
     */
    return pFrac.bigDecimalValue(20, BigDecimal.ROUND_HALF_UP).doubleValue();
}

From source file:org.egov.adtax.service.AdvertisementDemandService.java

public EgDemand updateDemandForLegacyEntry(final AdvertisementPermitDetail advertisementPermitDetail,
        EgDemand demand) {//  w ww  .j  ava 2s . co  m
    final Installment installment = getCurrentInstallment();
    BigDecimal totalDemandAmount = BigDecimal.ZERO;

    Boolean taxFullyPaidForCurrentYear = false;

    if (advertisementPermitDetail.getAdvertisement() != null
            && advertisementPermitDetail.getAdvertisement().getLegacy()
            && advertisementPermitDetail.getAdvertisement().getTaxPaidForCurrentYear())
        taxFullyPaidForCurrentYear = true;

    Boolean enchroachmentFeeAlreadyExistInDemand = false;
    Boolean arrearsTaxalreadyExistInDemand = false;
    Boolean taxalreadyExistInDemand = false;
    final List<EgDemandDetails> deleteDmdDtl = new ArrayList<>();
    if (demand == null)
        demand = createDemand(advertisementPermitDetail);
    else {
        final EgDemandReason pendingTaxReason = getDemandReasonByCodeAndInstallment(
                AdvertisementTaxConstants.DEMANDREASON_ARREAR_ADVERTISEMENTTAX, installment);
        final EgDemandReason encroachmentFeeReason = getDemandReasonByCodeAndInstallment(
                AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE, installment);
        final EgDemandReason taxReason = getDemandReasonByCodeAndInstallment(
                AdvertisementTaxConstants.DEMANDREASON_ADVERTISEMENTTAX, installment);

        for (final EgDemandDetails dmdDtl : demand.getEgDemandDetails())
            if (dmdDtl.getEgDemandReason().getId() == taxReason.getId()) {
                taxalreadyExistInDemand = true;
                if (advertisementPermitDetail.getTaxAmount().compareTo(BigDecimal.ZERO) > 0) {

                    totalDemandAmount = totalDemandAmount
                            .add(advertisementPermitDetail.getTaxAmount().subtract(dmdDtl.getAmount()));
                    dmdDtl.setAmount(
                            advertisementPermitDetail.getTaxAmount().setScale(0, BigDecimal.ROUND_HALF_UP));

                    if (taxFullyPaidForCurrentYear)
                        dmdDtl.setAmtCollected(advertisementPermitDetail.getTaxAmount() != null
                                ? advertisementPermitDetail.getTaxAmount()
                                : BigDecimal.ZERO);
                    else
                        dmdDtl.setAmtCollected(BigDecimal.ZERO);
                } else {
                    totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount());
                    deleteDmdDtl.add(dmdDtl);
                    // demand.removeEgDemandDetails(dmdDtl);
                }
            } else if (dmdDtl.getEgDemandReason().getId() == pendingTaxReason.getId()) {
                arrearsTaxalreadyExistInDemand = true;
                if (advertisementPermitDetail.getAdvertisement().getPendingTax() != null
                        && advertisementPermitDetail.getAdvertisement().getPendingTax()
                                .compareTo(BigDecimal.ZERO) > 0) {

                    totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getAdvertisement()
                            .getPendingTax().subtract(dmdDtl.getAmount()));
                    dmdDtl.setAmount(advertisementPermitDetail.getAdvertisement().getPendingTax().setScale(0,
                            BigDecimal.ROUND_HALF_UP));

                    /*
                     * if (taxFullyPaidForCurrentYear) {
                     * dmdDtl.setAmtCollected((advertisementPermitDetail.getAdvertisement().getPendingTax() != null ?
                     * (advertisementPermitDetail .getAdvertisement().getPendingTax()) : BigDecimal.ZERO)); } else
                     */
                    dmdDtl.setAmtCollected(BigDecimal.ZERO);
                } else {
                    totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount());
                    deleteDmdDtl.add(dmdDtl);
                }
            } else if (dmdDtl.getEgDemandReason().getId() == encroachmentFeeReason.getId()) {
                enchroachmentFeeAlreadyExistInDemand = true;
                if (advertisementPermitDetail.getEncroachmentFee() != null
                        && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) {
                    totalDemandAmount = totalDemandAmount
                            .add(advertisementPermitDetail.getEncroachmentFee().subtract(dmdDtl.getAmount()));
                    dmdDtl.setAmount(advertisementPermitDetail.getEncroachmentFee().setScale(0,
                            BigDecimal.ROUND_HALF_UP));

                    if (taxFullyPaidForCurrentYear)
                        dmdDtl.setAmtCollected(advertisementPermitDetail.getEncroachmentFee() != null
                                ? advertisementPermitDetail.getEncroachmentFee()
                                : BigDecimal.ZERO);
                    else
                        dmdDtl.setAmtCollected(BigDecimal.ZERO);

                    // update encroachment fee.. // Encroachment fee may not mandatory. If already part of demand
                } else {
                    totalDemandAmount = totalDemandAmount.subtract(dmdDtl.getAmount());
                    deleteDmdDtl.add(dmdDtl);
                    // delete demand detail
                }

            }

        for (final EgDemandDetails dmdDtls : deleteDmdDtl)
            demand.removeEgDemandDetails(dmdDtls);

        if (!enchroachmentFeeAlreadyExistInDemand && advertisementPermitDetail.getEncroachmentFee() != null
                && advertisementPermitDetail.getEncroachmentFee().compareTo(BigDecimal.ZERO) > 0) {
            demand.addEgDemandDetails(createDemandDetails(advertisementPermitDetail.getEncroachmentFee(),
                    getDemandReasonByCodeAndInstallment(AdvertisementTaxConstants.DEMANDREASON_ENCROCHMENTFEE,
                            installment),
                    taxFullyPaidForCurrentYear ? advertisementPermitDetail.getEncroachmentFee()
                            : BigDecimal.ZERO));
            totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getEncroachmentFee());
            demand.setEgInstallmentMaster(installment);
        }
        if (!arrearsTaxalreadyExistInDemand
                && advertisementPermitDetail.getAdvertisement().getPendingTax() != null
                && advertisementPermitDetail.getAdvertisement().getPendingTax()
                        .compareTo(BigDecimal.ZERO) > 0) {
            demand.addEgDemandDetails(createDemandDetails(
                    advertisementPermitDetail.getAdvertisement().getPendingTax(),
                    getDemandReasonByCodeAndInstallment(
                            AdvertisementTaxConstants.DEMANDREASON_ARREAR_ADVERTISEMENTTAX, installment),
                    BigDecimal.ZERO));
            totalDemandAmount = totalDemandAmount
                    .add(advertisementPermitDetail.getAdvertisement().getPendingTax());
            demand.setEgInstallmentMaster(installment);
        }
        if (!taxalreadyExistInDemand && advertisementPermitDetail.getTaxAmount() != null
                && advertisementPermitDetail.getTaxAmount().compareTo(BigDecimal.ZERO) > 0) {
            demand.addEgDemandDetails(createDemandDetails(advertisementPermitDetail.getTaxAmount(),
                    getDemandReasonByCodeAndInstallment(AdvertisementTaxConstants.DEMANDREASON_ADVERTISEMENTTAX,
                            installment),
                    taxFullyPaidForCurrentYear ? advertisementPermitDetail.getTaxAmount() : BigDecimal.ZERO));
            totalDemandAmount = totalDemandAmount.add(advertisementPermitDetail.getTaxAmount());
            demand.setEgInstallmentMaster(installment);
        }
        demand.addBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP));

    }
    return demand;

}

From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java

public static Map<String, Object> getExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();

    ShoppingCart cart = (ShoppingCart) context.get("cart");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }/*from w ww  . jav a 2s. c  o  m*/

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "GetExpressCheckoutDetails");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
        encoder.add("TOKEN", token);
    } else {
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "AccountingPayPalTokenNotFound", locale));
    }

    NVPDecoder decoder;
    try {
        decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) {
        cart.addOrderNote(decoder.get("NOTE"));
    }

    if (cart.getUserLogin() == null) {
        try {
            GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin")
                    .where("userLoginId", "anonymous").queryOne();
            try {
                cart.setUserLogin(userLogin, dispatcher);
            } catch (CartItemModifyException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId"));
    // Even if anon, a party could already have been created
    String partyId = cart.getOrderPartyId();
    if (partyId == null && anon) {
        // Check nothing has been set on the anon userLogin either
        partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null;
        cart.setOrderPartyId(partyId);
    }
    if (partyId != null) {
        GenericValue party = null;
        try {
            party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (party == null) {
            partyId = null;
        }
    }

    Map<String, Object> inMap = new HashMap<String, Object>();
    Map<String, Object> outMap = null;
    // Create the person if necessary
    boolean newParty = false;
    if (partyId == null) {
        newParty = true;
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("personalTitle", decoder.get("SALUTATION"));
        inMap.put("firstName", decoder.get("FIRSTNAME"));
        inMap.put("middleName", decoder.get("MIDDLENAME"));
        inMap.put("lastName", decoder.get("LASTNAME"));
        inMap.put("suffix", decoder.get("SUFFIX"));
        try {
            outMap = dispatcher.runSync("createPerson", inMap);
            partyId = (String) outMap.get("partyId");
            cart.setOrderPartyId(partyId);
            cart.getUserLogin().setString("partyId", partyId);
            inMap.clear();
            inMap.put("userLogin", cart.getUserLogin());
            inMap.put("partyId", partyId);
            inMap.put("roleTypeId", "CUSTOMER");
            dispatcher.runSync("createPartyRole", inMap);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    // Create a new email address if necessary
    String emailContactMechId = null;
    String emailContactPurposeTypeId = "PRIMARY_EMAIL";
    String emailAddress = decoder.get("EMAIL");
    if (!newParty) {
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(
                EntityCondition.makeCondition(
                        UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")),
                EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"),
                        EntityComparisonOperator.EQUALS, EntityFunction.UPPER(emailAddress))

        ));
        try {
            GenericValue matchingEmail = EntityQuery.use(delegator).from("PartyAndContactMech").where(cond)
                    .orderBy("fromDate").filterByDate().queryFirst();
            if (matchingEmail != null) {
                emailContactMechId = matchingEmail.getString("contactMechId");
            } else {
                // No email found so we'll need to create one but first check if it should be PRIMARY or just BILLING
                long primaryEmails = EntityQuery.use(delegator).from("PartyContactWithPurpose")
                        .where("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS",
                                "contactMechPurposeTypeId", "PRIMARY_EMAIL")
                        .filterByDate("contactFromDate", "contactThruDate", "purposeFromDate",
                                "purposeThruDate")
                        .queryCount();
                if (primaryEmails > 0)
                    emailContactPurposeTypeId = "BILLING_EMAIL";
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (emailContactMechId == null) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId);
        inMap.put("emailAddress", emailAddress);
        inMap.put("partyId", partyId);
        inMap.put("roleTypeId", "CUSTOMER");
        inMap.put("verified", "Y"); // Going to assume PayPal has taken care of this for us
        inMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyEmailAddress", inMap);
            emailContactMechId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    cart.addContactMech("ORDER_EMAIL", emailContactMechId);

    // Phone number
    String phoneNumber = decoder.get("PHONENUM");
    String phoneContactId = null;
    if (phoneNumber != null) {
        inMap.clear();
        if (phoneNumber.startsWith("+")) {
            // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber
            String[] phoneNumbers = phoneNumber.split(" ");
            inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0]));
            inMap.put("contactNumber", phoneNumbers[1]);
        } else {
            // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber
            inMap.put("countryCode", "1");
            String[] phoneNumbers = phoneNumber.split("-");
            inMap.put("areaCode", phoneNumbers[0]);
            inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]);
        }
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("partyId", partyId);
        try {
            outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap);
            phoneContactId = (String) outMap.get("contactMechId");
            cart.addContactMech("PHONE_BILLING", phoneContactId);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
        }
    }
    // Create a new Postal Address if necessary
    String postalContactId = null;
    boolean needsShippingPurpose = true;
    // if the cart for some reason already has a billing address, we'll leave it be
    boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null);
    Map<String, Object> postalMap = new HashMap<String, Object>();
    postalMap.put("toName", decoder.get("SHIPTONAME"));
    postalMap.put("address1", decoder.get("SHIPTOSTREET"));
    postalMap.put("address2", decoder.get("SHIPTOSTREET2"));
    postalMap.put("city", decoder.get("SHIPTOCITY"));
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"),
            delegator);
    postalMap.put("countryGeoId", countryGeoId);
    postalMap.put("stateProvinceGeoId",
            parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator));
    postalMap.put("postalCode", decoder.get("SHIPTOZIP"));
    if (!newParty) {
        // We want an exact match only
        EntityCondition cond = EntityCondition
                .makeCondition(UtilMisc.toList(EntityCondition.makeCondition(postalMap),
                        EntityCondition.makeCondition(UtilMisc.toMap("attnName", null, "directions", null,
                                "postalCodeExt", null, "postalCodeGeoId", null)),
                        EntityCondition.makeCondition("partyId", partyId)));
        try {
            GenericValue postalMatch = EntityQuery.use(delegator).from("PartyAndPostalAddress").where(cond)
                    .orderBy("fromDate").filterByDate().queryFirst();
            if (postalMatch != null) {
                postalContactId = postalMatch.getString("contactMechId");
                List<GenericValue> postalPurposes = EntityQuery.use(delegator).from("PartyContactMechPurpose")
                        .where("partyId", partyId, "contactMechId", postalContactId).filterByDate().queryList();
                List<Object> purposeStrings = EntityUtil.getFieldListFromEntityList(postalPurposes,
                        "contactMechPurposeTypeId", false);
                if (UtilValidate.isNotEmpty(purposeStrings) && purposeStrings.contains("SHIPPING_LOCATION")) {
                    needsShippingPurpose = false;
                }
                if (needsBillingPurpose && UtilValidate.isNotEmpty(purposeStrings)
                        && purposeStrings.contains("BILLING_LOCATION")) {
                    needsBillingPurpose = false;
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (postalContactId == null) {
        postalMap.put("userLogin", cart.getUserLogin());
        postalMap.put("fromDate", UtilDateTime.nowTimestamp());
        try {
            outMap = dispatcher.runSync("createPartyPostalAddress", postalMap);
            postalContactId = (String) outMap.get("contactMechId");
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }
    if (needsShippingPurpose || needsBillingPurpose) {
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("contactMechId", postalContactId);
        inMap.put("partyId", partyId);
        try {
            if (needsShippingPurpose) {
                inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
            if (needsBillingPurpose) {
                inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION");
                dispatcher.runSync("createPartyContactMechPurpose", inMap);
            }
        } catch (GenericServiceException e) {
            // Not the end of the world, we'll carry on
            Debug.logInfo(e.getMessage(), module);
        }
    }

    // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work with is the shipping option label
    // that was shown to the customer
    String shipMethod = decoder.get("SHIPPINGOPTIONNAME");
    if ("Calculated Offline".equals(shipMethod)) {
        cart.setAllCarrierPartyId("_NA_");
        cart.setAllShipmentMethodTypeId("NO_SHIPPING");
    } else {
        String[] shipMethodSplit = shipMethod.split(" - ");
        cart.setAllCarrierPartyId(shipMethodSplit[0]);
        String shippingMethodTypeDesc = StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
        try {
            GenericValue shipmentMethod = EntityQuery.use(delegator).from("ProductStoreShipmentMethView")
                    .where("productStoreId", cart.getProductStoreId(), "partyId", shipMethodSplit[0],
                            "roleTypeId", "CARRIER", "description", shippingMethodTypeDesc)
                    .queryFirst();
            cart.setAllShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
        } catch (GenericEntityException e1) {
            Debug.logError(e1, module);
        }
    }
    //Get rid of any excess ship groups
    List<CartShipInfo> shipGroups = cart.getShipGroups();
    for (int i = 1; i < shipGroups.size(); i++) {
        Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i);
        for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) {
            cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false);
        }
    }
    cart.cleanUpShipGroups();
    cart.setAllShippingContactMechId(postalContactId);
    Map<String, Object> result = ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0);
    if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
        return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE));
    }

    BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
    if (shippingTotal == null) {
        shippingTotal = BigDecimal.ZERO;
    }
    cart.setItemShipGroupEstimate(shippingTotal, 0);
    CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart);
    try {
        cho.calcAndAddTax();
    } catch (GeneralException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    // Create the PayPal payment method
    inMap.clear();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", partyId);
    inMap.put("contactMechId", postalContactId);
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", decoder.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", decoder.get("PAYERSTATUS"));

    try {
        outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");

    cart.clearPayments();
    BigDecimal maxAmount = cart.getGrandTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    cart.addPaymentAmount(paymentMethodId, maxAmount, true);

    return ServiceUtil.returnSuccess();

}

From source file:org.codecover.eclipse.views.RedundancyGraphView.java

private final void calculateSuiteRedundancy(String Criterion) {
    Set<CoverableItem> coverableItemSet = createCoverableItemSet(Criterion);
    Set<CoverableItem> mainSet = new HashSet<CoverableItem>(coverableItemSet);
    Set<CoverableItem> otherTestSet = new HashSet<CoverableItem>();
    if (Criterion.compareTo("Condition") != 0) {
        for (int i = 0; i < this.wholeTestCases.size(); i++) {
            TestCase currentTestCase = this.wholeTestCases.get(i);
            Set<CoverableItem> currentCoveredSet = new HashSet<CoverableItem>(
                    currentTestCase.getCoverageData().keySet());
            currentCoveredSet.retainAll(mainSet);
            int ts = currentCoveredSet.size();
            otherTestSet.clear();//from w  w w .ja v a2  s.c  o m
            for (int a = 0; a < this.wholeTestCases.size(); a++) {
                if (a != i) {
                    TestCase secondTestCase = this.wholeTestCases.get(a);
                    if (!this.RedundantTestCases.contains(secondTestCase)) {
                        Set<CoverableItem> secondSet = new HashSet<CoverableItem>(
                                secondTestCase.getCoverageData().keySet());
                        secondSet.retainAll(mainSet);
                        otherTestSet.addAll(secondSet);
                    }
                }
            }

            currentCoveredSet.retainAll(otherTestSet);
            double rts = currentCoveredSet.size();
            Double SuiteR = 0.0D;
            if (ts != 0.0D) {
                SuiteR = rts / ts;
            } else {
                SuiteR = (0.0D / 0.0D);
            }

            if (!SuiteR.isNaN()) {
                BigDecimal bd = new BigDecimal(SuiteR);
                bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                SuiteR = bd.doubleValue();
            }
            if (this.RedundantTestCases.contains(currentTestCase)) {
                this.SuiteRedundancy.put(currentTestCase.getName(), 1.0);
            } else {
                this.SuiteRedundancy.put(currentTestCase.getName(), SuiteR);
            }
        }
    } else {
        for (int i = 0; i < this.wholeTestCases.size(); i++) {
            TestCase currentTestCase = this.wholeTestCases.get(i);
            Set<CoverableItem> currentCoveredSet = new HashSet<CoverableItem>(
                    currentTestCase.getAssignmentsMap().keySet());
            currentCoveredSet.retainAll(mainSet);
            int amountFirstTestCase = 0;
            for (CoverableItem item : currentCoveredSet) {
                BooleanAssignmentMap map = currentTestCase.getAssignmentsMap().get(item);
                amountFirstTestCase += map.getEvaluatedAssignments().size();
            }

            int ts = amountFirstTestCase;
            int amountIntersection = 0;
            for (CoverableItem item : currentCoveredSet) {
                BooleanAssignmentMap map1 = currentTestCase.getAssignmentsMap().get(item);
                Set<BooleanAssignment> sharedAssignments = new HashSet<BooleanAssignment>(
                        map1.getEvaluatedAssignments());
                Set<BooleanAssignment> otherAssignments = new HashSet<BooleanAssignment>();
                for (int a = 0; a < this.wholeTestCases.size(); a++) {
                    if (a != i) {
                        TestCase secondTestCase = this.wholeTestCases.get(a);
                        if (!this.RedundantTestCases.contains(secondTestCase)) {
                            Set<CoverableItem> secondSet = new HashSet<CoverableItem>(
                                    secondTestCase.getAssignmentsMap().keySet());
                            secondSet.retainAll(mainSet);
                            if (secondSet.contains(item)) {
                                BooleanAssignmentMap map2 = secondTestCase.getAssignmentsMap().get(item);
                                otherAssignments.addAll(map2.getEvaluatedAssignments());
                            }
                        }
                    }
                }

                sharedAssignments.retainAll(otherAssignments);
                amountIntersection += sharedAssignments.size();
            }

            double rts = amountIntersection;
            Double SuiteR = 0.0D;
            if (ts != 0.0D) {
                SuiteR = rts / ts;
            } else {
                SuiteR = (0.0D / 0.0D);
            }

            if (!SuiteR.isNaN()) {
                BigDecimal bd = new BigDecimal(SuiteR);
                bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                SuiteR = bd.doubleValue();
            }
            this.SuiteRedundancy.put(currentTestCase.getName(), SuiteR);
        }
    }
}

From source file:org.egov.wtms.service.es.WaterChargeElasticSearchService.java

/**
 * Prepare list of WaterTaxPayerDetails for each bill collector by summing
 * up the values in each ward for the respective bil collector
 *
 * @param waterChargedashBoardRequest/* w  w w  .j av  a2 s  .c  o m*/
 * @param billCollectorWiseMap
 * @param billCollectorWiseWaterTaxPayerDetails
 */
private void prepareTaxersInfoForBillCollectors(final WaterChargeDashBoardRequest waterChargedashBoardRequest,
        final Map<String, List<WaterTaxPayerDetails>> billCollectorWiseMap,
        final List<WaterTaxPayerDetails> billCollectorWiseWaterTaxPayerDetails) {
    BigDecimal cytdColl;
    BigDecimal lytdColl;
    BigDecimal cytdDmd;
    BigDecimal totalDmd;
    WaterTaxPayerDetails waterTaxPayerDetails;
    for (final Entry<String, List<WaterTaxPayerDetails>> entry : billCollectorWiseMap.entrySet()) {
        waterTaxPayerDetails = new WaterTaxPayerDetails();
        cytdColl = BigDecimal.ZERO;
        lytdColl = BigDecimal.ZERO;
        cytdDmd = BigDecimal.ZERO;
        totalDmd = BigDecimal.ZERO;
        for (final WaterTaxPayerDetails taxPayer : entry.getValue()) {
            totalDmd = totalDmd.add(taxPayer.getTotalDmd() == null ? BigDecimal.ZERO : taxPayer.getTotalDmd());
            cytdColl = cytdColl.add(taxPayer.getCurrentYearTillDateColl() == null ? BigDecimal.ZERO
                    : taxPayer.getCurrentYearTillDateColl());
            cytdDmd = cytdDmd.add(taxPayer.getCurrentYearTillDateDmd() == null ? BigDecimal.ZERO
                    : taxPayer.getCurrentYearTillDateDmd());
            lytdColl = lytdColl.add(taxPayer.getLastYearTillDateColl() == null ? BigDecimal.ZERO
                    : taxPayer.getLastYearTillDateColl());
        }
        waterTaxPayerDetails.setBillCollector(entry.getKey());
        waterTaxPayerDetails.setRegionName(waterChargedashBoardRequest.getRegionName());
        waterTaxPayerDetails.setDistrictName(waterChargedashBoardRequest.getDistrictName());
        waterTaxPayerDetails.setUlbGrade(waterChargedashBoardRequest.getUlbGrade());
        waterTaxPayerDetails.setCurrentYearTillDateColl(cytdColl);
        waterTaxPayerDetails.setCurrentYearTillDateDmd(cytdDmd);
        waterTaxPayerDetails.setCurrentYearTillDateBalDmd(cytdDmd.subtract(cytdColl));
        waterTaxPayerDetails.setTotalDmd(totalDmd);
        waterTaxPayerDetails.setLastYearTillDateColl(lytdColl);
        waterTaxPayerDetails.setAchievement(cytdColl.multiply(WaterTaxConstants.BIGDECIMAL_100).divide(cytdDmd,
                1, BigDecimal.ROUND_HALF_UP));
        if (lytdColl.compareTo(BigDecimal.ZERO) > 0)
            cytdColl.subtract(lytdColl).multiply(WaterTaxConstants.BIGDECIMAL_100).divide(lytdColl, 1,
                    BigDecimal.ROUND_HALF_UP);
        billCollectorWiseWaterTaxPayerDetails.add(waterTaxPayerDetails);
    }
}