Example usage for java.math BigDecimal toPlainString

List of usage examples for java.math BigDecimal toPlainString

Introduction

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

Prototype

public String toPlainString() 

Source Link

Document

Returns a string representation of this BigDecimal without an exponent field.

Usage

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

/**
 * Figures out the tolerance for a search. For example, if the user is searching for <code>4.00</code>, this method
 * returns <code>0.005</code> because we shold actually match values which are
 * <code>4 (+/-) 0.005</code> according to the FHIR specs.
 *//*from w w  w.j av a 2s .  co m*/
static BigDecimal calculateFuzzAmount(ParamPrefixEnum cmpValue, BigDecimal theValue) {
    if (cmpValue == ParamPrefixEnum.APPROXIMATE) {
        return theValue.multiply(new BigDecimal(0.1));
    } else {
        String plainString = theValue.toPlainString();
        int dotIdx = plainString.indexOf('.');
        if (dotIdx == -1) {
            return new BigDecimal(0.5);
        }

        int precision = plainString.length() - (dotIdx);
        double mul = Math.pow(10, -precision);
        double val = mul * 5.0d;
        return new BigDecimal(val);
    }
}

From source file:org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveThermostatSetpointCommandClass.java

/**
 * Processes a THERMOSTAT_SETPOINT_REPORT message.
 * @param serialMessage the incoming message to process.
 * @param offset the offset position from which to start message processing.
 * @param endpoint the endpoint or instance number this message is meant for.
 *//*from  w ww.j av  a2s.co  m*/
protected void processThermostatSetpointReport(SerialMessage serialMessage, int offset, int endpoint) {

    int setpointTypeCode = serialMessage.getMessagePayloadByte(offset + 1);
    int scale = (serialMessage.getMessagePayloadByte(offset + 2) >> 3) & 0x03;

    try {
        BigDecimal value = extractValue(serialMessage.getMessagePayload(), offset + 2);

        logger.debug("NODE {}: Thermostat Setpoint report Scale = {}", this.getNode().getNodeId(), scale);
        logger.debug("NODE {}: Thermostat Setpoint Value = {}", this.getNode().getNodeId(), value);

        SetpointType setpointType = SetpointType.getSetpointType(setpointTypeCode);

        if (setpointType == null) {
            logger.error("NODE {}: Unknown Setpoint Type = {}, ignoring report.", this.getNode().getNodeId(),
                    setpointTypeCode);
            return;
        }

        // setpoint type seems to be supported, add it to the list.
        Setpoint setpoint = setpoints.get(setpointType);
        if (setpoint == null) {
            setpoint = new Setpoint(setpointType);
            setpoints.put(setpointType, setpoint);
        }
        setpoint.setInitialised();

        logger.debug("NODE {}: Thermostat Setpoint Report, Type {} ({}), value = {}",
                this.getNode().getNodeId(), setpointType.getLabel(), setpointTypeCode, value.toPlainString());
        ZWaveThermostatSetpointValueEvent zEvent = new ZWaveThermostatSetpointValueEvent(
                this.getNode().getNodeId(), endpoint, setpointType, scale, value);
        this.getController().notifyEventListeners(zEvent);
    } catch (NumberFormatException e) {
        return;
    }
}

From source file:org.opentaps.common.util.UtilCommon.java

/**
 * Reads a simply formatted, single sheet Excel document into a list of <code>Map</code>.
 * @param stream an <code>InputStream</code> of the excel document
 * @param columnNames a List containing the keys to use when mapping the columns into the Map (column 1 goes in the Map key columnNames 1, etc ...)
 * @param skipRows number of rows to skip, typically 1 to skip the header row
 * @return the List of Map representing the rows
 * @throws IOException if an error occurs
 *//*from w  ww .j a  v a2 s  . c o m*/
public static List<Map<String, String>> readExcelFile(InputStream stream, List<String> columnNames,
        int skipRows) throws IOException {
    POIFSFileSystem fs = new POIFSFileSystem(stream);
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    int sheetLastRowNumber = sheet.getLastRowNum();
    List<Map<String, String>> rows = new ArrayList<Map<String, String>>();
    for (int j = skipRows; j <= sheetLastRowNumber; j++) {
        HSSFRow erow = sheet.getRow(j);
        Map<String, String> row = new HashMap<String, String>();
        for (int i = 0; i < columnNames.size(); i++) {
            String columnName = columnNames.get(i);
            HSSFCell cell = erow.getCell(i);
            String s = "";
            if (cell != null) {

                // check if cell contains a number
                BigDecimal bd = null;
                try {
                    double d = cell.getNumericCellValue();
                    bd = BigDecimal.valueOf(d);
                } catch (Exception e) {
                    // do nothing
                }
                if (bd == null) {
                    s = cell.toString().trim();
                } else {
                    // if cell contains number trim the tailing zeros so that for example postal code string
                    // does not appear as a floating point number
                    s = bd.toPlainString();
                    // convert XX.XX000 into XX.XX
                    s = s.replaceFirst("^(-?\\d+\\.0*[^0]+)0*\\s*$", "$1");
                    // convert XX.000 into XX
                    s = s.replaceFirst("^(-?\\d+)\\.0*$", "$1");
                }
            }
            Debug.logInfo("readExcelFile cell (" + j + ", " + i + ") as (" + columnName + ") == " + s, MODULE);
            row.put(columnName, s);
        }
        rows.add(row);
    }
    return rows;
}

From source file:org.yes.cart.payment.impl.PostFinancePaymentGatewayImpl.java

private void populateItems(final Payment payment, final Map<String, String> params) {

    BigDecimal totalItemsGross = Total.ZERO;

    for (final PaymentLine item : payment.getOrderItems()) {
        totalItemsGross = totalItemsGross.add(item.getQuantity().multiply(item.getUnitPrice()));
    }//from   w  ww . j  a v  a 2 s  .  c  o m

    final int it = payment.getOrderItems().size();

    BigDecimal orderDiscountRemainder = Total.ZERO;
    BigDecimal orderDiscountPercent = Total.ZERO;
    final BigDecimal payGross = payment.getPaymentAmount();
    if (payGross.compareTo(totalItemsGross) < 0) {
        orderDiscountRemainder = totalItemsGross.subtract(payGross);
        orderDiscountPercent = orderDiscountRemainder.divide(totalItemsGross, 10, RoundingMode.HALF_UP);
    }

    int i = 1;
    boolean hasOrderDiscount = MoneyUtils.isFirstBiggerThanSecond(orderDiscountRemainder, Total.ZERO);
    for (final PaymentLine item : payment.getOrderItems()) {

        final BigDecimal itemGrossAmount = item.getUnitPrice().multiply(item.getQuantity())
                .setScale(Total.ZERO.scale(), RoundingMode.HALF_UP);
        params.put("ITEMID" + i,
                item.getSkuCode().length() > ITEMID ? item.getSkuCode().substring(0, ITEMID - 1) + "~"
                        : item.getSkuCode());
        params.put("ITEMNAME" + i,
                item.getSkuName().length() > ITEMNAME ? item.getSkuName().substring(0, ITEMNAME - 1) + "~"
                        : item.getSkuName());
        params.put("ITEMQUANT" + i, item.getQuantity().toPlainString());
        if (hasOrderDiscount && MoneyUtils.isFirstBiggerThanSecond(orderDiscountRemainder, Total.ZERO)
                && MoneyUtils.isFirstBiggerThanSecond(itemGrossAmount, Total.ZERO)) {
            BigDecimal discount;
            if (i == it) {
                // last item
                discount = orderDiscountRemainder;
            } else {
                BigDecimal itemDiscount = itemGrossAmount.multiply(orderDiscountPercent)
                        .setScale(Total.ZERO.scale(), RoundingMode.CEILING);
                if (MoneyUtils.isFirstBiggerThanSecond(orderDiscountRemainder, itemDiscount)) {
                    discount = itemDiscount;
                    orderDiscountRemainder = orderDiscountRemainder.subtract(itemDiscount);
                } else {
                    discount = orderDiscountRemainder;
                    orderDiscountRemainder = Total.ZERO;
                }

            }
            final BigDecimal scaleRate = discount.divide(itemGrossAmount.subtract(discount), 10,
                    RoundingMode.CEILING);
            final BigDecimal scaledTax = item.getTaxAmount().multiply(scaleRate).setScale(Total.ZERO.scale(),
                    RoundingMode.FLOOR);
            params.put("ITEMDISCOUNT" + i, discount.toPlainString());
            params.put("ITEMPRICE" + i, itemGrossAmount.subtract(discount).subtract(item.getTaxAmount())
                    .add(scaledTax).toPlainString());
            params.put("ITEMVAT" + i, item.getTaxAmount().subtract(scaledTax).toPlainString());
        } else {
            params.put("ITEMPRICE" + i, itemGrossAmount.subtract(item.getTaxAmount()).toPlainString());
            params.put("ITEMVAT" + i, item.getTaxAmount().toPlainString());
        }
        i++;
    }
}

From source file:au.org.ala.delta.editor.slotfile.directive.DirOutDefault.java

@Override
public void writeDirectiveArguments(DirectiveInOutState state) {

    _deltaWriter.setIndent(2);/*from w w w .  j av  a  2s.  co m*/
    MutableDeltaDataSet dataSet = state.getDataSet();
    Directive curDirective = state.getCurrentDirective().getDirective();
    // Dir directive;
    DirectiveArguments directiveArgs = state.getCurrentDirective().getDirectiveArguments();

    int argType = curDirective.getArgType();
    String temp = "";
    DirectiveType directiveType = state.getCurrentDirective().getType();
    List<Integer> dataList = null;

    int prevNo, curNo;

    List<DirectiveArgument<?>> args = null;

    switch (argType) {
    case DirectiveArgType.DIRARG_NONE:
    case DirectiveArgType.DIRARG_TRANSLATION:
    case DirectiveArgType.DIRARG_INTKEY_INCOMPLETE:
        break;

    case DirectiveArgType.DIRARG_TEXT: // What about multiple lines of text?
        // Should line breaks ALWAYS be
        // preserved?
    case DirectiveArgType.DIRARG_COMMENT: // Will actually be handled within
        // DirComment
        _deltaWriter.setIndent(0);
    case DirectiveArgType.DIRARG_FILE:
    case DirectiveArgType.DIRARG_OTHER:
    case DirectiveArgType.DIRARG_INTERNAL:
        writeText(directiveArgs, argType);
        break;

    case DirectiveArgType.DIRARG_INTEGER:
    case DirectiveArgType.DIRARG_REAL:
        if (directiveArgs.size() > 0) {
            _textBuffer.append(' ');
            _textBuffer.append(directiveArgs.getFirstArgumentValueAsString());
        }
        break;

    case DirectiveArgType.DIRARG_CHAR:
    case DirectiveArgType.DIRARG_ITEM:
        if (directiveArgs.size() > 0) {
            _textBuffer.append(' ');
            curNo = directiveArgs.getFirstArgumentIdAsInt();
            _textBuffer.append(curNo);
        }
        break;

    case DirectiveArgType.DIRARG_CHARLIST:
    case DirectiveArgType.DIRARG_ITEMLIST:
        if (directiveArgs.size() > 0) {
            dataList = new ArrayList<Integer>();
            for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments())
                dataList.add((Integer) vectIter.getId());
            _textBuffer.append(' ');
            appendRange(dataList, ' ', true, _textBuffer);
        }
        break;

    case DirectiveArgType.DIRARG_TEXTLIST:
        // Special handling for "legacy" data, when this was stored as a
        // simple, large
        // text block...
        if (directiveArgs.size() == 1 && directiveArgs.getFirstArgumentIdAsInt() <= 0
                && directiveArgs.getFirstArgumentText().length() > 1) {
            writeText(directiveArgs, DirectiveArgType.DIRARG_TEXT);
            break;
        }
        // Otherwise drop through...
    case DirectiveArgType.DIRARG_CHARTEXTLIST:
    case DirectiveArgType.DIRARG_ITEMTEXTLIST:
    case DirectiveArgType.DIRARG_ITEMFILELIST: {
        writeTextList(dataSet, directiveArgs, argType, temp);
        break;
    }
    case DirectiveArgType.DIRARG_CHARINTEGERLIST:
    case DirectiveArgType.DIRARG_CHARREALLIST:
    case DirectiveArgType.DIRARG_ITEMREALLIST:
        writeNumberList(directiveArgs);
        break;

    case DirectiveArgType.DIRARG_CHARGROUPS:
        for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
            dataList = new ArrayList<Integer>(vectIter.getDataList());
            _textBuffer.append(' ');
            appendRange(dataList, ':', true, _textBuffer);
        }
        break;

    case DirectiveArgType.DIRARG_ITEMCHARLIST:
        writeItemCharacterList(dataSet, directiveArgs, directiveType);
        break;

    case DirectiveArgType.DIRARG_ALLOWED:
        args = directiveArgs.getDirectiveArguments();
        Collections.sort(args);
        for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
            curNo = (Integer) vectIter.getId();
            _textBuffer.append(' ');
            _textBuffer.append(curNo);
            _textBuffer.append(',');

            List<Integer> tmpData = vectIter.getDataList();
            if (tmpData.size() < 3)
                throw new RuntimeException("ED_INTERNAL_ERROR");
            temp = Integer.toString(tmpData.get(0));
            _textBuffer.append(temp + ':');
            temp = Integer.toString(tmpData.get(1));
            _textBuffer.append(temp + ':');
            temp = Integer.toString(tmpData.get(2));
            _textBuffer.append(temp);
        }
        break;

    case DirectiveArgType.DIRARG_KEYSTATE:
        writeKeyStates(dataSet, directiveArgs);
        break;

    case DirectiveArgType.DIRARG_PRESET:
        for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
            curNo = (Integer) vectIter.getId();
            _textBuffer.append(' ');
            _textBuffer.append(curNo);
            _textBuffer.append(',');
            if (vectIter.getData().size() < 2)
                throw new RuntimeException("ED_INTERNAL_ERROR");
            _textBuffer.append(vectIter.getDataList().get(0));
            _textBuffer.append(':');
            _textBuffer.append(vectIter.getDataList().get(1));
        }
        break;

    case DirectiveArgType.DIRARG_INTKEY_ONOFF:
        if (directiveArgs.size() > 0 && directiveArgs.getFirstArgumentValue() != 0.0) {
            _textBuffer.append(' ');
            if (directiveArgs.getFirstArgumentValue() < 0.0)
                _textBuffer.append("Off");
            else if (directiveArgs.getFirstArgumentValue() > 0.0)
                _textBuffer.append("On");
        }
        break;

    case DirectiveArgType.DIRARG_INTKEY_ITEM:
        if (directiveArgs.size() > 0) {
            if (directiveArgs.getFirstArgumentIdAsInt() > 0) {
                _textBuffer.append(' ');
                curNo = directiveArgs.getFirstArgumentIdAsInt();
                _textBuffer.append(curNo);
            } else
                appendKeyword(_textBuffer, directiveArgs.getFirstArgumentText());
        }
        break;

    case DirectiveArgType.DIRARG_KEYWORD_CHARLIST:
    case DirectiveArgType.DIRARG_KEYWORD_ITEMLIST:
    case DirectiveArgType.DIRARG_INTKEY_CHARLIST:
    case DirectiveArgType.DIRARG_INTKEY_ITEMLIST:
        dataList = new ArrayList<Integer>();
        for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
            if ((Integer) vectIter.getId() > 0)
                dataList.add((Integer) vectIter.getId());
            else
                appendKeyword(_textBuffer, vectIter.getText(),
                        (argType == DirectiveArgType.DIRARG_KEYWORD_CHARLIST
                                || argType == DirectiveArgType.DIRARG_KEYWORD_ITEMLIST)
                                && vectIter == directiveArgs.get(0));
        }
        if (dataList.size() > 0) {
            _textBuffer.append(' ');
            appendRange(dataList, ' ', true, _textBuffer);
        }
        break;

    case DirectiveArgType.DIRARG_INTKEY_CHARREALLIST:
        if (directiveArgs.size() > 0) {
            // Will sort all keywords to appear before actual character
            // numbers, and group characters appropriately
            args = directiveArgs.getDirectiveArguments();
            Collections.sort(args);
            curNo = Integer.MAX_VALUE;
            prevNo = Integer.MAX_VALUE;
            dataList = new ArrayList<Integer>();
            BigDecimal curVal = BigDecimal.ZERO;
            BigDecimal prevVal = BigDecimal.ZERO;
            boolean firstChar = true;
            for (int i = 0; i <= args.size(); i++)
            // Note that vectIter is allowed to equal .end()
            // This allows the last value to be handled correctly within the
            // loop.
            // Be careful not to de-reference vectIter when this happens.
            {
                if (i != args.size()) {
                    DirectiveArgument<?> vectIter = args.get(i);
                    curVal = vectIter.getValue();
                    if ((Integer) vectIter.getId() <= 0) {
                        appendKeyword(_textBuffer, vectIter.getText());
                        if (!(curVal.compareTo(BigDecimal.ZERO) < 0.0)) {
                            _textBuffer.append(',');
                            _textBuffer.append(curVal.toPlainString());
                        }
                        continue;
                    }
                    curNo = (Integer) vectIter.getId();
                }
                if (firstChar || (prevNo == curNo - 1 && prevVal.equals(curVal))) {
                    dataList.add(curNo);
                    firstChar = false;
                } else if (dataList.size() > 0) {
                    _textBuffer.append(' ');
                    appendRange(dataList, ' ', false, _textBuffer);
                    if (!(prevVal.compareTo(BigDecimal.ZERO) < 0.0)) {

                        _textBuffer.append(',');
                        _textBuffer.append(prevVal.toPlainString());
                    }
                    dataList = new ArrayList<Integer>();
                    dataList.add(curNo);
                }
                prevNo = curNo;
                prevVal = curVal;
            }
        }
        break;

    case DirectiveArgType.DIRARG_INTKEY_ITEMCHARSET:
        writeIntItemCharSetArgs(argType, directiveArgs, _textBuffer);
        break;

    case DirectiveArgType.DIRARG_INTKEY_ATTRIBUTES:
        writeIntkeyAttributesArgs(directiveArgs, _textBuffer, dataSet);
        break;

    default:
        break;
    }
    outputTextBuffer(0, 2, false);
}

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

public static Map<String, Object> uspsRateInquire(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    Locale locale = (Locale) context.get("locale");

    // check for 0 weight
    BigDecimal shippableWeight = (BigDecimal) context.get("shippableWeight");
    if (shippableWeight.compareTo(BigDecimal.ZERO) == 0) {
        // TODO: should we return an error, or $0.00 ?
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsShippableWeightMustGreaterThanZero", locale));
    }// w  ww . ja v a  2s. c  o  m

    // get the origination ZIP
    String originationZip = null;
    GenericValue productStore = ProductStoreWorker.getProductStore(((String) context.get("productStoreId")),
            delegator);
    if (productStore != null && productStore.get("inventoryFacilityId") != null) {
        GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator,
                productStore.getString("inventoryFacilityId"),
                UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION"));
        if (facilityContactMech != null) {
            try {
                GenericValue shipFromAddress = EntityQuery.use(delegator).from("PostalAddress")
                        .where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne();
                if (shipFromAddress != null) {
                    originationZip = shipFromAddress.getString("postalCode");
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
        }
    }
    if (UtilValidate.isEmpty(originationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineOriginationZip", locale));
    }

    // get the destination ZIP
    String destinationZip = null;
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    if (UtilValidate.isNotEmpty(shippingContactMechId)) {
        try {
            GenericValue shipToAddress = EntityQuery.use(delegator).from("PostalAddress")
                    .where("contactMechId", shippingContactMechId).queryOne();
            if (shipToAddress != null) {
                if (!domesticCountries.contains(shipToAddress.getString("countryGeoId"))) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsRateInquiryOnlyInUsDestinations", locale));
                }
                destinationZip = shipToAddress.getString("postalCode");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (UtilValidate.isEmpty(destinationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineDestinationZip", locale));
    }

    // get the service code
    String serviceCode = null;
    try {
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("shipmentMethodTypeId", (String) context.get("shipmentMethodTypeId"), "partyId",
                        (String) context.get("carrierPartyId"), "roleTypeId",
                        (String) context.get("carrierRoleTypeId"))
                .queryOne();
        if (carrierShipmentMethod != null) {
            serviceCode = carrierShipmentMethod.getString("carrierServiceCode").toUpperCase();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (UtilValidate.isEmpty(serviceCode)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineServiceCode", locale));
    }

    // create the request document
    Document requestDocument = createUspsRequestDocument("RateV2Request", true, delegator,
            shipmentGatewayConfigId, resource);

    // TODO: 70 lb max is valid for Express, Priority and Parcel only - handle other methods
    BigDecimal maxWeight = new BigDecimal("70");
    String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight",
            resource, "shipment.usps.max.estimate.weight", "70");
    try {
        maxWeight = new BigDecimal(maxWeightStr);
    } catch (NumberFormatException e) {
        Debug.logWarning(
                "Error parsing max estimate weight string [" + maxWeightStr + "], using default instead",
                module);
        maxWeight = new BigDecimal("70");
    }

    List<Map<String, Object>> shippableItemInfo = UtilGenerics.checkList(context.get("shippableItemInfo"));
    List<Map<String, BigDecimal>> packages = ShipmentWorker.getPackageSplit(dctx, shippableItemInfo, maxWeight);
    boolean isOnePackage = packages.size() == 1; // use shippableWeight if there's only one package
    // TODO: Up to 25 packages can be included per request - handle more than 25
    for (ListIterator<Map<String, BigDecimal>> li = packages.listIterator(); li.hasNext();) {
        Map<String, BigDecimal> packageMap = li.next();

        BigDecimal packageWeight = isOnePackage ? shippableWeight
                : ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO);
        if (packageWeight.compareTo(BigDecimal.ZERO) == 0) {
            continue;
        }

        Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                requestDocument);
        packageElement.setAttribute("ID", String.valueOf(li.nextIndex() - 1)); // use zero-based index (see examples)

        UtilXml.addChildElementValue(packageElement, "Service", serviceCode, requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipOrigination",
                StringUtils.substring(originationZip, 0, 5), requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipDestination",
                StringUtils.substring(destinationZip, 0, 5), requestDocument);

        BigDecimal weightPounds = packageWeight.setScale(0, BigDecimal.ROUND_FLOOR);
        // for Parcel post, the weight must be at least 1 lb
        if ("PARCEL".equals(serviceCode.toUpperCase()) && (weightPounds.compareTo(BigDecimal.ONE) < 0)) {
            weightPounds = BigDecimal.ONE;
            packageWeight = BigDecimal.ZERO;
        }
        // (packageWeight % 1) * 16 (Rounded up to 0 dp)
        BigDecimal weightOunces = packageWeight.remainder(BigDecimal.ONE).multiply(new BigDecimal("16"))
                .setScale(0, BigDecimal.ROUND_CEILING);

        UtilXml.addChildElementValue(packageElement, "Pounds", weightPounds.toPlainString(), requestDocument);
        UtilXml.addChildElementValue(packageElement, "Ounces", weightOunces.toPlainString(), requestDocument);

        // TODO: handle other container types, package sizes, and machinable packages
        // IMPORTANT: Express or Priority Mail will fail if you supply a Container tag: you will get a message like
        // Invalid container type. Valid container types for Priority Mail are Flat Rate Envelope and Flat Rate Box.
        /* This is an official response from the United States Postal Service:
        The <Container> tag is used to specify the flat rate mailing options, or the type of large or oversized package being mailed.
        If you are wanting to get regular Express Mail rates, leave the <Container> tag empty, or do not include it in the request at all.
         */
        if ("Parcel".equalsIgnoreCase(serviceCode)) {
            UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
        }
        UtilXml.addChildElementValue(packageElement, "Size", "REGULAR", requestDocument);
        UtilXml.addChildElementValue(packageElement, "Machinable", "false", requestDocument);
    }

    // send the request
    Document responseDocument = null;
    try {
        responseDocument = sendUspsRequest("RateV2", 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));
    }

    if (responseDocument == null) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    List<? extends Element> rates = UtilXml.childElementList(responseDocument.getDocumentElement(), "Package");
    if (UtilValidate.isEmpty(rates)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    BigDecimal estimateAmount = BigDecimal.ZERO;
    for (Element packageElement : rates) {
        try {
            Element postageElement = UtilXml.firstChildElement(packageElement, "Postage");
            BigDecimal packageAmount = new BigDecimal(UtilXml.childElementValue(postageElement, "Rate"));
            estimateAmount = estimateAmount.add(packageAmount);
        } catch (NumberFormatException e) {
            Debug.logInfo(e, module);
        }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shippingEstimateAmount", estimateAmount);
    return result;
}

From source file:com.heliumv.api.inventory.InventoryApi.java

/**
 * Mengen &uuml;berpr&uuml;fen</b>
 * <p>Die Gesamtsumme der identity.amount muss ident mit der angegebenen Menge sein<p>
 * <p>Es d&uuml;rfen nur positive Mengen in den identities vorhanden sein.</p>
 * <p>Seriennummernbehaftete Artikel d&uuml;rfen nur die Menge 1.0 haben</p>
 * @param amount/*  w w  w . jav  a2  s .  c om*/
 * @param identities
 * @return
 */
private boolean verifyAmounts(ArtikelDto itemDto, BigDecimal amount, List<IdentityAmountEntry> identities) {
    if (!itemDto.istArtikelSnrOderchargentragend())
        return true;
    if (identities == null || identities.size() == 0) {
        respondBadRequestValueMissing("identities");
        return false;
    }

    BigDecimal amountIdentities = BigDecimal.ZERO;
    for (IdentityAmountEntry entry : identities) {
        if (entry.getAmount() == null) {
            respondBadRequestValueMissing("amount");
            appendBadRequestData(entry.getIdentity(), "amount missing");
            return false;
        }

        if (entry.getAmount().signum() != 1) {
            respondBadRequest("amount", "positive");
            appendBadRequestData(entry.getIdentity(), entry.getAmount().toPlainString());
            return false;
        }

        if (itemDto.isSeriennrtragend()) {
            if (BigDecimal.ONE.compareTo(entry.getAmount()) != 0) {
                respondBadRequest("snr-amount", "1 (is: " + entry.getAmount().toPlainString() + ")");
                return false;
            }
        }

        amountIdentities = amountIdentities.add(entry.getAmount());
    }

    if (amountIdentities.compareTo(amount.abs()) != 0) {
        respondBadRequest("totalamount != identityamount", amount.toPlainString());
        appendBadRequestData("identityamount", amountIdentities.toPlainString());
        return false;
    }

    return true;
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private BigDecimal getEndingSCN() throws SQLException {
    try (ResultSet rs = getLatestSCN.executeQuery()) {
        if (!rs.next()) {
            throw new SQLException("Missing SCN");
        }/*from   w  w  w.  ja  va  2  s .c  om*/
        BigDecimal scn = rs.getBigDecimal(1);
        if (LOG.isDebugEnabled()) {
            LOG.debug(CURRENT_LATEST_SCN_IS, scn.toPlainString());
        }
        return scn;
    }
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.oracle.OracleCDCSource.java

private void startLogMinerUsingGivenSCNs(BigDecimal oldestSCN, BigDecimal endSCN) throws SQLException {
    try {//from  w w  w .j  a va 2  s  . c  o m
        if (LOG.isDebugEnabled()) {
            LOG.debug(TRYING_TO_START_LOG_MINER_WITH_START_SCN_AND_END_SCN, oldestSCN.toPlainString(),
                    endSCN.toPlainString());
        }
        startLogMnrForCommitSCN.setBigDecimal(1, oldestSCN);
        startLogMnrForCommitSCN.setBigDecimal(2, endSCN);
        startLogMnrForCommitSCN.execute();
        if (LOG.isDebugEnabled()) {
            LOG.debug(STARTED_LOG_MINER_WITH_START_SCN_AND_END_SCN, oldestSCN.toPlainString(),
                    endSCN.toPlainString());
        }
    } catch (SQLException ex) {
        LOG.debug("SQLException while starting LogMiner", ex);
        throw ex;
    }
}

From source file:org.openbravo.erpCommon.ad_reports.MInOutTraceReports.java

private String processChilds(VariablesSecureApp vars, String mAttributesetinstanceId, String mProductId,
        String mLocatorId, String strIn, boolean colorbg2, String strmProductIdGlobal,
        Hashtable<String, Integer> calculated, Vector<Integer> count) throws ServletException {
    BigDecimal total = BigDecimal.ZERO;
    BigDecimal totalPedido = BigDecimal.ZERO;
    StringBuffer strHtml = new StringBuffer();

    String strCalculated = mProductId + "&" + mAttributesetinstanceId + "&" + mLocatorId;

    int c = count.get(0).intValue();
    c += 1;/*from  w w  w.  j a  v  a  2s .  c o  m*/
    count.removeAllElements();
    count.add(new Integer(c));
    calculated.put(strCalculated, new Integer(c));

    if (log4j.isDebugEnabled())
        log4j.debug("****** Hashtable.add: " + strCalculated);
    MInOutTraceReportsData[] dataChild = MInOutTraceReportsData.selectChilds(this, vars.getLanguage(),
            mAttributesetinstanceId, mProductId, mLocatorId, strIn.equals("Y") ? "plusQty" : "minusQty",
            strIn.equals("N") ? "minusQty" : "plusQty");
    if (dataChild == null || dataChild.length == 0) {
        return "";
    }
    boolean colorbg = true;

    strHtml.append(insertHeaderHtml(false, "0"));
    for (int i = 0; i < dataChild.length; i++) {

        strHtml.append("<tr style=\"background: ").append((colorbg ? "#CFDDE8" : "#FFFFFF")).append("\">");
        colorbg = !colorbg;

        strHtml.append("<td >\n");
        strHtml.append(getData(dataChild[i], ""));
        strHtml.append("</td>");
        total = total.add(new BigDecimal(dataChild[i].movementqty));
        if (!dataChild[i].quantityorder.equals(""))
            totalPedido = totalPedido.add(new BigDecimal(dataChild[i].quantityorder));

        strHtml.append(insertTotal(total.toPlainString(), dataChild[i].uomName, totalPedido.toPlainString(),
                dataChild[i].productUomName));
        strHtml.append("  </tr>\n");
        if (log4j.isDebugEnabled())
            log4j.debug("****** New line, qty: " + dataChild[i].movementqty + " "
                    + getData(dataChild[i], "TraceSubTable"));
        strHtml.append(processExternalChilds(vars, dataChild[i], strIn, colorbg2, strmProductIdGlobal,
                calculated, count));
    }
    strHtml.append(insertHeaderHtml(true, ""));
    return strHtml.toString();
}