Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

From source file:org.kuali.kfs.module.ar.service.impl.ContractsGrantsInvoiceCreateDocumentServiceImpl.java

/**
 * Given a Map of category keys mapping percentage values and an amount, find what amount each percentage would be
 * @param percentagesByCategory a map of category code keys mapping percentage values
 * @param amount the amount to split by percentages
 * @return a Map of amounts keyed by category codes
 *//*from w  ww.ja va 2  s  .  c  om*/
protected Map<String, KualiDecimal> calculateAmountsByCategory(Map<String, BigDecimal> percentagesByCategory,
        KualiDecimal amount) {
    final BigDecimal bigDecimalAmount = amount.bigDecimalValue().setScale(2, RoundingMode.HALF_UP);
    Map<String, KualiDecimal> amountsByCategory = new HashMap<>();
    for (String categoryCode : percentagesByCategory.keySet()) {
        amountsByCategory.put(categoryCode,
                new KualiDecimal(bigDecimalAmount.multiply(percentagesByCategory.get(categoryCode))));
    }
    return amountsByCategory;
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

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

    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator,
            shipmentId, locale);// w  w  w .  j  ava  2s.  co m
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsGatewayNotAvailable", locale));
    }

    try {
        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment")
                .where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "ProductShipmentRouteSegmentNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // ensure the carrier is USPS
        if (!"USPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNotRouteSegmentCarrier",
                    UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId),
                    locale));
        }

        // get the origin address
        GenericValue originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentOriginPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(originAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        String originZip = originAddress.getString("postalCode");
        if (UtilValidate.isEmpty(originZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginZipCodeMissing",
                    UtilMisc.toMap("contactMechId", originAddress.getString("contactMechId")), locale));
        }

        // get the destination address
        GenericValue destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentDestPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(destinationAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        String destinationZip = destinationAddress.getString("postalCode");
        if (UtilValidate.isEmpty(destinationZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentDestinationZipCodeMissing",
                    UtilMisc.toMap("contactMechId", destinationAddress.getString("contactMechId")), locale));
        }

        // get the service type from the CarrierShipmentMethod
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String partyId = shipmentRouteSegment.getString("carrierPartyId");

        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("partyId", partyId, "roleTypeId", "CARRIER", "shipmentMethodTypeId",
                        shipmentMethodTypeId)
                .queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierShipmentMethod",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }
        String serviceType = carrierShipmentMethod.getString("carrierServiceCode");
        if (UtilValidate.isEmpty(serviceType)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierServiceCodeFound",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }

        // get the packages for this shipment route segment
        List<GenericValue> shipmentPackageRouteSegList = shipmentRouteSegment
                .getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegList)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentPackageRouteSegsNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        BigDecimal actualTransportCost = BigDecimal.ZERO;

        String carrierDeliveryZone = null;
        String carrierRestrictionCodes = null;
        String carrierRestrictionDesc = null;

        // send a new request for each package
        for (Iterator<GenericValue> i = shipmentPackageRouteSegList.iterator(); i.hasNext();) {

            GenericValue shipmentPackageRouteSeg = i.next();
            Document requestDocument = createUspsRequestDocument("RateRequest", true, delegator,
                    shipmentGatewayConfigId, resource);

            Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                    requestDocument);
            packageElement.setAttribute("ID", "0");

            UtilXml.addChildElementValue(packageElement, "Service", serviceType, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipOrigination", originZip, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipDestination", destinationZip, requestDocument);

            GenericValue shipmentPackage = null;
            shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);

            // weight elements - Pounds, Ounces
            String weightStr = shipmentPackage.getString("weight");
            if (UtilValidate.isEmpty(weightStr)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsWeightNotFound",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")),
                        locale));
            }

            BigDecimal weight = BigDecimal.ZERO;
            try {
                weight = new BigDecimal(weightStr);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }

            String weightUomId = shipmentPackage.getString("weightUomId");
            if (UtilValidate.isEmpty(weightUomId)) {
                weightUomId = "WT_lb"; // assume weight is in pounds
            }
            if (!"WT_lb".equals(weightUomId)) {
                // attempt a conversion to pounds
                Map<String, Object> result = new HashMap<String, Object>();
                try {
                    result = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId",
                            weightUomId, "uomIdTo", "WT_lb", "originalValue", weight));
                } catch (GenericServiceException ex) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightConversionError",
                            UtilMisc.toMap("errorString", ex.getMessage()), locale));
                }

                if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)
                        && result.get("convertedValue") != null) {
                    weight = weight.multiply((BigDecimal) result.get("convertedValue"));
                } else {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightUnsupported",
                            UtilMisc.toMap("weightUomId", weightUomId, "shipmentId",
                                    shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId",
                                    shipmentPackage.getString("shipmentPackageSeqId"), "weightUom", "WT_lb"),
                            locale));
                }

            }

            BigDecimal weightPounds = weight.setScale(0, BigDecimal.ROUND_FLOOR);
            BigDecimal weightOunces = weight.multiply(new BigDecimal("16")).remainder(new BigDecimal("16"))
                    .setScale(0, BigDecimal.ROUND_CEILING);

            DecimalFormat df = new DecimalFormat("#");
            UtilXml.addChildElementValue(packageElement, "Pounds", df.format(weightPounds), requestDocument);
            UtilXml.addChildElementValue(packageElement, "Ounces", df.format(weightOunces), requestDocument);

            // Container element
            GenericValue carrierShipmentBoxType = null;
            List<GenericValue> carrierShipmentBoxTypes = null;
            carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType",
                    UtilMisc.toMap("partyId", "USPS"), null, false);

            if (carrierShipmentBoxTypes.size() > 0) {
                carrierShipmentBoxType = carrierShipmentBoxTypes.get(0);
            }

            if (carrierShipmentBoxType != null
                    && UtilValidate.isNotEmpty(carrierShipmentBoxType.getString("packagingTypeCode"))) {
                UtilXml.addChildElementValue(packageElement, "Container",
                        carrierShipmentBoxType.getString("packagingTypeCode"), requestDocument);
            } else {
                // default to "None", for customers using their own package
                UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
            }

            // Size element
            if (carrierShipmentBoxType != null && UtilValidate.isNotEmpty("oversizeCode")) {
                UtilXml.addChildElementValue(packageElement, "Size",
                        carrierShipmentBoxType.getString("oversizeCode"), requestDocument);
            } else {
                // default to "Regular", length + girth measurement <= 84 inches
                UtilXml.addChildElementValue(packageElement, "Size", "Regular", requestDocument);
            }

            // Although only applicable for Parcel Post, this tag is required for all requests
            UtilXml.addChildElementValue(packageElement, "Machinable", "False", requestDocument);

            Document responseDocument = null;
            try {
                responseDocument = sendUspsRequest("Rate", requestDocument, delegator, shipmentGatewayConfigId,
                        resource, locale);
            } catch (UspsRequestException e) {
                Debug.logInfo(e, module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError",
                                UtilMisc.toMap("errorString", e.getMessage()), locale));
            }

            Element respPackageElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(),
                    "Package");
            if (respPackageElement == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateDomesticResponseIncompleteElementPackage", locale));
            }

            Element respErrorElement = UtilXml.firstChildElement(respPackageElement, "Error");
            if (respErrorElement != null) {
                return ServiceUtil
                        .returnError(UtilProperties
                                .getMessage(resourceError, "FacilityShipmentUspsRateDomesticResponseError",
                                        UtilMisc.toMap("errorString",
                                                UtilXml.childElementValue(respErrorElement, "Description")),
                                        locale));
            }

            // update the ShipmentPackageRouteSeg
            String postageString = UtilXml.childElementValue(respPackageElement, "Postage");
            if (UtilValidate.isEmpty(postageString)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateDomesticResponseIncompleteElementPostage", locale));
            }

            BigDecimal postage = BigDecimal.ZERO;
            try {
                postage = new BigDecimal(postageString);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }
            actualTransportCost = actualTransportCost.add(postage);

            shipmentPackageRouteSeg.setString("packageTransportCost", postageString);
            shipmentPackageRouteSeg.store();

            // if this is the last package, get the zone and APO/FPO restrictions for the ShipmentRouteSegment
            if (!i.hasNext()) {
                carrierDeliveryZone = UtilXml.childElementValue(respPackageElement, "Zone");
                carrierRestrictionCodes = UtilXml.childElementValue(respPackageElement, "RestrictionCodes");
                carrierRestrictionDesc = UtilXml.childElementValue(respPackageElement,
                        "RestrictionDescription");
            }
        }

        // update the ShipmentRouteSegment
        shipmentRouteSegment.set("carrierDeliveryZone", carrierDeliveryZone);
        shipmentRouteSegment.set("carrierRestrictionCodes", carrierRestrictionCodes);
        shipmentRouteSegment.set("carrierRestrictionDesc", carrierRestrictionDesc);
        shipmentRouteSegment.setString("actualTransportCost", String.valueOf(actualTransportCost));
        shipmentRouteSegment.store();

    } catch (GenericEntityException gee) {
        Debug.logInfo(gee, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticReadingError",
                        UtilMisc.toMap("errorString", gee.getMessage()), locale));
    }

    return ServiceUtil.returnSuccess();
}

From source file:org.ofbiz.shipment.thirdparty.usps.UspsServices.java

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

    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator,
            shipmentId, locale);/*from   ww  w .j  a va 2 s .  c o  m*/
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsGatewayNotAvailable", locale));
    }

    try {
        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment")
                .where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "ProductShipmentRouteSegmentNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // ensure the carrier is USPS
        if (!"USPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNotRouteSegmentCarrier",
                    UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId),
                    locale));
        }

        // get the origin address
        GenericValue originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentOriginPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(originAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        String originZip = originAddress.getString("postalCode");
        if (UtilValidate.isEmpty(originZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginZipCodeMissing",
                    UtilMisc.toMap("contactMechId", originAddress.getString("contactMechId")), locale));
        }

        // get the destination address
        GenericValue destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentDestPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(destinationAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        String destinationZip = destinationAddress.getString("postalCode");
        if (UtilValidate.isEmpty(destinationZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentDestinationZipCodeMissing",
                    UtilMisc.toMap("contactMechId", destinationAddress.getString("contactMechId")), locale));
        }

        // get the service type from the CarrierShipmentMethod
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String partyId = shipmentRouteSegment.getString("carrierPartyId");

        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("partyId", partyId, "roleTypeId", "CARRIER", "shipmentMethodTypeId",
                        shipmentMethodTypeId)
                .queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierShipmentMethod",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }
        String serviceType = carrierShipmentMethod.getString("carrierServiceCode");
        if (UtilValidate.isEmpty(serviceType)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierServiceCodeFound",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }

        // get the packages for this shipment route segment
        List<GenericValue> shipmentPackageRouteSegList = shipmentRouteSegment
                .getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegList)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentPackageRouteSegsNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        BigDecimal actualTransportCost = BigDecimal.ZERO;

        String carrierDeliveryZone = null;
        String carrierRestrictionCodes = null;
        String carrierRestrictionDesc = null;

        // send a new request for each package
        for (Iterator<GenericValue> i = shipmentPackageRouteSegList.iterator(); i.hasNext();) {

            GenericValue shipmentPackageRouteSeg = i.next();
            //String sprsKeyString = "[" + shipmentPackageRouteSeg.getString("shipmentId") + "," +
            //        shipmentPackageRouteSeg.getString("shipmentPackageSeqId") + "," +
            //        shipmentPackageRouteSeg.getString("shipmentRouteSegmentId") + "]";

            Document requestDocument = createUspsRequestDocument("RateRequest", true, delegator,
                    shipmentGatewayConfigId, resource);

            Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                    requestDocument);
            packageElement.setAttribute("ID", "0");

            UtilXml.addChildElementValue(packageElement, "Service", serviceType, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipOrigination", originZip, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipDestination", destinationZip, requestDocument);

            GenericValue shipmentPackage = null;
            shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);

            // weight elements - Pounds, Ounces
            String weightStr = shipmentPackage.getString("weight");
            if (UtilValidate.isEmpty(weightStr)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsWeightNotFound",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")),
                        locale));
            }

            BigDecimal weight = BigDecimal.ZERO;
            try {
                weight = new BigDecimal(weightStr);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }

            String weightUomId = shipmentPackage.getString("weightUomId");
            if (UtilValidate.isEmpty(weightUomId)) {
                weightUomId = "WT_lb"; // assume weight is in pounds
            }
            if (!"WT_lb".equals(weightUomId)) {
                // attempt a conversion to pounds
                Map<String, Object> result = FastMap.newInstance();
                try {
                    result = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId",
                            weightUomId, "uomIdTo", "WT_lb", "originalValue", weight));
                } catch (GenericServiceException ex) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightConversionError",
                            UtilMisc.toMap("errorString", ex.getMessage()), locale));
                }

                if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)
                        && result.get("convertedValue") != null) {
                    weight = weight.multiply((BigDecimal) result.get("convertedValue"));
                } else {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightUnsupported",
                            UtilMisc.toMap("weightUomId", weightUomId, "shipmentId",
                                    shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId",
                                    shipmentPackage.getString("shipmentPackageSeqId"), "weightUom", "WT_lb"),
                            locale));
                }

            }

            BigDecimal weightPounds = weight.setScale(0, BigDecimal.ROUND_FLOOR);
            BigDecimal weightOunces = weight.multiply(new BigDecimal("16")).remainder(new BigDecimal("16"))
                    .setScale(0, BigDecimal.ROUND_CEILING);

            DecimalFormat df = new DecimalFormat("#");
            UtilXml.addChildElementValue(packageElement, "Pounds", df.format(weightPounds), requestDocument);
            UtilXml.addChildElementValue(packageElement, "Ounces", df.format(weightOunces), requestDocument);

            // Container element
            GenericValue carrierShipmentBoxType = null;
            List<GenericValue> carrierShipmentBoxTypes = null;
            carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType",
                    UtilMisc.toMap("partyId", "USPS"), null, false);

            if (carrierShipmentBoxTypes.size() > 0) {
                carrierShipmentBoxType = carrierShipmentBoxTypes.get(0);
            }

            if (carrierShipmentBoxType != null
                    && UtilValidate.isNotEmpty(carrierShipmentBoxType.getString("packagingTypeCode"))) {
                UtilXml.addChildElementValue(packageElement, "Container",
                        carrierShipmentBoxType.getString("packagingTypeCode"), requestDocument);
            } else {
                // default to "None", for customers using their own package
                UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
            }

            // Size element
            if (carrierShipmentBoxType != null && UtilValidate.isNotEmpty("oversizeCode")) {
                UtilXml.addChildElementValue(packageElement, "Size",
                        carrierShipmentBoxType.getString("oversizeCode"), requestDocument);
            } else {
                // default to "Regular", length + girth measurement <= 84 inches
                UtilXml.addChildElementValue(packageElement, "Size", "Regular", requestDocument);
            }

            // Although only applicable for Parcel Post, this tag is required for all requests
            UtilXml.addChildElementValue(packageElement, "Machinable", "False", requestDocument);

            Document responseDocument = null;
            try {
                responseDocument = sendUspsRequest("Rate", requestDocument, delegator, shipmentGatewayConfigId,
                        resource, locale);
            } catch (UspsRequestException e) {
                Debug.logInfo(e, module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError",
                                UtilMisc.toMap("errorString", e.getMessage()), locale));
            }

            Element respPackageElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(),
                    "Package");
            if (respPackageElement == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateDomesticResponseIncompleteElementPackage", locale));
            }

            Element respErrorElement = UtilXml.firstChildElement(respPackageElement, "Error");
            if (respErrorElement != null) {
                return ServiceUtil
                        .returnError(UtilProperties
                                .getMessage(resourceError, "FacilityShipmentUspsRateDomesticResponseError",
                                        UtilMisc.toMap("errorString",
                                                UtilXml.childElementValue(respErrorElement, "Description")),
                                        locale));
            }

            // update the ShipmentPackageRouteSeg
            String postageString = UtilXml.childElementValue(respPackageElement, "Postage");
            if (UtilValidate.isEmpty(postageString)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateDomesticResponseIncompleteElementPostage", locale));
            }

            BigDecimal postage = BigDecimal.ZERO;
            try {
                postage = new BigDecimal(postageString);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }
            actualTransportCost = actualTransportCost.add(postage);

            shipmentPackageRouteSeg.setString("packageTransportCost", postageString);
            shipmentPackageRouteSeg.store();

            // if this is the last package, get the zone and APO/FPO restrictions for the ShipmentRouteSegment
            if (!i.hasNext()) {
                carrierDeliveryZone = UtilXml.childElementValue(respPackageElement, "Zone");
                carrierRestrictionCodes = UtilXml.childElementValue(respPackageElement, "RestrictionCodes");
                carrierRestrictionDesc = UtilXml.childElementValue(respPackageElement,
                        "RestrictionDescription");
            }
        }

        // update the ShipmentRouteSegment
        shipmentRouteSegment.set("carrierDeliveryZone", carrierDeliveryZone);
        shipmentRouteSegment.set("carrierRestrictionCodes", carrierRestrictionCodes);
        shipmentRouteSegment.set("carrierRestrictionDesc", carrierRestrictionDesc);
        shipmentRouteSegment.setString("actualTransportCost", String.valueOf(actualTransportCost));
        shipmentRouteSegment.store();

    } catch (GenericEntityException gee) {
        Debug.logInfo(gee, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticReadingError",
                        UtilMisc.toMap("errorString", gee.getMessage()), locale));
    }

    return ServiceUtil.returnSuccess();
}

From source file:org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao.java

public FIN_Payment getNewPayment(boolean isReceipt, Organization organization, DocumentType docType,
        String strPaymentDocumentNo, BusinessPartner businessPartner, FIN_PaymentMethod paymentMethod,
        FIN_FinancialAccount finAccount, String strPaymentAmount, Date paymentDate, String referenceNo,
        Currency paymentCurrency, BigDecimal finTxnConvertRate, BigDecimal finTxnAmount) {
    final FIN_Payment newPayment = OBProvider.getInstance().get(FIN_Payment.class);
    newPayment.setReceipt(isReceipt);/*from  w  w w .j ava2s.com*/
    newPayment.setDocumentType(docType);
    newPayment.setDocumentNo(strPaymentDocumentNo);
    newPayment.setOrganization(organization);
    newPayment.setClient(organization.getClient());
    newPayment.setStatus("RPAP");
    newPayment.setBusinessPartner(businessPartner);
    newPayment.setPaymentMethod(paymentMethod);
    newPayment.setAccount(finAccount);
    final BigDecimal paymentAmount = new BigDecimal(strPaymentAmount);
    newPayment.setAmount(paymentAmount);
    newPayment.setPaymentDate(paymentDate);
    if (paymentCurrency != null) {
        newPayment.setCurrency(paymentCurrency);
    } else {
        newPayment.setCurrency(finAccount.getCurrency());
    }
    newPayment.setReferenceNo(referenceNo);
    if (finTxnConvertRate == null || finTxnConvertRate.compareTo(BigDecimal.ZERO) <= 0) {
        finTxnConvertRate = BigDecimal.ONE;
    }
    if (finTxnAmount == null || finTxnAmount.compareTo(BigDecimal.ZERO) == 0) {
        finTxnAmount = paymentAmount.multiply(finTxnConvertRate);
    }
    // This code commented due to fix in bug 17829
    // else if (paymentAmount != null && paymentAmount.compareTo(BigDecimal.ZERO) != 0) {
    // // Correct exchange rate for rounding that occurs in UI
    // finTxnConvertRate = finTxnAmount.divide(paymentAmount, MathContext.DECIMAL64);
    // }

    newPayment.setFinancialTransactionConvertRate(finTxnConvertRate);
    newPayment.setFinancialTransactionAmount(finTxnAmount);

    OBDal.getInstance().save(newPayment);

    return newPayment;
}

From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * @see org.kuali.ole.module.purap.service.PurapAccountingService#convertMoneyToPercent(org.kuali.ole.module.purap.document.PaymentRequestDocument)
 *///from  w ww  .j av a 2 s  . co m
@Override
public void convertMoneyToPercent(PaymentRequestDocument pr) {
    LOG.debug("convertMoneyToPercent() started");

    int itemNbr = 0;

    for (Iterator<PaymentRequestItem> iter = pr.getItems().iterator(); iter.hasNext();) {
        PaymentRequestItem item = iter.next();

        itemNbr++;
        String identifier = item.getItemIdentifierString();

        if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) {
            int numOfAccounts = item.getSourceAccountingLines().size();
            BigDecimal percentTotal = BigDecimal.ZERO;
            KualiDecimal accountTotal = KualiDecimal.ZERO;
            int accountIdentifier = 0;

            KualiDecimal addChargeItem = KualiDecimal.ZERO;
            KualiDecimal lineItemPreTaxTotal = KualiDecimal.ZERO;
            /* KualiDecimal prorateSurcharge = KualiDecimal.ZERO;
             if (item.getItemType().isQuantityBasedGeneralLedgerIndicator() && item.getExtendedPrice() != null && item.getExtendedPrice().compareTo(KualiDecimal.ZERO) != 0) {
            if (((OlePaymentRequestItem) item).getItemSurcharge() != null) {
                prorateSurcharge = new KualiDecimal(((OlePaymentRequestItem) item).getItemSurcharge()).multiply(item.getItemQuantity());
            }
             }*/
            PurApAccountingLine lastAccount = null;
            BigDecimal accountTotalPercent = BigDecimal.ZERO;

            for (PurApAccountingLine purApAccountingLine : item.getSourceAccountingLines()) {
                accountIdentifier++;
                PaymentRequestAccount account = (PaymentRequestAccount) purApAccountingLine;

                // account.getAmount returns the wrong value for trade in source accounting lines...
                KualiDecimal accountAmount = KualiDecimal.ZERO;
                if (ObjectUtils.isNotNull(account.getAmount())) {
                    accountAmount = account.getAmount();
                }

                BigDecimal tmpPercent = BigDecimal.ZERO;
                KualiDecimal extendedPrice = item.getTotalAmount();
                tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(),
                        PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR);

                if (accountIdentifier == numOfAccounts) {
                    // if on last account, calculate the percent by subtracting current percent total from 1
                    tmpPercent = BigDecimal.ONE.subtract(percentTotal);
                }

                // test that the above amount is correct, if so just check that the total of all these matches the item total
                BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue());
                calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR);
                KualiDecimal calcAmount = new KualiDecimal(calcAmountBd);
                //calcAmount = calcAmount.subtract(prorateSurcharge);
                if (calcAmount.compareTo(accountAmount) != 0) {
                    // rounding error
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("convertMoneyToPercent() Rounding error on " + account);
                    }
                    String param1 = identifier + "." + accountIdentifier;
                    String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue())
                            .toString();
                    GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(),
                            PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2);
                    account.setAmount(calcAmount);
                }

                // update percent
                if (LOG.isDebugEnabled()) {
                    LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent);
                }
                account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100)));
                accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent());
                lastAccount = account;
                // check total based on adjusted amount
                accountTotal = accountTotal.add(calcAmount);
                percentTotal = percentTotal.add(tmpPercent);
            }
            BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent)
                    .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING);
            if (ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) {
                KualiDecimal differencePercent = (((new KualiDecimal(accountTotalPercent))
                        .subtract(new KualiDecimal(100))).abs());
                if ((differencePercent.abs()).isLessEqual(
                        new KualiDecimal(1).multiply((new KualiDecimal(item.getSourceAccountingLines().size())
                                .divide(new KualiDecimal(2)))))) {
                    lastAccount
                            .setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference));
                } else {
                    lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent());
                }
            }
        }
    }
}

From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java

@Override
public void convertMoneyToPercent(InvoiceDocument inv) {
    LOG.debug("convertMoneyToPercent() started");

    int itemNbr = 0;

    for (Iterator<InvoiceItem> iter = inv.getItems().iterator(); iter.hasNext();) {
        InvoiceItem item = iter.next();//from   ww  w. j  a v a  2  s. c  om

        itemNbr++;
        String identifier = item.getItemIdentifierString();

        if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) {
            int numOfAccounts = item.getSourceAccountingLines().size();
            BigDecimal percentTotal = BigDecimal.ZERO;
            KualiDecimal accountTotal = KualiDecimal.ZERO;
            int accountIdentifier = 0;

            KualiDecimal addChargeItem = KualiDecimal.ZERO;
            KualiDecimal lineItemPreTaxTotal = KualiDecimal.ZERO;
            KualiDecimal prorateSurcharge = KualiDecimal.ZERO;
            if (item.getItemType().isQuantityBasedGeneralLedgerIndicator() && item.getExtendedPrice() != null
                    && item.getExtendedPrice().compareTo(KualiDecimal.ZERO) != 0) {
                if (((OleInvoiceItem) item).getItemSurcharge() != null) {
                    prorateSurcharge = new KualiDecimal(((OleInvoiceItem) item).getItemSurcharge())
                            .multiply(item.getItemQuantity());
                }
            }
            PurApAccountingLine lastAccount = null;
            BigDecimal accountTotalPercent = BigDecimal.ZERO;
            for (PurApAccountingLine purApAccountingLine : item.getSourceAccountingLines()) {
                accountIdentifier++;
                InvoiceAccount account = (InvoiceAccount) purApAccountingLine;

                // account.getAmount returns the wrong value for trade in source accounting lines...
                KualiDecimal accountAmount = KualiDecimal.ZERO;
                if (ObjectUtils.isNotNull(account.getAmount())) {
                    accountAmount = account.getAmount();
                }

                BigDecimal tmpPercent = BigDecimal.ZERO;
                KualiDecimal extendedPrice = item.getTotalAmount();
                tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(),
                        PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR);

                if (accountIdentifier == numOfAccounts) {
                    // if on last account, calculate the percent by subtracting current percent total from 1
                    tmpPercent = BigDecimal.ONE.subtract(percentTotal);
                }

                // test that the above amount is correct, if so just check that the total of all these matches the item total
                BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue());
                calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR);
                KualiDecimal calcAmount = new KualiDecimal(calcAmountBd);
                calcAmount = calcAmount.subtract(prorateSurcharge);
                if (calcAmount.compareTo(accountAmount) != 0) {
                    // rounding error
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("convertMoneyToPercent() Rounding error on " + account);
                    }
                    String param1 = identifier + "." + accountIdentifier;
                    String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue())
                            .toString();
                    GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(),
                            PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2);
                    account.setAmount(calcAmount);
                }

                // update percent
                if (LOG.isDebugEnabled()) {
                    LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent);
                }
                account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100)));
                accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent());
                lastAccount = account;

                // check total based on adjusted amount
                accountTotal = accountTotal.add(calcAmount);
                percentTotal = percentTotal.add(tmpPercent);
            }
            BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent)
                    .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING);
            if (ObjectUtils.isNotNull(lastAccount)
                    && ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) {
                KualiDecimal differencePercent = (((new KualiDecimal(accountTotalPercent))
                        .subtract(new KualiDecimal(100))).abs());
                if ((differencePercent.abs()).isLessEqual(
                        new KualiDecimal(1).multiply((new KualiDecimal(item.getSourceAccountingLines().size())
                                .divide(new KualiDecimal(2)))))) {
                    lastAccount
                            .setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference));
                } else {
                    lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent());
                }
            }
        }
    }
}

From source file:com.fujitsu.dc.test.setup.Setup.java

/**
 * $filter?EntityType?OData?./* ww  w  .  ja va 2s .c  om*/
 * @param entity EntityType??
 */
private void createFilterTestUserData(String entity) {
    final String token = AbstractCase.MASTER_TOKEN_NAME;
    final int userDataNum = 10;
    final int intData = 1111;
    final BigDecimal singleData = new BigDecimal(1111.11);
    final BigDecimal doubleData = new BigDecimal(1111111.1111111d);
    final long dateTimeData = 1410689956172L;
    final int dateTimeOffset = 1000000;
    try {
        for (int i = 0; i < userDataNum; i++) {
            StringBuilder sbuf = new StringBuilder();
            sbuf.append(String.format("{\"__id\":\"id_%04d\",", i));
            sbuf.append(String.format("\"string\":\"string %s\",", String.format("%04d", i)));
            sbuf.append(String.format("\"int32\":%d,", intData * i));
            sbuf.append(String.format("\"single\":%f,", singleData.multiply(new BigDecimal(i))));
            sbuf.append(String.format("\"double\":%f,", doubleData.multiply(new BigDecimal(i))));
            sbuf.append(String.format("\"boolean\":%b,", i % 2 == 0));
            sbuf.append(String.format("\"datetime\":\"/Date(%d)/\",", dateTimeData + i * dateTimeOffset));
            sbuf.append(String.format("\"string_list\":%s,", getStringArray(i)));
            sbuf.append(String.format("\"int32_list\":%s,", getIntgerArray(i)));
            sbuf.append(String.format("\"single_list\":%s,", getFloatArray(i)));
            sbuf.append(String.format("\"double_list\":%s,", getDoubleArray(i)));
            sbuf.append(String.format("\"boolean_list\":%s,", getBooleanArray(i)));
            sbuf.append(String.format("}", i % 2 == 0));
            JSONObject body = (JSONObject) new JSONParser().parse(new StringReader(sbuf.toString()));
            UserDataUtils.create(token, HttpStatus.SC_CREATED, body, TEST_CELL_FILTER, "box", "odata", entity);
        }
    } catch (IOException e) {
        fail(e.getMessage());
    } catch (ParseException e) {
        fail(e.getMessage());
    }
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsDeliveryConfirmation(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");

    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator,
            shipmentId, locale);//from   ww w . j  av  a  2 s .  c om
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsGatewayNotAvailable", locale));
    }

    try {
        GenericValue shipment = EntityQuery.use(delegator).from("Shipment").where("shipmentId", shipmentId)
                .queryOne();
        if (shipment == null) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resourceError, "ProductShipmentNotFoundId", locale) + shipmentId);
        }

        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment")
                .where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "ProductShipmentRouteSegmentNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // ensure the carrier is USPS
        if (!"USPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNotRouteSegmentCarrier",
                    UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId),
                    locale));
        }

        // get the origin address
        GenericValue originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentOriginPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(originAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // get the destination address
        GenericValue destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentDestPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(destinationAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // get the service type from the CarrierShipmentMethod
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String partyId = shipmentRouteSegment.getString("carrierPartyId");

        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("partyId", partyId, "roleTypeId", "CARRIER", "shipmentMethodTypeId",
                        shipmentMethodTypeId)
                .queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierShipmentMethod",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }
        String serviceType = carrierShipmentMethod.getString("carrierServiceCode");
        if (UtilValidate.isEmpty(serviceType)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsUnableDetermineServiceCode", locale));
        }

        // get the packages for this shipment route segment
        List<GenericValue> shipmentPackageRouteSegList = shipmentRouteSegment
                .getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegList)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentPackageRouteSegsNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegList) {
            Document requestDocument = createUspsRequestDocument("DeliveryConfirmationV2.0Request", true,
                    delegator, shipmentGatewayConfigId, resource);
            Element requestElement = requestDocument.getDocumentElement();

            UtilXml.addChildElementValue(requestElement, "Option", "3", requestDocument);
            UtilXml.addChildElement(requestElement, "ImageParameters", requestDocument);

            // From address
            if (UtilValidate.isNotEmpty(originAddress.getString("attnName"))) {
                UtilXml.addChildElementValue(requestElement, "FromName", originAddress.getString("attnName"),
                        requestDocument);
                UtilXml.addChildElementValue(requestElement, "FromFirm", originAddress.getString("toName"),
                        requestDocument);
            } else {
                UtilXml.addChildElementValue(requestElement, "FromName", originAddress.getString("toName"),
                        requestDocument);
            }
            // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1
            UtilXml.addChildElementValue(requestElement, "FromAddress1", originAddress.getString("address2"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromAddress2", originAddress.getString("address1"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromCity", originAddress.getString("city"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromState",
                    originAddress.getString("stateProvinceGeoId"), requestDocument);
            UtilXml.addChildElementValue(requestElement, "FromZip5", originAddress.getString("postalCode"),
                    requestDocument);
            UtilXml.addChildElement(requestElement, "FromZip4", requestDocument);

            // To address
            if (UtilValidate.isNotEmpty(destinationAddress.getString("attnName"))) {
                UtilXml.addChildElementValue(requestElement, "ToName", destinationAddress.getString("attnName"),
                        requestDocument);
                UtilXml.addChildElementValue(requestElement, "ToFirm", destinationAddress.getString("toName"),
                        requestDocument);
            } else {
                UtilXml.addChildElementValue(requestElement, "ToName", destinationAddress.getString("toName"),
                        requestDocument);
            }
            // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1
            UtilXml.addChildElementValue(requestElement, "ToAddress1", destinationAddress.getString("address2"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToAddress2", destinationAddress.getString("address1"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToCity", destinationAddress.getString("city"),
                    requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToState",
                    destinationAddress.getString("stateProvinceGeoId"), requestDocument);
            UtilXml.addChildElementValue(requestElement, "ToZip5", destinationAddress.getString("postalCode"),
                    requestDocument);
            UtilXml.addChildElement(requestElement, "ToZip4", requestDocument);

            GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);

            // WeightInOunces
            String weightStr = shipmentPackage.getString("weight");
            if (UtilValidate.isEmpty(weightStr)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsWeightNotFound",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")),
                        locale));
            }

            BigDecimal weight = BigDecimal.ZERO;
            try {
                weight = new BigDecimal(weightStr);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }

            String weightUomId = shipmentPackage.getString("weightUomId");
            if (UtilValidate.isEmpty(weightUomId)) {
                // assume weight is in pounds for consistency (this assumption is made in uspsDomesticRate also)
                weightUomId = "WT_lb";
            }
            if (!"WT_oz".equals(weightUomId)) {
                // attempt a conversion to pounds
                GenericValue uomConversion = EntityQuery.use(delegator).from("UomConversion")
                        .where("uomId", weightUomId, "uomIdTo", "WT_oz").queryOne();
                if (uomConversion == null
                        || UtilValidate.isEmpty(uomConversion.getString("conversionFactor"))) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightUnsupported",
                            UtilMisc.toMap("weightUomId", weightUomId, "shipmentId",
                                    shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId",
                                    shipmentPackage.getString("shipmentPackageSeqId"), "weightUom", "WT_oz"),
                            locale));
                }
                weight = weight.multiply(uomConversion.getBigDecimal("conversionFactor"));
            }

            DecimalFormat df = new DecimalFormat("#");
            UtilXml.addChildElementValue(requestElement, "WeightInOunces",
                    df.format(weight.setScale(0, BigDecimal.ROUND_CEILING)), requestDocument);

            UtilXml.addChildElementValue(requestElement, "ServiceType", serviceType, requestDocument);
            UtilXml.addChildElementValue(requestElement, "ImageType", "TIF", requestDocument);
            UtilXml.addChildElementValue(requestElement, "AddressServiceRequested", "True", requestDocument);

            Document responseDocument = null;
            try {
                responseDocument = sendUspsRequest("DeliveryConfirmationV2", requestDocument, delegator,
                        shipmentGatewayConfigId, resource, locale);
            } catch (UspsRequestException e) {
                Debug.logInfo(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationSendingError",
                        UtilMisc.toMap("errorString", e.getMessage()), locale));
            }
            Element responseElement = responseDocument.getDocumentElement();

            Element respErrorElement = UtilXml.firstChildElement(responseElement, "Error");
            if (respErrorElement != null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponseError",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId"),
                                "errorString", UtilXml.childElementValue(respErrorElement, "Description")),
                        locale));
            }

            String labelImageString = UtilXml.childElementValue(responseElement, "DeliveryConfirmationLabel");
            if (UtilValidate.isEmpty(labelImageString)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponseIncompleteElementDeliveryConfirmationLabel",
                        locale));
            }
            shipmentPackageRouteSeg.setBytes("labelImage", Base64.base64Decode(labelImageString.getBytes()));
            String trackingCode = UtilXml.childElementValue(responseElement, "DeliveryConfirmationNumber");
            if (UtilValidate.isEmpty(trackingCode)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsDeliveryConfirmationResponsenIncompleteElementDeliveryConfirmationNumber",
                        locale));
            }
            shipmentPackageRouteSeg.set("trackingCode", trackingCode);
            shipmentPackageRouteSeg.store();
        }

    } catch (GenericEntityException gee) {
        Debug.logInfo(gee, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsDeliveryConfirmationReadingError",
                        UtilMisc.toMap("errorString", gee.getMessage()), locale));
    }

    return ServiceUtil.returnSuccess();
}

From source file:org.kuali.ole.select.document.service.impl.OleCreditMemoServiceImpl.java

public void calculateProrateItemSurcharge(OleVendorCreditMemoDocument vendorCreditMemoDocument) {
    LOG.debug("Inside Calculation for ProrateItemSurcharge");
    vendorCreditMemoDocument.setProrateBy(vendorCreditMemoDocument.isProrateQty() ? OLEConstants.PRORATE_BY_QTY
            : vendorCreditMemoDocument.isProrateManual() ? OLEConstants.MANUAL_PRORATE
                    : vendorCreditMemoDocument.isProrateDollar() ? OLEConstants.PRORATE_BY_DOLLAR
                            : vendorCreditMemoDocument.isNoProrate() ? OLEConstants.NO_PRORATE : null);
    BigDecimal addChargeItem = BigDecimal.ZERO;
    List<OleCreditMemoItem> item = (List<OleCreditMemoItem>) vendorCreditMemoDocument.getItems();
    for (OleCreditMemoItem items : item) {
        if (!items.getItemType().isQuantityBasedGeneralLedgerIndicator()
                && !items.getItemTypeCode()
                        .equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_PMT_TERMS_DISCOUNT_CODE)
                && items.getItemUnitPrice() != null) {
            addChargeItem = addChargeItem.add(items.getItemUnitPrice());
        }//from w  w w.  ja  v a 2  s  .  c  o  m
    }
    List<BigDecimal> newUnitPriceList = new ArrayList<BigDecimal>();
    BigDecimal totalExtPrice = new BigDecimal(0);
    BigDecimal newUnitPrice = new BigDecimal(0);
    BigDecimal extPrice = new BigDecimal(0);
    BigDecimal unitPricePercent = new BigDecimal(0);
    BigDecimal hundred = new BigDecimal(100);
    BigDecimal one = new BigDecimal(1);
    BigDecimal totalSurCharge = new BigDecimal(0);
    BigDecimal totalItemQuantity = new BigDecimal(0);
    BigDecimal itemSurchargeCons = new BigDecimal(0);
    for (int i = 0; item.size() > i; i++) {
        OleCreditMemoItem items = (OleCreditMemoItem) vendorCreditMemoDocument.getItem(i);
        if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator())
                && !ObjectUtils.isNull(items.getItemQuantity())) {
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                totalItemQuantity = totalItemQuantity.add(items.getItemQuantity().bigDecimalValue());
            }
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)
                    || vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                    || vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                /*if (items.getItemDiscount() == null) {
                items.setItemDiscount(KualiDecimal.ZERO);
                }
                if (items.getItemDiscountType() != null && items.getItemDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
                newUnitPrice = (hundred.subtract(items.getItemDiscount().bigDecimalValue())).divide(hundred).multiply(items.getItemListPrice().bigDecimalValue());
                }
                else {
                newUnitPrice = items.getItemListPrice().bigDecimalValue().subtract(items.getItemDiscount().bigDecimalValue());
                }*/
                newUnitPrice = items.getItemUnitPrice();
                newUnitPriceList.add(newUnitPrice);
                extPrice = newUnitPrice.multiply(items.getItemQuantity().bigDecimalValue());
                totalExtPrice = totalExtPrice.add(extPrice);
            }
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
                if (items.getItemSurcharge() == null) {
                    items.setItemSurcharge(BigDecimal.ZERO);
                }
                totalSurCharge = totalSurCharge
                        .add(items.getItemQuantity().bigDecimalValue().multiply(items.getItemSurcharge()));
            }
        }

    }
    if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
        if (totalItemQuantity.compareTo(BigDecimal.ZERO) != 0) {
            itemSurchargeCons = one.divide(totalItemQuantity, 8, RoundingMode.HALF_UP);
        }
    }
    for (int i = 0, j = 0; item.size() > i; i++) {
        OleCreditMemoItem items = (OleCreditMemoItem) vendorCreditMemoDocument.getItem(i);
        if (items.getItemType().isQuantityBasedGeneralLedgerIndicator() && newUnitPriceList.size() > j
                && !ObjectUtils.isNull(items.getItemQuantity())) {
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)) {
                if (totalExtPrice.compareTo(BigDecimal.ZERO) != 0) {
                    unitPricePercent = newUnitPriceList.get(j).divide(totalExtPrice, 8, RoundingMode.HALF_UP);
                }
                items.setItemSurcharge(
                        unitPricePercent.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                items.setExtendedPrice(
                        (new KualiDecimal((newUnitPriceList.get(j).add(items.getItemSurcharge()).toString())))
                                .multiply(items.getItemQuantity()));
            }
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) {
                items.setItemSurcharge(
                        itemSurchargeCons.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP));
                items.setExtendedPrice(
                        new KualiDecimal(((newUnitPriceList.get(j).add(items.getItemSurcharge()).toString())))
                                .multiply(items.getItemQuantity()));
            }
            if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)
                    && items.getItemSurcharge() != null) {
                items.setExtendedPrice(
                        new KualiDecimal(((newUnitPriceList.get(j).add(items.getItemSurcharge()).toString())))
                                .multiply(items.getItemQuantity()));
            }
            j++;
        }
    }
    if (vendorCreditMemoDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) {
        if (totalSurCharge.compareTo(addChargeItem) != 0) {
            GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY,
                    OLEKeyConstants.ERROR_PAYMENT_REQUEST_TOTAL_MISMATCH);
        }
    }
    LOG.debug("Leaving Calculation for ProrateItemSurcharge");
}

From source file:com.cloud.storage.StorageManagerImpl.java

private boolean checkPoolforSpace(StoragePool pool, long allocatedSizeWithTemplate, long totalAskingSize) {
    // allocated space includes templates
    StoragePoolVO poolVO = _storagePoolDao.findById(pool.getId());

    long totalOverProvCapacity;

    if (pool.getPoolType().supportsOverProvisioning()) {
        BigDecimal overProvFactor = getStorageOverProvisioningFactor(pool.getId());

        totalOverProvCapacity = overProvFactor.multiply(new BigDecimal(pool.getCapacityBytes())).longValue();

        s_logger.debug("Found storage pool " + poolVO.getName() + " of type " + pool.getPoolType().toString()
                + " with over-provisioning factor " + overProvFactor.toString());
        s_logger.debug("Total over-provisioned capacity calculated is " + overProvFactor + " * "
                + pool.getCapacityBytes());
    } else {//  ww w. j ava  2s .c  om
        totalOverProvCapacity = pool.getCapacityBytes();

        s_logger.debug("Found storage pool " + poolVO.getName() + " of type " + pool.getPoolType().toString());
    }

    s_logger.debug("Total capacity of the pool " + poolVO.getName() + " with ID " + pool.getId() + " is "
            + totalOverProvCapacity);

    double storageAllocatedThreshold = CapacityManager.StorageAllocatedCapacityDisableThreshold
            .valueIn(pool.getDataCenterId());

    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Checking pool: " + pool.getId() + " for storage allocation , maxSize : "
                + totalOverProvCapacity + ", totalAllocatedSize : " + allocatedSizeWithTemplate
                + ", askingSize : " + totalAskingSize + ", allocated disable threshold: "
                + storageAllocatedThreshold);
    }

    double usedPercentage = (allocatedSizeWithTemplate + totalAskingSize) / (double) (totalOverProvCapacity);

    if (usedPercentage > storageAllocatedThreshold) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Insufficient un-allocated capacity on: " + pool.getId()
                    + " for storage allocation since its allocated percentage: " + usedPercentage
                    + " has crossed the allocated pool.storage.allocated.capacity.disablethreshold: "
                    + storageAllocatedThreshold + ", skipping this pool");
        }

        return false;
    }

    if (totalOverProvCapacity < (allocatedSizeWithTemplate + totalAskingSize)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Insufficient un-allocated capacity on: " + pool.getId()
                    + " for storage allocation, not enough storage, maxSize : " + totalOverProvCapacity
                    + ", totalAllocatedSize : " + allocatedSizeWithTemplate + ", askingSize : "
                    + totalAskingSize);
        }

        return false;
    }

    return true;
}