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:tasly.greathealth.oms.export.financial.facades.impl.DefaulTaslyFinancialReportFacade.java

private double getPriceByFreight(final double unitPrice, final double sumPrice, final double freight) {
    final BigDecimal unit = new BigDecimal(unitPrice);
    final BigDecimal sum = new BigDecimal(sumPrice);
    final BigDecimal fre = new BigDecimal(freight);

    return unit.divide(sum, 4, BigDecimal.ROUND_HALF_UP).multiply(fre).setScale(2, BigDecimal.ROUND_HALF_UP)
            .doubleValue();//from ww  w .  jav a 2 s .co  m
}

From source file:org.egov.infra.gis.service.GeoLocationService.java

private static BigDecimal getRangeSize(BigDecimal wardDataMinAmount, BigDecimal wardDataMaxAmount,
        int totalNoOfColors) {

    BigDecimal rangeSize = (wardDataMaxAmount.subtract(wardDataMinAmount))
            .divide(BigDecimal.valueOf(totalNoOfColors), BigDecimal.ROUND_HALF_UP);
    return rangeSize;
}

From source file:org.codice.ddf.spatial.ogc.wfs.catalog.converter.impl.AbstractFeatureConverter.java

private String convertToBytes(HierarchicalStreamReader reader, String unit) {

    BigDecimal resourceSize = new BigDecimal(reader.getValue());
    resourceSize = resourceSize.setScale(1, BigDecimal.ROUND_HALF_UP);

    switch (unit) {
    case B:/*from w ww .j a  v a  2 s.c o  m*/
        break;
    case KB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_KB));
        break;
    case MB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_MB));
        break;
    case GB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_GB));
        break;
    case TB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_TB));
        break;
    case PB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_PB));
        break;
    default:
        break;
    }

    String resourceSizeAsString = resourceSize.toPlainString();
    LOGGER.debug("resource size in bytes: {}", resourceSizeAsString);
    return resourceSizeAsString;
}

From source file:com.delmar.station.web.action.WFDetailAction.java

/**
 * ?/*from   w w  w.  ja v  a  2 s .  co m*/
 * @return
 */
public String initDetail() {

    //?
    if (id != null && id > 0) {
        wfDetail = wfDetailService.getWFDetailById(id);
        if (wfDetail != null) {
            warehouseForwarder = warehouseForwarderService.selectByPrimaryKey(wfDetail.getMasterID());
        }

        init();

        //
    } else {
        warehouseForwarder = warehouseForwarderService.getWareHouseForwarderByNo(warehouseNo);
        lastWFDetail = null;
        List<String> referenceNoList = null;
        wfDetail = new WFDetail();
        if (warehouseForwarder != null) {
            WFReality wfReality = wfRealityService.getWFRealityByMasterId(warehouseForwarder.getId());
            if (wfReality != null) {
                int totalGoodsNumber = 0;
                double totalGoodsWeight = 0;
                double totalGoodsSize = 0;

                if (warehouseForwarder.getGoodsNumber() - wfReality.getGoodsNumber() > 0) {
                    totalGoodsNumber = warehouseForwarder.getGoodsNumber() - wfReality.getGoodsNumber();
                }

                if (warehouseForwarder.getGoodsWeight() - wfReality.getGoodsWeight() > 0) {
                    totalGoodsWeight = warehouseForwarder.getGoodsWeight() - wfReality.getGoodsWeight();
                }

                if (warehouseForwarder.getGoodsSize() - wfReality.getGoodsSize() > 0) {
                    totalGoodsSize = warehouseForwarder.getGoodsSize() - wfReality.getGoodsSize();
                }

                //??
                BigDecimal goodsWeight = new BigDecimal(totalGoodsWeight);
                BigDecimal goodsSize = new BigDecimal(totalGoodsSize);
                wfDetail.setGoodsNumber(totalGoodsNumber);
                wfDetail.setGoodsWeight(goodsWeight.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                wfDetail.setGoodsSize(goodsSize.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());

            } else {

                //??
                BigDecimal goodsWeight = new BigDecimal(warehouseForwarder.getGoodsWeight());
                BigDecimal goodsSize = new BigDecimal(warehouseForwarder.getGoodsSize());
                wfDetail.setGoodsNumber(warehouseForwarder.getGoodsNumber());
                wfDetail.setGoodsWeight(goodsWeight.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
                wfDetail.setGoodsSize(goodsSize.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
            }

            wfDetail.setGoodsDesc(warehouseForwarder.getGoodsDesc());
            wfDetail.setMaiTou(warehouseForwarder.getMaiTou());
            wfDetail.setChargeData(warehouseForwarder.getChargeData());
            wfDetail.setMasterID(warehouseForwarder.getId());
            wfDetail.setTrustFileCode(warehouseForwarder.getTrustFileCode());
            wfDetail.setCompanyID(warehouseForwarder.getCompanyID());

            if (warehouseForwarder.getToWarehouse().equals(getCurrentUserThird(CARGO_PRO_WAREHOUSE))) {
                List<WFDetail> list = wfDetailService.getWFDetailByMasterId(warehouseForwarder.getId());

                //sqlorder by inDate desc ?
                if (list != null && list.size() > 0) {
                    lastWFDetail = list.get(0);
                }

                if (StringUtils.isNotEmpty(warehouseForwarder.getReferenceNo())) {
                    String referenceNo = warehouseForwarder.getReferenceNo();

                    String[] tempRreferenceNo = referenceNo.split(";");
                    referenceNoList = new ArrayList<String>();
                    for (int i = 0; i < tempRreferenceNo.length; i++) {
                        referenceNoList.add(tempRreferenceNo[i]);
                    }
                }
            }

            //???????
            wfDetail.setInDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            if (referenceNoList != null && lastWFDetail != null) {
                wfDetail.setCarDriver(lastWFDetail.getCarDriver());
                wfDetail.setCarLicenseNo(lastWFDetail.getCarLicenseNo());
            }

            if (lastWFDetail != null) {

                wfDetail.setReceiptPerson(lastWFDetail.getReceiptPerson());
                wfDetail.setShippingSpace(lastWFDetail.getShippingSpace());
            }

            UserResource ur = (UserResource) ServletActionContext.getRequest().getSession()
                    .getAttribute("resource");
            packageList = datadictService.getDatadictTrlByValue(DatadictType.PACKAGELIST,
                    ur.getLocale().toString());
            FacesUtils.setValueInHashtableOfSession("packageList", packageList);
        }
    }

    return "initDetail";
}

From source file:net.certiv.authmgr.task.section.core.classifier.BayesPartitionClassifier.java

/**
 * Implementation of a partial probability Bayes classifier. Determines the
 * conditional probability for the given word set in each of the partitions that exist
 * in the given category. Assumes that the word set is a match to one of the
 * partitions. Also assumes word term independence per standard naive Bayes.
 * // w  ww . ja  va 2s .c om
 * @param category the category to check
 * @param words the word set to match to a partition
 * @return the label of the partition with the highest partial probability for the
 *         given set of words
 * @author Gbr
 */
protected String classify(String category, String words[]) throws WordsDataSourceException {

    PartitionProbabilities results = new PartitionProbabilities(category);
    String[] publicPartitions = wordsData.getPartitionList(category, SPACE_TOTALS);
    if (publicPartitions != null) {
        for (int i = 0; i < publicPartitions.length; i++) {
            String partition = publicPartitions[i];
            if (debug)
                Log.debug(this, "classify() - Partition: " + partition);
            double score = calculatePartialProbability(category, partition, words);
            BigDecimal scoreBD = new BigDecimal(score).setScale(16, BigDecimal.ROUND_HALF_UP);
            if (debug)
                Log.debug(this, Util.leftAlign(partition + ":", 14) + scoreBD);
            results.setScore(partition, score); // normaliseSignificance(score));
        }
    }
    return results.maxScorePartition();
}

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

/**
 * Returns total demand from WaterCharge index, based on input filters
 *
 * @param waterChargedashBoardRequest/*from ww  w.j av  a 2 s  . co  m*/
 * @return
 */
public BigDecimal getTotalDemandBasedOnInputFilters(
        final WaterChargeDashBoardRequest waterChargedashBoardRequest) {
    final BoolQueryBuilder boolQuery = waterChargeCollDocService.prepareWhereClause(waterChargedashBoardRequest,
            null);
    final SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(WATER_TAX_INDEX_NAME)
            .withQuery(boolQuery)
            .addAggregation(AggregationBuilders.sum(WaterTaxConstants.WATERCHARGETOTALDEMAND)
                    .field(WaterTaxConstants.WATERCHARGETOTALDEMAND))
            .build();

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

    final Sum aggr = collAggr.get(WaterTaxConstants.WATERCHARGETOTALDEMAND);
    return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:com.konakart.bl.modules.payment.cyberpac.Cyberpac.java

/**
 * Return a payment details object for Cyberpac
 * //ww  w  .  j  av  a 2 s . co  m
 * @param order
 * @param info
 * @return Returns information in a PaymentDetails object
 * @throws Exception
 */
public PaymentDetails getPaymentDetails(Order order, PaymentInfo info) throws Exception {
    StaticData sd = staticDataHM.get(getStoreId());
    /*
     * The CyberpacZone zone, if greater than zero, should reference a GeoZone. If the
     * DeliveryAddress of the order isn't within that GeoZone, then we throw an exception
     */
    if (sd.getZone() > 0) {
        checkZone(info, sd.getZone());
    }

    // Get the scale for currency calculations
    int scale = new Integer(order.getCurrency().getDecimalPlaces()).intValue();

    // Get the resource bundle
    ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, info.getLocale());
    if (rb == null) {
        throw new KKException(
                "A resource file cannot be found for the country " + info.getLocale().getCountry());
    }

    PaymentDetails pDetails = new PaymentDetails();
    pDetails.setCode(code);
    pDetails.setSortOrder(sd.getSortOrder());
    pDetails.setPaymentType(PaymentDetails.BROWSER_PAYMENT_GATEWAY);
    pDetails.setDescription(rb.getString(MODULE_PAYMENT_CYBERPAC_TEXT_DESCRIPTION));
    pDetails.setTitle(rb.getString(MODULE_PAYMENT_CYBERPAC_TEXT_TITLE));

    // Return now if the full payment details aren't required. This happens when the manager
    // just wants a list of payment gateways to display in the UI.
    if (info.isReturnDetails() == false) {
        return pDetails;
    }

    pDetails.setPostOrGet("post");
    pDetails.setRequestUrl(sd.getRequestUrl());

    List<NameValue> parmList = new ArrayList<NameValue>();

    /*
     * Parameters posted to gateway
     */

    // Total
    BigDecimal total = null;
    for (int i = 0; i < order.getOrderTotals().length; i++) {
        OrderTotal ot = (OrderTotal) order.getOrderTotals()[i];
        if (ot.getClassName().equals(OrderTotalMgr.ot_total)) {
            total = ot.getValue().setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
    }
    if (total == null) {
        throw new KKException("An Order Total was not found in the order id = " + order.getId());
    }
    parmList.add(new NameValue("Ds_Merchant_Amount", total.toString()));

    // Currency
    String currCode = null;
    if (order.getCurrency().getCode().equalsIgnoreCase("EUR")) {
        currCode = "978";
    } else if (order.getCurrency().getCode().equalsIgnoreCase("USD")) {
        currCode = "840";
    } else if (order.getCurrency().getCode().equalsIgnoreCase("GBP")) {
        currCode = "826";
    } else if (order.getCurrency().getCode().equalsIgnoreCase("JPY")) {
        currCode = "392";
    } else {
        throw new KKException("The currency with code = " + order.getCurrency().getCode()
                + " is not supported by the Cyberpac payment gateway.");
    }
    String ds_Merchant_Currency = currCode;
    parmList.add(new NameValue("Ds_Merchant_Currency", ds_Merchant_Currency));

    // Various
    String ds_Merchant_Order = Integer.toString(order.getId());
    parmList.add(new NameValue("Ds_Merchant_Order", ds_Merchant_Order));
    parmList.add(new NameValue("Ds_Merchant_ProductDescription",
            rb.getString(MODULE_PAYMENT_CYBERPAC_CUSTOMER_MSG) + " " + order.getId()));
    parmList.add(new NameValue("Ds_Merchant_Cardholder", order.getBillingName()));
    String ds_Merchant_MerchantCode = sd.getMerchantCode();
    parmList.add(new NameValue("Ds_Merchant_MerchantCode", ds_Merchant_MerchantCode));
    parmList.add(new NameValue("Ds_Merchant_MerchantURL", sd.getCallbackUrl()));
    if (sd.getRedirectKOUrl() != null && sd.getRedirectKOUrl().length() > 0) {
        parmList.add(new NameValue("Ds_Merchant_UrlKO", sd.getRedirectKOUrl()));
    }
    if (sd.getRedirectOKUrl() != null && sd.getRedirectOKUrl().length() > 0) {
        parmList.add(new NameValue("Ds_Merchant_UrlOK", sd.getRedirectOKUrl()));
    }

    String lang = "001"; // Default Spanish Castellano
    String langCode = order.getLocale().substring(0, 2);
    if (order.getLocale().equalsIgnoreCase("ca_ES")) {
        lang = "003";
    } else if (langCode.equalsIgnoreCase("en")) {
        lang = "002";
    } else if (langCode.equalsIgnoreCase("fr")) {
        lang = "004";
    } else if (langCode.equalsIgnoreCase("de")) {
        lang = "005";
    } else if (langCode.equalsIgnoreCase("it")) {
        lang = "007";
    } else if (langCode.equalsIgnoreCase("pt")) {
        lang = "009";
    } else if (order.getLocale().equalsIgnoreCase("eu_ES")) {
        lang = "013";
    } else if (langCode.equalsIgnoreCase("ru")) {
        lang = "014";
    }
    parmList.add(new NameValue("Ds_Merchant_ConsumerLanguage", lang));

    parmList.add(new NameValue("Ds_Merchant_Terminal", sd.getTerminalNumber()));

    if (sd.getTransactionType() != null && sd.getTransactionType().length() > 0) {
        parmList.add(new NameValue("Ds_Merchant_TransactionType", sd.getTransactionType()));
    } else {
        parmList.add(new NameValue("Ds_Merchant_TransactionType", "2"));
    }

    // Data passed to us in callback. Need to create a session
    SSOTokenIf ssoToken = new SSOToken();
    String sessionId = getEng().login(sd.getCallbackUsername(), sd.getCallbackPassword());
    if (sessionId == null) {
        throw new KKException(
                "Unable to log into the engine using the Cyberpac Callback Username and Password");
    }
    ssoToken.setSessionId(sessionId);
    ssoToken.setCustom1(String.valueOf(order.getId()));
    // Save the SSOToken with a valid sessionId and the order id in custom1
    String uuid = getEng().saveSSOToken(ssoToken);
    parmList.add(new NameValue("Ds_Merchant_MerchantData", uuid));

    // Sign the data
    // Digest=SHA-1(Ds_Merchant_Amount + Ds_Merchant_Order +Ds_Merchant_MerchantCode
    // + DS_Merchant_Currency + SECRET CODE)
    String ds_Merchant_Amount = (total.multiply(new BigDecimal(100))).toString();
    String stringToSign = ds_Merchant_Amount + ds_Merchant_Order + ds_Merchant_MerchantCode
            + ds_Merchant_Currency + sd.getSecretSigningCode();
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] digest = md.digest(stringToSign.getBytes("UTF8"));
    String hexEncodedDigest = (Hex.encodeHex(digest)).toString();
    parmList.add(new NameValue("Ds_Merchant_MerchantSignature", hexEncodedDigest));
    if (log.isDebugEnabled()) {
        StringBuffer str = new StringBuffer();
        str.append("Parameters to sign:").append("\n");
        str.append("Ds_Merchant_Amount        = ").append(ds_Merchant_Amount).append("\n");
        str.append("Ds_Merchant_Order         = ").append(ds_Merchant_Order).append("\n");
        str.append("Ds_Merchant_MerchantCode  = ").append(ds_Merchant_MerchantCode).append("\n");
        str.append("Ds_Merchant_Currency      = ").append(ds_Merchant_Currency).append("\n");
        str.append("Secret Code               = ").append(sd.getSecretSigningCode()).append("\n");
        str.append("String to sign            = ").append(stringToSign).append("\n");
        str.append("SHA-1 result              = ").append(hexEncodedDigest).append("\n");
        log.debug(str);
    }

    // Put the parameters into an array
    NameValue[] nvArray = new NameValue[parmList.size()];
    parmList.toArray(nvArray);
    pDetails.setParameters(nvArray);

    if (log.isDebugEnabled()) {
        log.debug(pDetails.toString());
    }

    return pDetails;
}

From source file:org.egov.services.recoveries.RecoveryService.java

public BigDecimal getDeductionAmount(final String recoveryCode, final String partyType,
        final String subPartyType, final String docType, final BigDecimal grossAmount, final Date asOnDate)
        throws Exception {

    final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy", Constants.LOCALE);
    BigDecimal incomeTax = new BigDecimal(0);
    BigDecimal surcharge = new BigDecimal(0);
    BigDecimal education = new BigDecimal(0);
    BigDecimal total = new BigDecimal(0);
    BigDecimal deductionAmt = new BigDecimal(0);
    EgDeductionDetails egDeductionDetails = null;

    if (null == recoveryCode || recoveryCode.trim().equals("")) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Recovery Code is missing");
        throw new ValidationException(EMPTY, "Recovery Code is missing");
    }/*from   w  ww.j  a  va2s . c  om*/

    if (null == partyType || partyType.trim().equals("")) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Party Type is missing");
        throw new ValidationException(EMPTY, "Party Type is missing");
    }

    if (null == grossAmount) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Gross Amount is missing");
        throw new ValidationException(EMPTY, "Gross Amount is missing");
    }

    if (null == asOnDate) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("AsOnDate is missing");
        throw new ValidationException(EMPTY, "AsOnDate is missing");
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("getDeductionAmount() -> recoveryCode :" + recoveryCode + " | partyType :" + partyType
                + " | grossAmount :" + grossAmount + " | asOnDate :" + dateFormatter.format(asOnDate)
                + " | docType :" + docType);

    EgwTypeOfWork egwTypeOfWork = null;
    EgPartytype egSubPartytype = null;

    final EgPartytype egPartytype = getPartytypeByCode(partyType);
    final Recovery recovery = getTdsByTypeAndPartyType(recoveryCode, egPartytype);

    if (recovery == null)
        throw new ValidationException(EMPTY,
                "Recovery with " + recoveryCode + " code  and " + egPartytype + " party type is invalid.");
    if (recovery.getRecoveryMode() == 'M')
        return BigDecimal.valueOf(-1);

    if (null != docType)
        egwTypeOfWork = getTypeOfWorkByCode(docType);

    if (null != subPartyType)
        egSubPartytype = getSubPartytypeByCode(subPartyType);

    try {
        egDeductionDetails = egDeductionDetHibernateDao.findEgDeductionDetailsForDeduAmt(recovery, egPartytype,
                egSubPartytype, egwTypeOfWork, asOnDate);
    } catch (final Exception e) {
        LOGGER.error("Exception in egDeductionDetails fetching :" + e);
        throw new ValidationException(EMPTY, "Error while fetching the date for this " + recoveryCode
                + " code for this " + dateFormatter.format(asOnDate) + " date. " + e.getMessage());
    }

    if (null == egDeductionDetails)
        throw new ValidationException(EMPTY, "There is no data for this " + recoveryCode + " code for this "
                + dateFormatter.format(asOnDate) + " date.");

    if (null != recovery.getCalculationType() && recovery.getCalculationType().equalsIgnoreCase("flat")) {
        if (null != egDeductionDetails.getFlatAmount())
            deductionAmt = egDeductionDetails.getFlatAmount();
    } else {
        if (null != egDeductionDetails.getIncometax())
            incomeTax = egDeductionDetails.getIncometax();
        if (null != egDeductionDetails.getSurcharge())
            surcharge = egDeductionDetails.getSurcharge();
        if (null != egDeductionDetails.getEducation())
            education = egDeductionDetails.getEducation();
        total = incomeTax.add(surcharge).add(education);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("total IT/SC/EC " + total);
        deductionAmt = grossAmount.multiply(total.divide(new BigDecimal(100)));
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("deductionAmt :" + deductionAmt);
    return deductionAmt = deductionAmt.setScale(2, BigDecimal.ROUND_HALF_UP);
}

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

public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");

    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);

    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;//from  w ww  . ja va2 s  .  c  o  m
    if (weakCart != null) {
        cart = weakCart.get();
    }
    if (cart == null) {
        Debug.logError("Could locate the ShoppingCart for token " + token, module);
        return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = new HashMap<String, Object>();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
        return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put("stateProvinceGeoId",
            parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));

    try {
        GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system")
                .cache().queryOne();
        inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
        parentTransaction = TransactionUtil.suspend();
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, module);
    }
    try {
        Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
        contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
        Debug.logError(e.getMessage(), module);
        return ServiceUtil.returnSuccess();
    }
    try {
        TransactionUtil.commit(beganTransaction);
        if (parentTransaction != null)
            TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");

    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
        BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
        //Check that we have a valid estimate (allowing zero value estimates for now)
        if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
            continue;
        }
        cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
        cart.setAllCarrierPartyId(shipMethod.getString("partyId"));
        try {
            coh.calcAndAddTax();
        } catch (GeneralException e) {
            Debug.logError(e, module);
            continue;
        }
        String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
        encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
        encoder.add("L_SHIPPINGOPTIONAMOUNT" + line,
                estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        // Just make this first one default for now
        encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
        encoder.add("L_TAXAMT" + line,
                cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        line++;
    }
    String responseMsg = null;
    try {
        responseMsg = encoder.encode();
    } catch (PayPalException e) {
        Debug.logError(e, module);
    }
    if (responseMsg != null) {
        try {
            response.setContentLength(responseMsg.getBytes("UTF-8").length);
        } catch (UnsupportedEncodingException e) {
            Debug.logError(e, module);
        }

        try {
            Writer writer = response.getWriter();
            writer.write(responseMsg);
            writer.close();
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }

    // Remove the temporary ship address
    try {
        GenericValue postalAddress = EntityQuery.use(delegator).from("PostalAddress")
                .where("contactMechId", contactMechId).queryOne();
        postalAddress.remove();
        GenericValue contactMech = EntityQuery.use(delegator).from("ContactMech")
                .where("contactMechId", contactMechId).queryOne();
        contactMech.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
}

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

/**
 * Method to recalculate rate./* w w w . ja  v a 2  s.c  o  m*/
 *
 * @param _parameter Parameter as passed from the eFaps API.
 * @return new Return.
 * @throws EFapsException on error.
 */
public Return recalculateRate(final Parameter _parameter) throws EFapsException {
    final Instance docInst = Instance.get(_parameter.getParameterValue("docInst"));
    final PrintQuery print = new PrintQuery(docInst);
    print.addAttribute(CISales.DocumentSumAbstract.RateCrossTotal, CISales.DocumentSumAbstract.CrossTotal,
            CISales.DocumentSumAbstract.RateCurrencyId, CISales.DocumentSumAbstract.CurrencyId,
            CISales.DocumentSumAbstract.Date, CISales.DocumentSumAbstract.Name);
    print.execute();

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

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

    final BigDecimal newCrossTotal = rateCross.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO
            : rateCross.divide(rate, BigDecimal.ROUND_HALF_UP);
    final BigDecimal gainloss = newCrossTotal.subtract(crossTotal);
    final Map<String, String[]> map = validateInfo(_parameter, gainloss);
    final String[] accs = map.get("accs");
    final String[] check = map.get("check");
    if (checkAccounts(accs, 0, check).length() > 0 && checkAccounts(accs, 1, check).length() > 0) {
        if (gainloss.compareTo(BigDecimal.ZERO) != 0) {
            if (!tarCurr.equals(curr)) {
                final String[] accOids = map.get("accountOids");

                final Insert insert = new Insert(CIAccounting.Transaction);
                final StringBuilder description = new StringBuilder();
                final DateTimeFormatter formater = DateTimeFormat.mediumDate();
                final String dateStr = dateDoc.withChronology(Context.getThreadContext().getChronology())
                        .toString(formater.withLocale(Context.getThreadContext().getLocale()));
                description
                        .append(DBProperties
                                .getProperty("Accounting_TransactionRecalculateForm.TxnRecalculate.Label"))
                        .append(" ").append(nameDoc).append(" ").append(dateStr);
                insert.add(CIAccounting.Transaction.Description, description);
                insert.add(CIAccounting.Transaction.Date, _parameter.getParameterValue("date"));
                insert.add(CIAccounting.Transaction.PeriodLink, _parameter.getInstance().getId());
                insert.add(CIAccounting.Transaction.Status,
                        Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId());
                insert.execute();

                final Instance instance = insert.getInstance();
                new Create().connectDocs2Transaction(_parameter, instance, docInst);

                final Insert insert2 = new Insert(CIAccounting.TransactionPositionCredit);
                insert2.add(CIAccounting.TransactionPositionCredit.TransactionLink, instance.getId());
                insert2.add(CIAccounting.TransactionPositionCredit.AccountLink,
                        Instance.get(accOids[1]).getId());
                insert2.add(CIAccounting.TransactionPositionCredit.CurrencyLink, curr.getInstance().getId());
                insert2.add(CIAccounting.TransactionPositionCredit.RateCurrencyLink,
                        curr.getInstance().getId());
                insert2.add(CIAccounting.TransactionPositionCredit.Rate, new Object[] { 1, 1 });
                insert2.add(CIAccounting.TransactionPositionCredit.RateAmount, gainloss.abs());
                insert2.add(CIAccounting.TransactionPositionCredit.Amount, gainloss.abs());
                insert2.execute();

                final Insert insert3 = new Insert(CIAccounting.TransactionPositionDebit);
                insert3.add(CIAccounting.TransactionPositionDebit.TransactionLink, instance.getId());
                insert3.add(CIAccounting.TransactionPositionDebit.AccountLink,
                        Instance.get(accOids[0]).getId());
                insert3.add(CIAccounting.TransactionPositionDebit.CurrencyLink, curr.getInstance().getId());
                insert3.add(CIAccounting.TransactionPositionDebit.RateCurrencyLink, curr.getInstance().getId());
                insert3.add(CIAccounting.TransactionPositionDebit.Rate, new Object[] { 1, 1 });
                insert3.add(CIAccounting.TransactionPositionDebit.RateAmount, gainloss.abs().negate());
                insert3.add(CIAccounting.TransactionPositionDebit.Amount, gainloss.abs().negate());
                insert3.execute();

                _parameter.put(ParameterValues.INSTANCE, docInst);
                new Accounting4DocSum().recalculateRate(_parameter);
            }
        }
    }
    return new Return();
}