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:com.selfsoft.business.action.TbFixEntrustAction.java

public String statisticsTbFixEntrust() throws Exception {

    ActionContext.getContext().put("tmUserMap", tmUserService.findAllTmUserMap());

    if (null == tbFixEntrust) {

        tbFixEntrust = new TbFixEntrust();

        tbFixEntrust.setIsvalid(Constants.ISVALIDVALUE);

        Date d = new Date();

        Date s = CommonMethod.parseStringToDate(
                CommonMethod.getYear(d) + "-" + CommonMethod.getMonth(d) + "-01", "yyyy-MM-dd");

        Date e = CommonMethod.parseStringToDate(
                CommonMethod.getYear(d) + "-" + CommonMethod.getMonth(d) + "-"
                        + CommonMethod.getMonthDays(CommonMethod.getYear(d), CommonMethod.getMonth(d)),
                "yyyy-MM-dd");

        tbFixEntrust.setFixDateStart(s);

        tbFixEntrust.setFixDateEnd(e);//from   w  w  w.ja v a  2s.  c om
    }

    List<TbFixEntrust> tbFixEntrustList = tbFixEntrustService.findByTbFixEntrust(tbFixEntrust);

    ActionContext.getContext().put("tbFixEntrustList", tbFixEntrustList);

    if (null != tbFixEntrustList && tbFixEntrustList.size() > 0) {

        BigDecimal d_fixHourAll = new BigDecimal("0.00");

        for (TbFixEntrust tbFixEntrust : tbFixEntrustList) {

            Double fixHourAll = tbFixEntrustContentService
                    .countTbFixEnTrustContentByTbFixEntrustId(tbFixEntrust.getId());

            d_fixHourAll = d_fixHourAll
                    .add(new BigDecimal(String.valueOf(fixHourAll == null ? 0.00d : fixHourAll)))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
        }

        ActionContext.getContext().put("fixHourAll", d_fixHourAll);
    }

    //ActionContext.getContext().put("sellPriceAll",new BigDecimal(tbFixEntrustService.getTotalSellPriceByEntrustList(tbFixEntrustList)).setScale(2));

    //ActionContext.getContext().put("costPriceAll",new BigDecimal(tbFixEntrustService.getTotalCostPriceByEntrustList(tbFixEntrustList)).setScale(2));

    ActionContext.getContext().put("sellPriceAll",
            tbFixEntrustService.getTotalSellPriceByEntrustList(tbFixEntrustList));

    ActionContext.getContext().put("costPriceAll",
            tbFixEntrustService.getTotalCostPriceByEntrustList(tbFixEntrustList));

    List<StatisticsTbFixBusinessVo> statisticsTbFixBusinessVoList = tbFixEntrustService
            .statisticsTbFixEntrust(tbFixEntrust);

    ActionContext.getContext().put("statisticsTbFixBusinessVoList", statisticsTbFixBusinessVoList);

    return Constants.SUCCESS;

}

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

private void addBrokerRelationUser(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole)
        throws Exception {
    long detailId = detail.getId();
    long tradeId = trade.getId();
    Page<UserRelationDO> userRelationsPage = userRelationManager.getRelationsByConditions(null, null,
            detail.getUserId(), null);/*from  w  ww .  ja v  a 2  s.  c o  m*/

    UserBaseInfoDO jjrUserBaseInfo = null;
    if (ListUtil.isNotEmpty(userRelationsPage.getResult())) {
        UserRelationDO relationDO = userRelationsPage.getResult().get(0);
        List<UserBaseInfoDO> curParentJjrs = userBaseInfoManager.queryByType(null,
                String.valueOf(relationDO.getParentId()));
        if (ListUtil.isNotEmpty(curParentJjrs)) {
            if (UserTypeEnum.GR.code().equals(curParentJjrs.get(0).getType())) {
                jjrUserBaseInfo = curParentJjrs.get(0);
            }
        }
        if (jjrUserBaseInfo == null && this.sysFunctionConfigService.isAllEconomicMan()) {
            jjrUserBaseInfo = userBaseInfoManager.queryByUserId(detail.getUserId());
        }
    }
    if (jjrUserBaseInfo != null) {
        ProfitAsignInfo profitAsignInfo = userRelationManager
                .queryByReceiveIdAndDistributionId(detail.getUserId(), jjrUserBaseInfo.getUserId());
        double distributionRule = 0;
        double distributionAmount = 0;
        if (profitAsignInfo != null) {
            distributionRule = CommonUtil.mul(divsionRuleRole.getRule(),
                    profitAsignInfo.getDistributionQuota());
        }
        double actualRule = divsionRuleRole.getRule() - distributionRule;
        BigDecimal bg = new BigDecimal(getDaysRuleRate(actualRule, trade) * detail.getAmount());
        double jjrAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
        jjrAmount = Math.floor(jjrAmount);
        if (distributionRule > 0) {
            BigDecimal bgdis = new BigDecimal(getDaysRuleRate(distributionRule, trade) * detail.getAmount());
            distributionAmount = bgdis.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
            distributionAmount = Math.floor(distributionAmount);
            //???
            TradeDetail extraDetail = new TradeDetail(detail.getUserId(), tradeId, (long) distributionAmount,
                    12, divsionRuleRole.getPhase(), String.valueOf(detailId));
            extraDetail.setProfitType(1);
            extraDetail.setProfitRate(distributionRule);
            tradeDetailDao.addTradeDetail(extraDetail);
        }

        //?
        tradeDetailDao.addTradeDetail(new TradeDetail(jjrUserBaseInfo.getUserId(), tradeId, (long) jjrAmount,
                11, divsionRuleRole.getPhase(), String.valueOf(detailId)));
    }

}

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

public static Map<String, Object> doExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));
    Locale locale = (Locale) context.get("locale");

    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {/*  w  w  w . j  a  va2s.co  m*/
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod", false);
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal subTotal = grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2,
            BigDecimal.ROUND_HALF_UP);
    encoder.add("ITEMAMT", subTotal.toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalPaymentSetting, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

    Map<String, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
        if (errorMessages.containsKey("10417")) {
            // "The transaction cannot complete successfully,  Instruct the customer to use an alternative payment method"
            // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again
            boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
            if (retry) {
                context.put("_RETRY_", false);
                return PayPalServices.doExpressCheckout(dctx, context);
            }
        }
        return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));

    Map<String, Object> outMap = null;
    try {
        outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
        Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
        return outMap;
    }
    return ServiceUtil.returnSuccess();
}

From source file:com.github.totyumengr.minicubes.cluster.TimeSeriesMiniCubeManagerHzImpl.java

@Override
public BigDecimal sum(String indName, Map<String, List<Integer>> filterDims) {

    try {/*from w  w w  .  j  a  v a  2  s . c  o  m*/
        Set<String> cubeIds = cubeIds();

        // Do execute
        List<BigDecimal> results = execute(new Sum(indName, filterDims), cubeIds, hzExecutorTimeout);
        LOGGER.debug("Sum {} on {} results is {}", indName, cubeIds, results);

        BigDecimal result = results.stream().reduce(new BigDecimal(0), (x, y) -> x.add(y)).setScale(IND_SCALE,
                BigDecimal.ROUND_HALF_UP);
        LOGGER.info("Sum {} on {} result is {}", indName, cubeIds, result);

        return result;
    } finally {
        AGG_CONTEXT.remove();
    }
}

From source file:org.egov.ptis.service.es.PropertyTaxElasticSearchIndexService.java

/**
 * Returns Top Ten with ULB wise grouping and total amount aggregation
 *
 * @param collectionDetailsRequest//from w  ww.  j a v a  2  s  .  co m
 * @param indexName
 * @param order
 * @param orderingAggregationName
 * @return
 */
public List<TaxPayerDetails> returnUlbWiseAggregationResults(
        final CollectionDetailsRequest collectionDetailsRequest, final String indexName, final Boolean order,
        final String orderingAggregationName, final int size, final boolean isBillCollectorWise,
        CFinancialYear currFinYear) {
    BigDecimal proportionalArrearDmd;
    BigDecimal proportionalCurrDmd;
    BigDecimal variation;
    Sum totalDemandAggregation;
    Sum totalCollectionAggregation;
    Sum arrearDmd;
    Sum currentDmd;
    Sum arrearInterestDmd;
    Sum currentInterestDmd;
    Sum arrearCollAmt;
    Sum currentCollAmt;
    Sum arrearIntColl;
    Sum currentIntColl;
    final List<TaxPayerDetails> taxPayers = new ArrayList<>();
    Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>();
    final BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest)
            .filter(QueryBuilders.matchQuery(IS_ACTIVE, true))
            .filter(QueryBuilders.matchQuery(IS_EXEMPTED, false));

    // orderingAggregationName is the aggregation name by which we have to
    // order the results
    // IN this case can be one of "totaldemand" or "total_collection" or
    // "avg_achievement"
    String groupingField;
    if (StringUtils.isNotBlank(collectionDetailsRequest.getUlbCode()) || StringUtils
            .isNotBlank(collectionDetailsRequest.getType())
            && (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_BILLCOLLECTORWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_REVENUEINSPECTORWISE
                            .equalsIgnoreCase(collectionDetailsRequest.getType())
                    || DASHBOARD_GROUPING_REVENUEOFFICERWISE
                            .equalsIgnoreCase(collectionDetailsRequest.getType())))
        groupingField = REVENUE_WARD;
    else
        groupingField = CITY_NAME;

    AggregationBuilder aggregation;
    SearchQuery searchQueryColl;
    // Apply the ordering and max results size only if the type is not
    // billcollector
    if (!isBillCollectorWise) {
        aggregation = prepareAggregationForTaxPayers(size, groupingField)
                .order(Terms.Order.aggregation(orderingAggregationName, order));
        searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
                .addAggregation(aggregation).build();
    } else {
        aggregation = prepareAggregationForTaxPayers(250, groupingField);
        searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery)
                .withPageable(new PageRequest(0, 250)).addAggregation(aggregation).build();
    }

    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    final Date fromDate = DateUtils.startOfDay(currFinYear.getStartingDate());
    final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    final Date lastYearFromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1);
    final Date lastYearToDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1);

    // Fetch ward wise Bill Collector details for ward based grouping
    if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType()))
        wardWiseBillCollectors = collectionIndexElasticSearchService
                .getWardWiseBillCollectors(collectionDetailsRequest);

    TaxPayerDetails taxDetail;
    final StringTerms totalAmountAggr = collAggr.get(BY_AGGREGATION_FIELD);
    BigDecimal lastYearCollection;
    for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) {
        taxDetail = new TaxPayerDetails();
        taxDetail.setRegionName(collectionDetailsRequest.getRegionName());
        taxDetail.setDistrictName(collectionDetailsRequest.getDistrictName());
        taxDetail.setUlbGrade(collectionDetailsRequest.getUlbGrade());
        final String fieldName = String.valueOf(entry.getKey());
        // If the grouping is based on ward, set the Bill Collector name and number
        if (groupingField.equals(REVENUE_WARD)) {
            taxDetail.setWardName(fieldName);
            if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType())
                    && !wardWiseBillCollectors.isEmpty()) {
                taxDetail.setBillCollector(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollector());
                taxDetail.setBillCollMobNo(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollectorMobileNo());
                taxDetail.setBillCollectorCode(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY
                        : wardWiseBillCollectors.get(fieldName).getBillCollectorCode());
            }
        } else
            taxDetail.setUlbName(fieldName);

        // Proportional Demand = (totalDemand/12)*noOfmonths
        final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1;
        totalDemandAggregation = entry.getAggregations().get(TOTALDEMAND);
        totalCollectionAggregation = entry.getAggregations().get(TOTAL_COLLECTION);
        arrearDmd = entry.getAggregations().get(ARREAR_DMD_STR);
        currentDmd = entry.getAggregations().get(CURR_DMD);
        arrearInterestDmd = entry.getAggregations().get(ARREAR_INTEREST_DMD);
        currentInterestDmd = entry.getAggregations().get(CURR_INTEREST_DMD);
        arrearCollAmt = entry.getAggregations().get(ARREAR_COLLECTION);
        currentCollAmt = entry.getAggregations().get(ANNUAL_COLLECTION);
        arrearIntColl = entry.getAggregations().get(ARREAR_INTEREST_COLLECTION);
        currentIntColl = entry.getAggregations().get(CURRENT_INTEREST_COLLECTION);

        final BigDecimal totalDemandValue = BigDecimal.valueOf(totalDemandAggregation.getValue()).setScale(0,
                BigDecimal.ROUND_HALF_UP);
        final BigDecimal totalCollections = BigDecimal.valueOf(totalCollectionAggregation.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP);
        final BigDecimal proportionalDemand = totalDemandValue
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        taxDetail.setTotalDmd(totalDemandValue);
        taxDetail.setCytdColl(totalCollections);
        taxDetail.setCytdDmd(proportionalDemand);
        if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0)
            taxDetail.setAchievement(totalCollections.multiply(BIGDECIMAL_100).divide(proportionalDemand, 1,
                    BigDecimal.ROUND_HALF_UP));
        taxDetail.setCytdBalDmd(proportionalDemand.subtract(totalCollections));
        if (StringUtils.isNotBlank(taxDetail.getUlbName()))
            lastYearCollection = collectionIndexElasticSearchService.getCollectionBetweenDates(
                    collectionDetailsRequest, lastYearFromDate, lastYearToDate, fieldName, null, "totalAmount");
        else
            lastYearCollection = collectionIndexElasticSearchService.getCollectionBetweenDates(
                    collectionDetailsRequest, lastYearFromDate, lastYearToDate, null, fieldName, "totalAmount");
        taxDetail.setLytdColl(lastYearCollection);
        taxDetail.setArrearColl(
                BigDecimal.valueOf(arrearCollAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentColl(
                BigDecimal.valueOf(currentCollAmt.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setInterestColl(
                BigDecimal.valueOf(arrearIntColl.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).add(
                        BigDecimal.valueOf(currentIntColl.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));
        taxDetail.setArrearDemand(
                BigDecimal.valueOf(arrearDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentDemand(
                BigDecimal.valueOf(currentDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setArrearInterestDemand(
                BigDecimal.valueOf(arrearInterestDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        taxDetail.setCurrentInterestDemand(
                BigDecimal.valueOf(currentInterestDmd.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        proportionalArrearDmd = taxDetail.getArrearDemand()
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        proportionalCurrDmd = taxDetail.getCurrentDemand()
                .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                .multiply(BigDecimal.valueOf(noOfMonths));
        taxDetail.setProportionalArrearDemand(proportionalArrearDmd);
        taxDetail.setProportionalCurrentDemand(proportionalCurrDmd);

        // variance = ((currentYearCollection -
        // lastYearCollection)*100)/lastYearCollection

        if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0)
            variation = BIGDECIMAL_100;
        else
            variation = totalCollections.subtract(lastYearCollection).multiply(BIGDECIMAL_100)
                    .divide(lastYearCollection, 1, BigDecimal.ROUND_HALF_UP);
        taxDetail.setLyVar(variation);
        taxPayers.add(taxDetail);
    }
    // If for Bill Collector, then fetch details for all wards, else limit
    // the results size
    if (isBillCollectorWise)
        return taxPayers;
    else
        return returnTopResults(taxPayers, size, order);
}

From source file:com.osafe.services.OsafePayPalServices.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));*/
        return ServiceUtil.returnError(
                "Couldn't retrieve a PaymentGatewayConfigPayPal record for Express Checkout, cannot continue.");
    }//from  w  ww.ja va 2  s  . c  om

    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));*/
        return ServiceUtil
                .returnError("Express Checkout token not present in cart, cannot get checkout details.");
    }

    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 = delegator.findOne("UserLogin", false, "userLoginId", "anonymous");
            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 = delegator.findOne("Party", false, "partyId", partyId);
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (party == null) {
            partyId = null;
        }
    }

    Map<String, Object> inMap = FastMap.newInstance();
    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)),
                EntityUtil.getFilterByDateExpr()

        ));
        try {
            GenericValue matchingEmail = EntityUtil.getFirst(delegator.findList("PartyAndContactMech", cond,
                    null, UtilMisc.toList("fromDate"), null, false));
            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
                cond = EntityCondition.makeCondition(UtilMisc.toList(
                        EntityCondition.makeCondition(UtilMisc.toMap("partyId", partyId, "contactMechTypeId",
                                "EMAIL_ADDRESS", "contactMechPurposeTypeId", "PRIMARY_EMAIL")),
                        EntityCondition.makeConditionDate("contactFromDate", "contactThruDate"),
                        EntityCondition.makeConditionDate("purposeFromDate", "purposeThruDate")));
                List<GenericValue> primaryEmails = delegator.findList("PartyContactWithPurpose", cond, null,
                        null, null, false);
                if (UtilValidate.isNotEmpty(primaryEmails))
                    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 = FastMap.newInstance();
    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 = OsafePayPalServices.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)),
                        EntityUtil.getFilterByDateExpr(), EntityCondition.makeCondition("partyId", partyId)));
        try {
            GenericValue postalMatch = EntityUtil.getFirst(delegator.findList("PartyAndPostalAddress", cond,
                    null, UtilMisc.toList("fromDate"), null, false));
            if (postalMatch != null) {
                postalContactId = postalMatch.getString("contactMechId");
                EntityCondition purposeCond = EntityCondition.makeCondition(UtilMisc.toList(
                        EntityCondition.makeCondition(
                                UtilMisc.toMap("partyId", partyId, "contactMechId", postalContactId)),
                        EntityUtil.getFilterByDateExpr()));
                List<GenericValue> postalPurposes = delegator.findList("PartyContactMechPurpose", purposeCond,
                        null, null, null, false);
                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");
    Debug.log("gotPayPalShipMethod" + shipMethod, module);
    if (UtilValidate.isNotEmpty(shipMethod)) {
        if ("Calculated Offline".equals(shipMethod)) {
            cart.setCarrierPartyId("_NA_");
            cart.setShipmentMethodTypeId("NO_SHIPPING");
        } else {
            String[] shipMethodSplit = shipMethod.split(" - ");
            cart.setCarrierPartyId(shipMethodSplit[0]);
            String shippingMethodTypeDesc = StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
            try {
                EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toMap("productStoreId",
                        cart.getProductStoreId(), "partyId", shipMethodSplit[0], "roleTypeId", "CARRIER",
                        "description", shippingMethodTypeDesc));
                GenericValue shipmentMethod = EntityUtil.getFirst(
                        delegator.findList("ProductStoreShipmentMethView", cond, null, null, null, false));
                cart.setShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
            } catch (GenericEntityException e1) {
                Debug.logError(e1, module);
            }
        }
        Debug.log("gotShipMethod" + shipMethod, 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.setShippingContactMechId(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.efaps.esjp.accounting.transaction.Recalculate_Base.java

/**
 * Creates the gain loss4 document account.
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return the return//from w ww. ja va  2s .c o m
 * @throws EFapsException on error
 */
public Return createGainLoss4DocumentAccount(final Parameter _parameter) throws EFapsException {
    final Set<String> setAccounts = getAccounts4DocumentConfig(_parameter);

    final String[] oidsDoc = (String[]) Context.getThreadContext().getSessionAttribute(
            CIFormAccounting.Accounting_GainLoss4DocumentAccountForm.selectedDocuments.name);
    final DateTime dateTo = new DateTime(_parameter
            .getParameterValue(CIFormAccounting.Accounting_GainLoss4DocumentAccountForm.transactionDate.name));
    for (final String oid : oidsDoc) {
        final Instance instDoc = Instance.get(oid);

        final QueryBuilder attrQuerBldr = new QueryBuilder(CIAccounting.Transaction2SalesDocument);
        attrQuerBldr.addWhereAttrEqValue(CIAccounting.Transaction2SalesDocument.ToLink, instDoc);
        final AttributeQuery attrQuery = attrQuerBldr
                .getAttributeQuery(CIAccounting.Transaction2SalesDocument.FromLink);

        // filter classification Document
        final QueryBuilder attrQueryBldr2 = new QueryBuilder(CIAccounting.Transaction);
        attrQueryBldr2.addWhereAttrEqValue(CIAccounting.Transaction.PeriodLink,
                _parameter.getInstance().getId());
        attrQueryBldr2.addWhereAttrInQuery(CIAccounting.Transaction.ID, attrQuery);
        final AttributeQuery attrQuery2 = attrQuerBldr.getAttributeQuery(CIAccounting.Transaction.ID);

        final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.TransactionPositionAbstract);
        queryBldr.addWhereAttrInQuery(CIAccounting.TransactionPositionAbstract.TransactionLink, attrQuery2);
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CIAccounting.TransactionPositionAbstract.Amount,
                CIAccounting.TransactionPositionAbstract.RateAmount,
                CIAccounting.TransactionPositionAbstract.CurrencyLink,
                CIAccounting.TransactionPositionAbstract.RateCurrencyLink);
        final SelectBuilder selAcc = new SelectBuilder()
                .linkto(CIAccounting.TransactionPositionAbstract.AccountLink).oid();
        multi.addSelect(selAcc);
        multi.execute();
        final Map<String, AccountInfo> map = new HashMap<>();
        while (multi.next()) {
            final Instance accountInst = Instance.get(multi.<String>getSelect(selAcc));
            if (setAccounts.contains(accountInst.getOid())) {
                final BigDecimal oldRateAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.RateAmount);
                final BigDecimal oldAmount = multi
                        .<BigDecimal>getAttribute(CIAccounting.TransactionPositionAbstract.Amount);
                final Instance targetCurrInst = Instance.get(CIERP.Currency.getType(),
                        multi.<Long>getAttribute(CIAccounting.TransactionPositionAbstract.RateCurrencyLink));
                final Instance currentInst = Instance.get(CIERP.Currency.getType(),
                        multi.<Long>getAttribute(CIAccounting.TransactionPositionAbstract.CurrencyLink));

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

                BigDecimal gainloss = BigDecimal.ZERO;
                if (!currentInst.equals(targetCurrInst)) {
                    gainloss = newAmount.subtract(oldAmount);
                } else {
                    gainloss = newAmount;
                }
                if (map.containsKey(accountInst.getOid())) {
                    final AccountInfo tarAcc = map.get(accountInst.getOid());
                    tarAcc.addAmount(gainloss);
                } else {
                    final AccountInfo tarAcc = new AccountInfo(accountInst, gainloss);
                    tarAcc.setAmountRate(gainloss);
                    tarAcc.setCurrInstance(currentInst);
                    map.put(accountInst.getOid(), tarAcc);
                }
            }
        }

        if (!map.isEmpty()) {
            Insert insert = null;
            CurrencyInst curr = null;
            BigDecimal gainlossSum = BigDecimal.ZERO;
            for (final Entry<String, AccountInfo> entry : map.entrySet()) {
                final AccountInfo tarAcc = entry.getValue();
                final Instance instAcc = Instance.get(entry.getKey());
                final BigDecimal gainloss = tarAcc.getAmount();
                gainlossSum = gainlossSum.add(gainloss);
                final Instance currInstance = tarAcc.getCurrInstance();
                curr = new CurrencyInst(currInstance);
                final Map<String, String[]> mapVal = validateInfo(_parameter, gainloss);
                final String[] accs = mapVal.get("accs");
                final String[] check = mapVal.get("check");

                if (checkAccounts(accs, 0, check).length() > 0) {
                    if (gainloss.compareTo(BigDecimal.ZERO) != 0) {
                        final String[] accOids = mapVal.get("accountOids");
                        if (insert == null) {
                            final DateTimeFormatter formater = DateTimeFormat.mediumDate();
                            final String dateStr = dateTo
                                    .withChronology(Context.getThreadContext().getChronology())
                                    .toString(formater.withLocale(Context.getThreadContext().getLocale()));
                            final StringBuilder description = new StringBuilder();
                            description
                                    .append(DBProperties
                                            .getProperty("Accounting_DocumentAccountForm.TxnRecalculate.Label"))
                                    .append(" ").append(dateStr);
                            insert = new Insert(CIAccounting.Transaction);
                            insert.add(CIAccounting.Transaction.Description, description.toString());
                            insert.add(CIAccounting.Transaction.Date, dateTo);
                            insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId());
                            insert.add(CIAccounting.Transaction.Status,
                                    Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId());
                            insert.execute();
                        }

                        Insert insertPos = new Insert(CIAccounting.TransactionPositionCredit);
                        insertPos.add(CIAccounting.TransactionPositionCredit.TransactionLink, insert.getId());
                        if (gainloss.signum() < 0) {
                            insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink, instAcc.getId());
                        } else {
                            insertPos.add(CIAccounting.TransactionPositionCredit.AccountLink,
                                    Instance.get(accOids[0]).getId());
                        }
                        insertPos.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs());
                        insertPos.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs());
                        insertPos.add(CIAccounting.TransactionPositionCredit.CurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionCredit.Rate,
                                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                        insertPos.execute();

                        insertPos = new Insert(CIAccounting.TransactionPositionDebit);
                        insertPos.add(CIAccounting.TransactionPositionDebit.TransactionLink, insert.getId());
                        if (gainloss.signum() < 0) {
                            insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink,
                                    Instance.get(accOids[0]).getId());
                        } else {
                            insertPos.add(CIAccounting.TransactionPositionDebit.AccountLink, instAcc.getId());
                        }
                        insertPos.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate());
                        insertPos.add(CIAccounting.TransactionPositionDebit.RateAmount,
                                gainloss.abs().negate());
                        insertPos.add(CIAccounting.TransactionPositionDebit.CurrencyLink, currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink,
                                currInstance.getId());
                        insertPos.add(CIAccounting.TransactionPositionDebit.Rate,
                                new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                        insertPos.execute();
                    }
                }
            }
            if (insert != null) {
                final Instance instance = insert.getInstance();
                // create classifications
                final Classification classification1 = (Classification) CIAccounting.TransactionClass.getType();
                final Insert relInsert1 = new Insert(classification1.getClassifyRelationType());
                relInsert1.add(classification1.getRelLinkAttributeName(), instance.getId());
                relInsert1.add(classification1.getRelTypeAttributeName(), classification1.getId());
                relInsert1.execute();

                final Insert classInsert1 = new Insert(classification1);
                classInsert1.add(classification1.getLinkAttributeName(), instance.getId());
                classInsert1.execute();

                final Classification classification = (Classification) CIAccounting.TransactionClassGainLoss
                        .getType();
                final Insert relInsert = new Insert(classification.getClassifyRelationType());
                relInsert.add(classification.getRelLinkAttributeName(), instance.getId());
                relInsert.add(classification.getRelTypeAttributeName(), classification.getId());
                relInsert.execute();

                final Insert classInsert = new Insert(classification);
                classInsert.add(classification.getLinkAttributeName(), instance.getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.Amount, gainlossSum);
                classInsert.add(CIAccounting.TransactionClassGainLoss.RateAmount, gainlossSum);
                classInsert.add(CIAccounting.TransactionClassGainLoss.CurrencyLink, curr.getInstance().getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.RateCurrencyLink,
                        curr.getInstance().getId());
                classInsert.add(CIAccounting.TransactionClassGainLoss.Rate,
                        new Object[] { BigDecimal.ONE, BigDecimal.ONE });
                classInsert.execute();

                new Create().connectDocs2Transaction(_parameter, instance, instDoc);
            }
        }
    }

    return new Return();
}

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

private void addMarketingRelationUser(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole)
        throws Exception {
    double yxJGAmount = 0;
    BigDecimal bg = new BigDecimal(getDaysRuleRate(divsionRuleRole.getRule(), trade) * detail.getAmount());
    yxJGAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    yxJGAmount = Math.floor(yxJGAmount);

    UserBaseInfoDO curParentJjr = null;//  w  w w  .ja v a 2 s . c om
    if (curParentJjr == null) {
        try {
            curParentJjr = userBaseInfoManager.queryByUserName(detail.getUserName(),
                    SysUserRoleEnum.BROKER.getValue());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    if (curParentJjr == null) {
        Page<UserRelationDO> userRelationsPage = userRelationManager.getRelationsByConditions(null, null,
                detail.getUserId(), null);
        if (userRelationsPage.getResult() != null && userRelationsPage.getResult().size() > 0) {
            List<UserBaseInfoDO> curParentJjrs = userBaseInfoManager.queryByType(null,
                    String.valueOf(userRelationsPage.getResult().get(0).getParentId()));
            if (curParentJjrs != null && curParentJjrs.size() > 0) {
                if (UserTypeEnum.GR.code().equals(curParentJjrs.get(0).getType())) {
                    curParentJjr = curParentJjrs.get(0);
                }

            }
        }
    }
    if (curParentJjr != null) {
        //??
        UserBaseInfoDO curParentJG = null;
        int maxLength = 20;
        int index = 0;
        long curParentJjrUserId = curParentJjr.getUserId();
        while (curParentJG == null && index < maxLength) {
            index++;
            Page<UserRelationDO> userRelationsJGPage = userRelationManager.getRelationsByConditions(null, null,
                    curParentJjrUserId, null);
            if (userRelationsJGPage.getResult() != null && userRelationsJGPage.getResult().size() > 0) {
                long parentUserId = userRelationsJGPage.getResult().get(0).getParentId();
                UserBaseInfoDO parentUser = userBaseInfoManager.queryByUserId(parentUserId);
                if (parentUser != null) {
                    if (UserTypeEnum.JG.code().equals(parentUser.getType())) {
                        curParentJG = parentUser;
                        break;
                    } else {
                        curParentJjrUserId = parentUser.getUserId();
                    }
                }
            } else {
                break;
            }
        }
        if (curParentJG != null) {
            //?
            tradeDetailDao.addTradeDetail(new TradeDetail(curParentJG.getUserId(), trade.getId(),
                    (long) yxJGAmount, 10, divsionRuleRole.getPhase(), String.valueOf(detail.getId())));
        }

    }

    //      double yxJGAmount = 0;
    //      long tradeId = trade.getId();
    //      long detailId = detail.getId();
    //      BigDecimal bg = new BigDecimal(getDaysRuleRate(
    //            divsionRuleRole.getRule(), trade)
    //            * detail.getAmount());
    //      yxJGAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    //      yxJGAmount = Math.floor(yxJGAmount);
    //      // ??
    //      Page<UserRelationDO> userRelationsPage = userRelationManager
    //            .getRelationsByConditions(null, null, detail.getUserId(), null);
    //      if (userRelationsPage.getResult() != null
    //            && userRelationsPage.getResult().size() > 0) {
    //         List<UserBaseInfoDO> curParentJjrs = userBaseInfoManager
    //               .queryByType(
    //                     null,
    //                     String.valueOf(userRelationsPage.getResult().get(0)
    //                           .getParentId()));
    //         UserBaseInfoDO curParentJjr = null;
    //         if (curParentJjrs != null && curParentJjrs.size() > 0) {
    //            curParentJjr = curParentJjrs.get(0);
    //            // ??
    //            Page<UserRelationDO> userRelationsJGPage = userRelationManager
    //                  .getRelationsByConditions(null, null,
    //                        curParentJjr.getUserId(), null);
    //            if (userRelationsJGPage.getResult() != null
    //                  && userRelationsJGPage.getResult().size() > 0) {
    //               List<UserBaseInfoDO> curParentJGs = userBaseInfoManager
    //                     .queryByType(
    //                           UserTypeEnum.JG.code(),
    //                           String.valueOf(userRelationsJGPage
    //                                 .getResult().get(0).getParentId()));
    //               UserBaseInfoDO curParentJG = null;
    //               if (curParentJGs != null && curParentJGs.size() > 0) {
    //                  curParentJG = curParentJGs.get(0);
    //                  // ?
    //                  tradeDetailDao.addTradeDetail(new TradeDetail(
    //                        curParentJG.getUserId(), tradeId,
    //                        (long) yxJGAmount, 10, divsionRuleRole
    //                              .getPhase(), String.valueOf(detailId)));
    //               }
    //            }
    //         }
    //      }
}

From source file:com.osafe.services.OsafePayPalServices.java

public static Map<String, Object> doExpressCheckout(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));
    Locale locale = (Locale) context.get("locale");

    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {//from   w  w  w  . j  a va 2s.  co  m
        payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod");
        payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod");
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal subTotal = grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2,
            BigDecimal.ROUND_HALF_UP);
    encoder.add("ITEMAMT", subTotal.toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());

    NVPDecoder decoder = null;
    try {
        decoder = sendNVPRequest(payPalPaymentSetting, encoder);
    } catch (PayPalException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (decoder == null) {
        /*            return ServiceUtil.returnError(UtilProperties.getMessage(resource, 
            "AccountingPayPalUnknownError", locale));*/
        return ServiceUtil.returnError("An error occurred while communicating with PayPal");
    }

    Map<String, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
        if (errorMessages.containsKey("10417")) {
            // "The transaction cannot complete successfully,  Instruct the customer to use an alternative payment method"
            // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again
            boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
            if (retry) {
                context.put("_RETRY_", false);
                return OsafePayPalServices.doExpressCheckout(dctx, context);
            }
        }
        return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));

    Map<String, Object> outMap = null;
    try {
        outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
        Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
        return outMap;
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.kalypso.grid.GeoGridUtilities.java

/**
 * gets the min and max values for the given {@link ICoverageCollection}
 *//*from w w  w. j a va2  s .  c o  m*/
public static BigDecimal[] getMinMax(final ICoverageCollection covCollection) throws Exception {
    final BigDecimal[] minmax = new BigDecimal[2];

    BigDecimal minValue = new BigDecimal(Double.MAX_VALUE).setScale(4, BigDecimal.ROUND_HALF_UP);
    BigDecimal maxValue = new BigDecimal(-Double.MAX_VALUE).setScale(4, BigDecimal.ROUND_HALF_UP);

    final IFeatureBindingCollection<ICoverage> coverages = covCollection.getCoverages();
    for (final ICoverage coverage : coverages) {
        final IGeoGrid grid = GeoGridUtilities.toGrid(coverage);

        final BigDecimal min = grid.getMin();
        final BigDecimal max = grid.getMax();

        minValue = minValue.min(min);
        maxValue = maxValue.max(max);
    }

    minmax[0] = minValue;
    minmax[1] = maxValue;

    return minmax;
}