Example usage for java.math BigDecimal ROUND_CEILING

List of usage examples for java.math BigDecimal ROUND_CEILING

Introduction

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

Prototype

int ROUND_CEILING

To view the source code for java.math BigDecimal ROUND_CEILING.

Click Source Link

Document

Rounding mode to round towards positive infinity.

Usage

From source file:la2launcher.MainFrame.java

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed

    Thread th = new Thread() {
        @Override/*  w w  w. ja  v a2  s  .c o  m*/
        public void run() {
            try {
                jTextArea2.setText(" ");
                File patch = File.createTempFile("patch", ".zip");
                patch.deleteOnExit();
                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(patchPath);
                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                FileOutputStream fos = new FileOutputStream(patch);
                HttpEntity entity1 = response1.getEntity();
                copyStream(entity1.getContent(), fos, new CopyListener() {
                    @Override
                    public void transfered(int n) {
                        bytesRecieved += n;
                        bytesRecievedTotal += n;
                    }
                });
                response1.close();
                fos.close();
                jTextArea2.setText(jTextArea2.getText() + "\r\n ");

                try {
                    new DirDeltaPatcher().patch(new File(gamePath + "\\system"), patch);
                } catch (Exception e) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n" + e);
                    return;
                }
                jTextArea2.setText(jTextArea2.getText() + "\r\n? ");

            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };

    th.start();

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (th.isAlive());

            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
        }
    }.start();

}

From source file:la2launcher.MainFrame.java

private void processValidation(boolean full) {
    final long initTime = new Date().getTime();
    final String patcherUrl = "http://" + updateHost + "/hf/updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000)
    final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS,
            new ArrayBlockingQueue<Runnable>(10000));
    tpe.execute(new Runnable() {
        @Override//w w  w  .  j  a  v  a2  s .c  o m
        public void run() {
            jTextArea2.setText("");
            try {
                if (full) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n?  ");
                } else {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n?  system");
                }
                File patcher = File.createTempFile("la2", "la2");
                patcher.deleteOnExit();
                File patcherExt = File.createTempFile("la2", "la2");
                patcherExt.deleteOnExit();
                FileOutputStream fos = new FileOutputStream(patcher);
                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(patcherUrl);
                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                HttpEntity entity1 = response1.getEntity();
                copyStream(entity1.getContent(), fos, null);
                response1.close();
                fos.close();
                jTextArea2.setText(jTextArea2.getText()
                        + "\r\n??  ? ?: " + patcherUrl);

                fixBzip2File(patcher);
                jTextArea2.setText(jTextArea2.getText() + "\r\n ?");

                BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(patcher));
                OutputStream pout = new FileOutputStream(patcherExt);
                copyStream(bz, pout, new CopyListener() {
                    @Override
                    public void transfered(int n) {
                        bytesRecieved += n;
                        bytesRecievedTotal += n;
                    }
                });
                pout.close();
                bz.close();
                jTextArea2.setText(jTextArea2.getText() + "\r\n? ?");

                if (full) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n  ");
                } else {
                    jTextArea2.setText(jTextArea2.getText()
                            + "\r\n     system");
                }

                DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
                model.setRowCount(0);

                int filesCount = scanSumFilesCount(patcherExt, full);
                jProgressBar1.setMinimum(0);
                jProgressBar1.setMaximum(filesCount);
                jProgressBar1.setValue(0);
                jLabel4.setText("0/" + filesCount);
                scanSumFile(patcherExt, new SumHandler() {

                    private ReentrantLock lock = new ReentrantLock();

                    @Override
                    public void handle(MDNamePair pair) {
                        try {
                            jProgressBar1.setIndeterminate(false);
                            //lock.unlock();
                            tpe.execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        lock.lock();
                                        //printMsg(pair.filename);
                                        String crc = digest(new File(gamePath + pair.filename));
                                        //printMsg("    : " + pair.crc);
                                        //printMsg("   ? ? : " + crc);
                                        if (!pair.crc.equals(crc)) {
                                            DefaultTableModel dtm = (DefaultTableModel) jTable2.getModel();
                                            dtm.addRow(new Object[] { pair.filename, false });
                                        }
                                        jProgressBar1.setValue(jProgressBar1.getValue() + 1);
                                        jLabel4.setText(jProgressBar1.getValue() + "/" + filesCount);
                                        lock.unlock();
                                    } catch (NoSuchAlgorithmException ex) {
                                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                                    } catch (IOException ex) {
                                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                                    } finally {
                                        //if (lock.isLocked()) lock.unlock();
                                    }
                                }
                            });
                        } finally {
                            //if (lock.isLocked()) lock.unlock();
                        }
                    }
                }, full);
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (tpe.getActiveCount() > 0);
            tpe.shutdown();
            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
            printMsg("  " + (new Date().getTime() - initTime)
                    + " ?.");
        }
    }.start();
}

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  ww .j  a v  a 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();
            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);//  w w w. j ava 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.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * calculates values for a list of accounting lines based on an amount taking discount into account
 *
 * @param sourceAccountingLines/*from   w w  w .j  ava2 s  . c o m*/
 * @param totalAmount
 * @param discountAmount
 */
@Override
public <T extends PurApAccountingLine> void updateAccountAmountsWithTotal(List<T> sourceAccountingLines,
        KualiDecimal totalAmount, KualiDecimal discountAmount) {

    // if we have a discount, then we need to base the amounts on the discount, but the percent on the total
    boolean noDiscount = true;
    if ((discountAmount != null) && KualiDecimal.ZERO.compareTo(discountAmount) != 0) {
        noDiscount = false;
    }

    if ((totalAmount != null) && KualiDecimal.ZERO.compareTo(totalAmount) != 0) {

        KualiDecimal accountTotal = KualiDecimal.ZERO;
        BigDecimal accountTotalPercent = BigDecimal.ZERO;
        T lastAccount = null;

        for (T account : sourceAccountingLines) {
            if (ObjectUtils.isNotNull(account.getAccountLinePercent())
                    || ObjectUtils.isNotNull(account.getAmount())) {
                if (ObjectUtils.isNotNull(account.getAmount())
                        && account.getAmount().isGreaterThan(KualiDecimal.ZERO)) {
                    KualiDecimal amt = account.getAmount();
                    KualiDecimal calculatedPercent = new KualiDecimal(
                            amt.multiply(new KualiDecimal(100)).divide(totalAmount).toString());
                    account.setAccountLinePercent(
                            calculatedPercent.bigDecimalValue().setScale(BIG_DECIMAL_SCALE));
                }

                if (ObjectUtils.isNotNull(account.getAccountLinePercent())) {
                    BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString())
                            .divide(new BigDecimal(100));
                    if (noDiscount) {
                        if (ObjectUtils.isNull(account.getAmount()) || account.getAmount().isZero()) {
                            account.setAmount(
                                    new KualiDecimal(pct.multiply(new BigDecimal(totalAmount.toString()))
                                            .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
                        }
                    } else {
                        account.setAmount(
                                new KualiDecimal(pct.multiply(new BigDecimal(discountAmount.toString()))
                                        .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
                    }
                }
            }

            if (ObjectUtils.isNotNull(account.getAmount())) {
                accountTotal = accountTotal.add(account.getAmount());
            }

            if (ObjectUtils.isNotNull(account.getAccountLinePercent())) {
                accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent());
            }

            lastAccount = account;
        }

        // put excess on last account
        if (lastAccount != null) {
            KualiDecimal difference = new KualiDecimal(0);
            if (noDiscount) {
                difference = totalAmount.subtract(accountTotal);
            } else {
                difference = discountAmount.subtract(accountTotal);
            }
            if (ObjectUtils.isNotNull(lastAccount.getAmount())) {
                if ((difference.abs()).isLessEqual(new KualiDecimal(1).multiply(
                        new KualiDecimal(sourceAccountingLines.size()).divide(new KualiDecimal(2))))) {
                    lastAccount.setAmount(lastAccount.getAmount().add(difference));
                } else {
                    lastAccount.setAmount(lastAccount.getAmount());
                }
            }
            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(sourceAccountingLines.size()).divide(new KualiDecimal(2)))))) {
                    lastAccount
                            .setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference));
                } else {
                    lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent());
                }
            }
        }
    } else {
        // zero out if extended price is zero
        for (T account : sourceAccountingLines) {
            if (ObjectUtils.isNotNull(account.getAmount())) {
                account.setAmount(KualiDecimal.ZERO);
            }
        }
    }
}

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

/**
 * calculates values for a list of accounting lines based on an amount for proportional method
 *
 * @param sourceAccountingLines//from   w  w  w.j  a  v a 2 s. c  o  m
 * @param totalAmount
 */
@Override
public <T extends PurApAccountingLine> void updatePreqProporationalAccountAmountsWithTotal(
        List<T> sourceAccountingLines, KualiDecimal totalAmount) {
    if ((totalAmount != null) && KualiDecimal.ZERO.compareTo(totalAmount) != 0) {
        KualiDecimal accountTotal = KualiDecimal.ZERO;
        BigDecimal accountTotalPercent = BigDecimal.ZERO;
        T lastAccount = null;

        for (T account : sourceAccountingLines) {
            if (ObjectUtils.isNotNull(account.getAccountLinePercent())
                    || ObjectUtils.isNotNull(account.getAmount())) {
                if (ObjectUtils.isNotNull(account.getAccountLinePercent())) {
                    BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString())
                            .divide(new BigDecimal(100));
                    account.setAmount(new KualiDecimal(pct.multiply(new BigDecimal(totalAmount.toString()))
                            .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
                }
            }

            if (ObjectUtils.isNotNull(account.getAmount())) {
                accountTotal = accountTotal.add(account.getAmount());
            }
            if (ObjectUtils.isNotNull(account.getAccountLinePercent())) {
                accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent());
            }

            lastAccount = account;
        }

        // put excess on last account
        if (lastAccount != null) {
            KualiDecimal difference = totalAmount.subtract(accountTotal);
            if (ObjectUtils.isNotNull(lastAccount.getAmount())) {
                lastAccount.setAmount(lastAccount.getAmount().add(difference));
            }

            BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent)
                    .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING);
            if (ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) {
                lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference));
            }
        }
    }
}

From source file:org.pentaho.di.core.ConstTest.java

@Test
public void testRound() {
    assertEquals(1.0, Const.round(1.0, 0, BigDecimal.ROUND_UP));
    assertEquals(1.0, Const.round(1.0, 0, BigDecimal.ROUND_DOWN));
    assertEquals(1.0, Const.round(1.0, 0, BigDecimal.ROUND_CEILING));
    assertEquals(1.0, Const.round(1.0, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(1.0, Const.round(1.0, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(1.0, Const.round(1.0, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(1.0, Const.round(1.0, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(1.0, Const.round(1.0, 0, Const.ROUND_HALF_CEILING));

    assertEquals(2.0, Const.round(1.2, 0, BigDecimal.ROUND_UP));
    assertEquals(1.0, Const.round(1.2, 0, BigDecimal.ROUND_DOWN));
    assertEquals(2.0, Const.round(1.2, 0, BigDecimal.ROUND_CEILING));
    assertEquals(1.0, Const.round(1.2, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(1.0, Const.round(1.2, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(1.0, Const.round(1.2, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(1.0, Const.round(1.2, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(1.0, Const.round(1.2, 0, Const.ROUND_HALF_CEILING));

    assertEquals(2.0, Const.round(1.5, 0, BigDecimal.ROUND_UP));
    assertEquals(1.0, Const.round(1.5, 0, BigDecimal.ROUND_DOWN));
    assertEquals(2.0, Const.round(1.5, 0, BigDecimal.ROUND_CEILING));
    assertEquals(1.0, Const.round(1.5, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(2.0, Const.round(1.5, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(1.0, Const.round(1.5, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(2.0, Const.round(1.5, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(2.0, Const.round(1.5, 0, Const.ROUND_HALF_CEILING));

    assertEquals(2.0, Const.round(1.7, 0, BigDecimal.ROUND_UP));
    assertEquals(1.0, Const.round(1.7, 0, BigDecimal.ROUND_DOWN));
    assertEquals(2.0, Const.round(1.7, 0, BigDecimal.ROUND_CEILING));
    assertEquals(1.0, Const.round(1.7, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(2.0, Const.round(1.7, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(2.0, Const.round(1.7, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(2.0, Const.round(1.7, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(2.0, Const.round(1.7, 0, Const.ROUND_HALF_CEILING));

    assertEquals(2.0, Const.round(2.0, 0, BigDecimal.ROUND_UP));
    assertEquals(2.0, Const.round(2.0, 0, BigDecimal.ROUND_DOWN));
    assertEquals(2.0, Const.round(2.0, 0, BigDecimal.ROUND_CEILING));
    assertEquals(2.0, Const.round(2.0, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(2.0, Const.round(2.0, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(2.0, Const.round(2.0, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(2.0, Const.round(2.0, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(2.0, Const.round(2.0, 0, Const.ROUND_HALF_CEILING));

    assertEquals(3.0, Const.round(2.2, 0, BigDecimal.ROUND_UP));
    assertEquals(2.0, Const.round(2.2, 0, BigDecimal.ROUND_DOWN));
    assertEquals(3.0, Const.round(2.2, 0, BigDecimal.ROUND_CEILING));
    assertEquals(2.0, Const.round(2.2, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(2.0, Const.round(2.2, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(2.0, Const.round(2.2, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(2.0, Const.round(2.2, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(2.0, Const.round(2.2, 0, Const.ROUND_HALF_CEILING));

    assertEquals(3.0, Const.round(2.5, 0, BigDecimal.ROUND_UP));
    assertEquals(2.0, Const.round(2.5, 0, BigDecimal.ROUND_DOWN));
    assertEquals(3.0, Const.round(2.5, 0, BigDecimal.ROUND_CEILING));
    assertEquals(2.0, Const.round(2.5, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(3.0, Const.round(2.5, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(2.0, Const.round(2.5, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(2.0, Const.round(2.5, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(3.0, Const.round(2.5, 0, Const.ROUND_HALF_CEILING));

    assertEquals(3.0, Const.round(2.7, 0, BigDecimal.ROUND_UP));
    assertEquals(2.0, Const.round(2.7, 0, BigDecimal.ROUND_DOWN));
    assertEquals(3.0, Const.round(2.7, 0, BigDecimal.ROUND_CEILING));
    assertEquals(2.0, Const.round(2.7, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(3.0, Const.round(2.7, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(3.0, Const.round(2.7, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(3.0, Const.round(2.7, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(3.0, Const.round(2.7, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-1.0, Const.round(-1.0, 0, BigDecimal.ROUND_UP));
    assertEquals(-1.0, Const.round(-1.0, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-1.0, Const.round(-1.0, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-1.0, Const.round(-1.0, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-1.0, Const.round(-1.0, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-1.0, Const.round(-1.0, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-1.0, Const.round(-1.0, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-1.0, Const.round(-1.0, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-2.0, Const.round(-1.2, 0, BigDecimal.ROUND_UP));
    assertEquals(-1.0, Const.round(-1.2, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-1.0, Const.round(-1.2, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-2.0, Const.round(-1.2, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-1.0, Const.round(-1.2, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-1.0, Const.round(-1.2, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-1.0, Const.round(-1.2, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-1.0, Const.round(-1.2, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-2.0, Const.round(-1.5, 0, BigDecimal.ROUND_UP));
    assertEquals(-1.0, Const.round(-1.5, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-1.0, Const.round(-1.5, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-2.0, Const.round(-1.5, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-2.0, Const.round(-1.5, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-1.0, Const.round(-1.5, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-2.0, Const.round(-1.5, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-1.0, Const.round(-1.5, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-2.0, Const.round(-1.7, 0, BigDecimal.ROUND_UP));
    assertEquals(-1.0, Const.round(-1.7, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-1.0, Const.round(-1.7, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-2.0, Const.round(-1.7, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-2.0, Const.round(-1.7, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-2.0, Const.round(-1.7, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-2.0, Const.round(-1.7, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-2.0, Const.round(-1.7, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-2.0, Const.round(-2.0, 0, BigDecimal.ROUND_UP));
    assertEquals(-2.0, Const.round(-2.0, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-2.0, Const.round(-2.0, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-2.0, Const.round(-2.0, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-2.0, Const.round(-2.0, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-2.0, Const.round(-2.0, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-2.0, Const.round(-2.0, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-2.0, Const.round(-2.0, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-3.0, Const.round(-2.2, 0, BigDecimal.ROUND_UP));
    assertEquals(-2.0, Const.round(-2.2, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-2.0, Const.round(-2.2, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-3.0, Const.round(-2.2, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-2.0, Const.round(-2.2, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-2.0, Const.round(-2.2, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-2.0, Const.round(-2.2, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-2.0, Const.round(-2.2, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-3.0, Const.round(-2.5, 0, BigDecimal.ROUND_UP));
    assertEquals(-2.0, Const.round(-2.5, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-2.0, Const.round(-2.5, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-3.0, Const.round(-2.5, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-3.0, Const.round(-2.5, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-2.0, Const.round(-2.5, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-2.0, Const.round(-2.5, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-2.0, Const.round(-2.5, 0, Const.ROUND_HALF_CEILING));

    assertEquals(-3.0, Const.round(-2.7, 0, BigDecimal.ROUND_UP));
    assertEquals(-2.0, Const.round(-2.7, 0, BigDecimal.ROUND_DOWN));
    assertEquals(-2.0, Const.round(-2.7, 0, BigDecimal.ROUND_CEILING));
    assertEquals(-3.0, Const.round(-2.7, 0, BigDecimal.ROUND_FLOOR));
    assertEquals(-3.0, Const.round(-2.7, 0, BigDecimal.ROUND_HALF_UP));
    assertEquals(-3.0, Const.round(-2.7, 0, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-3.0, Const.round(-2.7, 0, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-3.0, Const.round(-2.7, 0, Const.ROUND_HALF_CEILING));

    assertEquals(0.010, Const.round(0.010, 2, BigDecimal.ROUND_UP));
    assertEquals(0.010, Const.round(0.010, 2, BigDecimal.ROUND_DOWN));
    assertEquals(0.010, Const.round(0.010, 2, BigDecimal.ROUND_CEILING));
    assertEquals(0.010, Const.round(0.010, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(0.010, Const.round(0.010, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(0.010, Const.round(0.010, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(0.010, Const.round(0.010, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(0.010, Const.round(0.010, 2, Const.ROUND_HALF_CEILING));

    assertEquals(0.020, Const.round(0.012, 2, BigDecimal.ROUND_UP));
    assertEquals(0.010, Const.round(0.012, 2, BigDecimal.ROUND_DOWN));
    assertEquals(0.020, Const.round(0.012, 2, BigDecimal.ROUND_CEILING));
    assertEquals(0.010, Const.round(0.012, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(0.010, Const.round(0.012, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(0.010, Const.round(0.012, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(0.010, Const.round(0.012, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(0.010, Const.round(0.012, 2, Const.ROUND_HALF_CEILING));

    assertEquals(0.020, Const.round(0.015, 2, BigDecimal.ROUND_UP));
    assertEquals(0.010, Const.round(0.015, 2, BigDecimal.ROUND_DOWN));
    assertEquals(0.020, Const.round(0.015, 2, BigDecimal.ROUND_CEILING));
    assertEquals(0.010, Const.round(0.015, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(0.020, Const.round(0.015, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(0.010, Const.round(0.015, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(0.020, Const.round(0.015, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(0.020, Const.round(0.015, 2, Const.ROUND_HALF_CEILING));

    assertEquals(0.020, Const.round(0.017, 2, BigDecimal.ROUND_UP));
    assertEquals(0.010, Const.round(0.017, 2, BigDecimal.ROUND_DOWN));
    assertEquals(0.020, Const.round(0.017, 2, BigDecimal.ROUND_CEILING));
    assertEquals(0.010, Const.round(0.017, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(0.020, Const.round(0.017, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(0.020, Const.round(0.017, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(0.020, Const.round(0.017, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(0.020, Const.round(0.017, 2, Const.ROUND_HALF_CEILING));

    assertEquals(0.020, Const.round(0.020, 2, BigDecimal.ROUND_UP));
    assertEquals(0.020, Const.round(0.020, 2, BigDecimal.ROUND_DOWN));
    assertEquals(0.020, Const.round(0.020, 2, BigDecimal.ROUND_CEILING));
    assertEquals(0.020, Const.round(0.020, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(0.020, Const.round(0.020, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(0.020, Const.round(0.020, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(0.020, Const.round(0.020, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(0.020, Const.round(0.020, 2, Const.ROUND_HALF_CEILING));

    assertEquals(0.030, Const.round(0.022, 2, BigDecimal.ROUND_UP));
    assertEquals(0.020, Const.round(0.022, 2, BigDecimal.ROUND_DOWN));
    assertEquals(0.030, Const.round(0.022, 2, BigDecimal.ROUND_CEILING));
    assertEquals(0.020, Const.round(0.022, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(0.020, Const.round(0.022, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(0.020, Const.round(0.022, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(0.020, Const.round(0.022, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(0.020, Const.round(0.022, 2, Const.ROUND_HALF_CEILING));

    assertEquals(0.030, Const.round(0.025, 2, BigDecimal.ROUND_UP));
    assertEquals(0.020, Const.round(0.025, 2, BigDecimal.ROUND_DOWN));
    assertEquals(0.030, Const.round(0.025, 2, BigDecimal.ROUND_CEILING));
    assertEquals(0.020, Const.round(0.025, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(0.030, Const.round(0.025, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(0.020, Const.round(0.025, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(0.020, Const.round(0.025, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(0.030, Const.round(0.025, 2, Const.ROUND_HALF_CEILING));

    assertEquals(0.030, Const.round(0.027, 2, BigDecimal.ROUND_UP));
    assertEquals(0.020, Const.round(0.027, 2, BigDecimal.ROUND_DOWN));
    assertEquals(0.030, Const.round(0.027, 2, BigDecimal.ROUND_CEILING));
    assertEquals(0.020, Const.round(0.027, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(0.030, Const.round(0.027, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(0.030, Const.round(0.027, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(0.030, Const.round(0.027, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(0.030, Const.round(0.027, 2, Const.ROUND_HALF_CEILING));

    assertEquals(-0.010, Const.round(-0.010, 2, BigDecimal.ROUND_UP));
    assertEquals(-0.010, Const.round(-0.010, 2, BigDecimal.ROUND_DOWN));
    assertEquals(-0.010, Const.round(-0.010, 2, BigDecimal.ROUND_CEILING));
    assertEquals(-0.010, Const.round(-0.010, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(-0.010, Const.round(-0.010, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-0.010, Const.round(-0.010, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-0.010, Const.round(-0.010, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-0.010, Const.round(-0.010, 2, Const.ROUND_HALF_CEILING));

    assertEquals(-0.020, Const.round(-0.012, 2, BigDecimal.ROUND_UP));
    assertEquals(-0.010, Const.round(-0.012, 2, BigDecimal.ROUND_DOWN));
    assertEquals(-0.010, Const.round(-0.012, 2, BigDecimal.ROUND_CEILING));
    assertEquals(-0.020, Const.round(-0.012, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(-0.010, Const.round(-0.012, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-0.010, Const.round(-0.012, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-0.010, Const.round(-0.012, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-0.010, Const.round(-0.012, 2, Const.ROUND_HALF_CEILING));

    assertEquals(-0.020, Const.round(-0.015, 2, BigDecimal.ROUND_UP));
    assertEquals(-0.010, Const.round(-0.015, 2, BigDecimal.ROUND_DOWN));
    assertEquals(-0.010, Const.round(-0.015, 2, BigDecimal.ROUND_CEILING));
    assertEquals(-0.020, Const.round(-0.015, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(-0.020, Const.round(-0.015, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-0.010, Const.round(-0.015, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-0.020, Const.round(-0.015, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-0.010, Const.round(-0.015, 2, Const.ROUND_HALF_CEILING));

    assertEquals(-0.020, Const.round(-0.017, 2, BigDecimal.ROUND_UP));
    assertEquals(-0.010, Const.round(-0.017, 2, BigDecimal.ROUND_DOWN));
    assertEquals(-0.010, Const.round(-0.017, 2, BigDecimal.ROUND_CEILING));
    assertEquals(-0.020, Const.round(-0.017, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(-0.020, Const.round(-0.017, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-0.020, Const.round(-0.017, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-0.020, Const.round(-0.017, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-0.020, Const.round(-0.017, 2, Const.ROUND_HALF_CEILING));

    assertEquals(-0.020, Const.round(-0.020, 2, BigDecimal.ROUND_UP));
    assertEquals(-0.020, Const.round(-0.020, 2, BigDecimal.ROUND_DOWN));
    assertEquals(-0.020, Const.round(-0.020, 2, BigDecimal.ROUND_CEILING));
    assertEquals(-0.020, Const.round(-0.020, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(-0.020, Const.round(-0.020, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-0.020, Const.round(-0.020, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-0.020, Const.round(-0.020, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-0.020, Const.round(-0.020, 2, Const.ROUND_HALF_CEILING));

    assertEquals(-0.030, Const.round(-0.022, 2, BigDecimal.ROUND_UP));
    assertEquals(-0.020, Const.round(-0.022, 2, BigDecimal.ROUND_DOWN));
    assertEquals(-0.020, Const.round(-0.022, 2, BigDecimal.ROUND_CEILING));
    assertEquals(-0.030, Const.round(-0.022, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(-0.020, Const.round(-0.022, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-0.020, Const.round(-0.022, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-0.020, Const.round(-0.022, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-0.020, Const.round(-0.022, 2, Const.ROUND_HALF_CEILING));

    assertEquals(-0.030, Const.round(-0.025, 2, BigDecimal.ROUND_UP));
    assertEquals(-0.020, Const.round(-0.025, 2, BigDecimal.ROUND_DOWN));
    assertEquals(-0.020, Const.round(-0.025, 2, BigDecimal.ROUND_CEILING));
    assertEquals(-0.030, Const.round(-0.025, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(-0.030, Const.round(-0.025, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-0.020, Const.round(-0.025, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-0.020, Const.round(-0.025, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-0.020, Const.round(-0.025, 2, Const.ROUND_HALF_CEILING));

    assertEquals(-0.030, Const.round(-0.027, 2, BigDecimal.ROUND_UP));
    assertEquals(-0.020, Const.round(-0.027, 2, BigDecimal.ROUND_DOWN));
    assertEquals(-0.020, Const.round(-0.027, 2, BigDecimal.ROUND_CEILING));
    assertEquals(-0.030, Const.round(-0.027, 2, BigDecimal.ROUND_FLOOR));
    assertEquals(-0.030, Const.round(-0.027, 2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-0.030, Const.round(-0.027, 2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-0.030, Const.round(-0.027, 2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-0.030, Const.round(-0.027, 2, Const.ROUND_HALF_CEILING));

    assertEquals(100.0, Const.round(100.0, -2, BigDecimal.ROUND_UP));
    assertEquals(100.0, Const.round(100.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(100.0, Const.round(100.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(100.0, Const.round(100.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(100.0, Const.round(100.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(100.0, Const.round(100.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(100.0, Const.round(100.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(100.0, Const.round(100.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(200.0, Const.round(120.0, -2, BigDecimal.ROUND_UP));
    assertEquals(100.0, Const.round(120.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(200.0, Const.round(120.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(100.0, Const.round(120.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(100.0, Const.round(120.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(100.0, Const.round(120.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(100.0, Const.round(120.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(100.0, Const.round(120.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(200.0, Const.round(150.0, -2, BigDecimal.ROUND_UP));
    assertEquals(100.0, Const.round(150.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(200.0, Const.round(150.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(100.0, Const.round(150.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(200.0, Const.round(150.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(100.0, Const.round(150.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200.0, Const.round(150.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(200.0, Const.round(150.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(200.0, Const.round(170.0, -2, BigDecimal.ROUND_UP));
    assertEquals(100.0, Const.round(170.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(200.0, Const.round(170.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(100.0, Const.round(170.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(200.0, Const.round(170.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(200.0, Const.round(170.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200.0, Const.round(170.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(200.0, Const.round(170.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(200.0, Const.round(200.0, -2, BigDecimal.ROUND_UP));
    assertEquals(200.0, Const.round(200.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(200.0, Const.round(200.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(200.0, Const.round(200.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(200.0, Const.round(200.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(200.0, Const.round(200.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200.0, Const.round(200.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(200.0, Const.round(200.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(300.0, Const.round(220.0, -2, BigDecimal.ROUND_UP));
    assertEquals(200.0, Const.round(220.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(300.0, Const.round(220.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(200.0, Const.round(220.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(200.0, Const.round(220.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(200.0, Const.round(220.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200.0, Const.round(220.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(200.0, Const.round(220.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(300.0, Const.round(250.0, -2, BigDecimal.ROUND_UP));
    assertEquals(200.0, Const.round(250.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(300.0, Const.round(250.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(200.0, Const.round(250.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(300.0, Const.round(250.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(200.0, Const.round(250.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(200.0, Const.round(250.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(300.0, Const.round(250.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(300.0, Const.round(270.0, -2, BigDecimal.ROUND_UP));
    assertEquals(200.0, Const.round(270.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(300.0, Const.round(270.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(200.0, Const.round(270.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(300.0, Const.round(270.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(300.0, Const.round(270.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(300.0, Const.round(270.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(300.0, Const.round(270.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-100.0, Const.round(-100.0, -2, BigDecimal.ROUND_UP));
    assertEquals(-100.0, Const.round(-100.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-100.0, Const.round(-100.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-100.0, Const.round(-100.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-100.0, Const.round(-100.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-100.0, Const.round(-100.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-100.0, Const.round(-100.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-100.0, Const.round(-100.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-200.0, Const.round(-120.0, -2, BigDecimal.ROUND_UP));
    assertEquals(-100.0, Const.round(-120.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-100.0, Const.round(-120.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-200.0, Const.round(-120.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-100.0, Const.round(-120.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-100.0, Const.round(-120.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-100.0, Const.round(-120.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-100.0, Const.round(-120.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-200.0, Const.round(-150.0, -2, BigDecimal.ROUND_UP));
    assertEquals(-100.0, Const.round(-150.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-100.0, Const.round(-150.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-200.0, Const.round(-150.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-200.0, Const.round(-150.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-100.0, Const.round(-150.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200.0, Const.round(-150.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-100.0, Const.round(-150.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-200.0, Const.round(-170.0, -2, BigDecimal.ROUND_UP));
    assertEquals(-100.0, Const.round(-170.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-100.0, Const.round(-170.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-200.0, Const.round(-170.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-200.0, Const.round(-170.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-200.0, Const.round(-170.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200.0, Const.round(-170.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-200.0, Const.round(-170.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-200.0, Const.round(-200.0, -2, BigDecimal.ROUND_UP));
    assertEquals(-200.0, Const.round(-200.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-200.0, Const.round(-200.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-200.0, Const.round(-200.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-200.0, Const.round(-200.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-200.0, Const.round(-200.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200.0, Const.round(-200.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-200.0, Const.round(-200.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-300.0, Const.round(-220.0, -2, BigDecimal.ROUND_UP));
    assertEquals(-200.0, Const.round(-220.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-200.0, Const.round(-220.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-300.0, Const.round(-220.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-200.0, Const.round(-220.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-200.0, Const.round(-220.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200.0, Const.round(-220.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-200.0, Const.round(-220.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-300.0, Const.round(-250.0, -2, BigDecimal.ROUND_UP));
    assertEquals(-200.0, Const.round(-250.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-200.0, Const.round(-250.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-300.0, Const.round(-250.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-300.0, Const.round(-250.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-200.0, Const.round(-250.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-200.0, Const.round(-250.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-200.0, Const.round(-250.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(-300.0, Const.round(-270.0, -2, BigDecimal.ROUND_UP));
    assertEquals(-200.0, Const.round(-270.0, -2, BigDecimal.ROUND_DOWN));
    assertEquals(-200.0, Const.round(-270.0, -2, BigDecimal.ROUND_CEILING));
    assertEquals(-300.0, Const.round(-270.0, -2, BigDecimal.ROUND_FLOOR));
    assertEquals(-300.0, Const.round(-270.0, -2, BigDecimal.ROUND_HALF_UP));
    assertEquals(-300.0, Const.round(-270.0, -2, BigDecimal.ROUND_HALF_DOWN));
    assertEquals(-300.0, Const.round(-270.0, -2, BigDecimal.ROUND_HALF_EVEN));
    assertEquals(-300.0, Const.round(-270.0, -2, Const.ROUND_HALF_CEILING));

    assertEquals(Double.NaN, Const.round(Double.NaN, 0, BigDecimal.ROUND_UP));
    assertEquals(Double.NEGATIVE_INFINITY, Const.round(Double.NEGATIVE_INFINITY, 0, BigDecimal.ROUND_UP));
    assertEquals(Double.POSITIVE_INFINITY, Const.round(Double.POSITIVE_INFINITY, 0, BigDecimal.ROUND_UP));
}

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)
 *///w w w .j a  v a  2 s.c o 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.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  w w w.  j a v a  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 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.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  w  w  w .  jav a2 s .  c o m

        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());
                }
            }
        }
    }
}