Example usage for java.math BigDecimal subtract

List of usage examples for java.math BigDecimal subtract

Introduction

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

Prototype

public BigDecimal subtract(BigDecimal subtrahend) 

Source Link

Document

Returns a BigDecimal whose value is (this - subtrahend) , and whose scale is max(this.scale(), subtrahend.scale()) .

Usage

From source file:org.egov.wtms.application.service.WaterConnectionDetailsService.java

public BigDecimal getTotalAmountTillPreviousFinYear(WaterConnectionDetails waterConnectionDetails) {
    EgDemand currentDemand = waterTaxUtils.getCurrentDemand(waterConnectionDetails).getDemand();
    BigDecimal balance = ZERO;//from   w  w  w  .  ja  va2 s  .co m
    if (currentDemand != null) {
        List<Object> instVsAmt = connectionDemandService
                .getDmdCollAmtInstallmentWiseUptoPreviousFinYear(currentDemand);
        for (Object object : instVsAmt) {
            Object[] ddObject = (Object[]) object;
            BigDecimal dmdAmt = new BigDecimal((Double) ddObject[2]);
            BigDecimal collAmt = ZERO;
            if (ddObject[2] != null)
                collAmt = new BigDecimal((Double) ddObject[3]);
            balance = balance.add(dmdAmt.subtract(collAmt));
        }
    }
    if (balance.signum() < 0)
        balance = ZERO;
    return balance;
}

From source file:com.autentia.intra.bean.billing.BillBean.java

private void calcTotals(List<Bill> res) {

    BigDecimal valor = new BigDecimal(0);
    BigDecimal valorNoTaxes = new BigDecimal(0);
    for (Bill elem : res) {
        valor = valor.add(elem.getTotal());
        valorNoTaxes = valorNoTaxes.add(elem.getTotalNoTaxes());
    }/*from  w  w w.  j a  v a2 s  . c  o  m*/

    setTotals(valor);
    setTotalsNoTaxes(valorNoTaxes);
    setTotalsTaxes(valor.subtract(valorNoTaxes));
}

From source file:org.openbravo.advpaymentmngt.actionHandler.AddPaymentActionHandler.java

private void addSelectedPSDs(FIN_Payment payment, JSONObject jsonparams, List<String> pdToRemove)
        throws JSONException {
    JSONObject orderInvoiceGrid = jsonparams.getJSONObject("order_invoice");
    JSONArray selectedPSDs = orderInvoiceGrid.getJSONArray("_selection");
    for (int i = 0; i < selectedPSDs.length(); i++) {
        JSONObject psdRow = selectedPSDs.getJSONObject(i);
        String strPSDIds = psdRow.getString("id");
        String strPaidAmount = psdRow.getString("amount");
        BigDecimal paidAmount = new BigDecimal(strPaidAmount);

        boolean isWriteOff = psdRow.getBoolean("writeoff");
        // psdIds can be grouped
        String[] psdIds = strPSDIds.replaceAll(" ", "").split(",");
        List<FIN_PaymentScheduleDetail> psds = getOrderedPaymentScheduleDetails(psdIds);
        BigDecimal outstandingAmount = BigDecimal.ZERO;
        BigDecimal remainingAmount = paidAmount;
        for (FIN_PaymentScheduleDetail psd : psds) {
            BigDecimal assignAmount = BigDecimal.ZERO;

            if (psd.getPaymentDetails() != null) {
                // This schedule detail comes from an edited payment so outstanding amount needs to be
                // properly calculated
                List<FIN_PaymentScheduleDetail> outStandingPSDs = FIN_AddPayment.getOutstandingPSDs(psd);
                if (outStandingPSDs.size() > 0) {
                    outstandingAmount = psd.getAmount().add(outStandingPSDs.get(0).getAmount());
                } else {
                    outstandingAmount = psd.getAmount();
                }/*from  w  w w. j av a 2s  .c o m*/
                pdToRemove.remove(psd.getPaymentDetails().getId());
            } else {
                outstandingAmount = psd.getAmount();
            }
            // Manage negative amounts
            if ((remainingAmount.signum() > 0 && remainingAmount.compareTo(outstandingAmount) >= 0)
                    || ((remainingAmount.signum() < 0 && outstandingAmount.signum() < 0)
                            && (remainingAmount.compareTo(outstandingAmount) <= 0))) {
                assignAmount = outstandingAmount;
                remainingAmount = remainingAmount.subtract(outstandingAmount);
            } else {
                assignAmount = remainingAmount;
                remainingAmount = BigDecimal.ZERO;
            }
            FIN_AddPayment.updatePaymentDetail(psd, payment, assignAmount, isWriteOff);
        }
    }
}

From source file:org.openbravo.advpaymentmngt.ad_actionbutton.ProcessInvoice.java

private FieldProvider[] getCreditPayments(Invoice invoice) {
    FieldProvider[] data = FieldProviderFactory.getFieldProviderArray(creditPayments);
    String dateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
            .getProperty("dateFormat.java");
    SimpleDateFormat dateFormater = new SimpleDateFormat(dateFormat);

    BigDecimal pendingToPay = invoice.getGrandTotalAmount();
    try {// w  w w  .j a  va  2s.  c  om
        OBContext.setAdminMode(true);
        for (int i = 0; i < data.length; i++) {
            FieldProviderFactory.setField(data[i], "finCreditPaymentId", creditPayments.get(i).getId());
            FieldProviderFactory.setField(data[i], "documentNo", creditPayments.get(i).getDocumentNo());
            FieldProviderFactory.setField(data[i], "paymentDescription",
                    creditPayments.get(i).getDescription());
            if (creditPayments.get(i).getPaymentDate() != null) {
                FieldProviderFactory.setField(data[i], "documentDate",
                        dateFormater.format(creditPayments.get(i).getPaymentDate()).toString());
            }

            final BigDecimal outStandingAmt = creditPayments.get(i).getGeneratedCredit()
                    .subtract(creditPayments.get(i).getUsedCredit());
            FieldProviderFactory.setField(data[i], "outstandingAmount", outStandingAmt.toString());

            FieldProviderFactory.setField(data[i], "paymentAmount",
                    pendingToPay.compareTo(outStandingAmt) > 0 ? outStandingAmt.toString()
                            : (pendingToPay.compareTo(BigDecimal.ZERO) > 0 ? pendingToPay.toString() : ""));
            pendingToPay = pendingToPay.subtract(outStandingAmt);

            FieldProviderFactory.setField(data[i], "finSelectedCreditPaymentId",
                    "".equals(data[i].getField("paymentAmount")) ? "" : creditPayments.get(i).getId());
            FieldProviderFactory.setField(data[i], "rownum", String.valueOf(i));
        }
    } finally {
        OBContext.restorePreviousMode();
    }

    return data;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The integer root.// w  w  w . jav a2  s  .c  o  m
 *
 * @param n the positive argument.
 * @param x the non-negative argument.
 * @return The n-th root of the BigDecimal rounded to the precision implied by x, x^(1/n).
 */
static public BigDecimal root(final int n, final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        throw new ArithmeticException("negative argument " + x.toString() + " of root");
    }
    if (n <= 0) {
        throw new ArithmeticException("negative power " + n + " of root");
    }
    if (n == 1) {
        return x;
    }
    /* start the computation from a double precision estimate */
    BigDecimal s = new BigDecimal(Math.pow(x.doubleValue(), 1.0 / n));
    /* this creates nth with nominal precision of 1 digit
     */
    final BigDecimal nth = new BigDecimal(n);
    /* Specify an internal accuracy within the loop which is
     * slightly larger than what is demanded by eps below.
     */
    final BigDecimal xhighpr = scalePrec(x, 2);
    MathContext mc = new MathContext(2 + x.precision());
    /* Relative accuracy of the result is eps.
     */
    final double eps = x.ulp().doubleValue() / (2 * n * x.doubleValue());
    for (;;) {
        /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being
         * smaller than the precision requested. The relative correction is (1-x/s^n)/n,
         */
        BigDecimal c = xhighpr.divide(s.pow(n - 1), mc);
        c = s.subtract(c);
        MathContext locmc = new MathContext(c.precision());
        c = c.divide(nth, locmc);
        s = s.subtract(c);
        if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) {
            break;
        }
    }
    return s.round(new MathContext(err2prec(eps)));
}

From source file:org.ofbiz.order.shoppingcart.CheckOutHelper.java

/**
 * Validates payment methods.//w w w .  j  a va  2s.co m
 * <p>
 * SCIPIO: WARN: The stock code in this method does not only check the validity of current pay methods in cart; it
 * also updates pay meth amounts for those that were previously left null.
 * <p>
 * SCIPIO: NOTE: Logic must reflect that of {@link ShoppingCart#isPaymentAdequate()}.
 */
public Map<String, Object> validatePaymentMethods() {
    String errMsg = null;
    String billingAccountId = cart.getBillingAccountId();
    BigDecimal billingAccountAmt = cart.getBillingAccountAmount();
    BigDecimal availableAmount = this.availableAccountBalance(billingAccountId);
    if (billingAccountAmt.compareTo(availableAmount) > 0) {
        Debug.logError("Billing account " + billingAccountId + " has [" + availableAmount
                + "] available but needs [" + billingAccountAmt + "] for this order", module);
        Map<String, String> messageMap = UtilMisc.toMap("billingAccountId", billingAccountId);
        errMsg = UtilProperties.getMessage(resource_error, "checkevents.not_enough_available_on_account",
                messageMap, (cart != null ? cart.getLocale() : Locale.getDefault()));
        return ServiceUtil.returnError(errMsg);
    }

    // payment by billing account only requires more checking
    List<String> paymentMethods = cart.getPaymentMethodIds();

    // SCIPIO: Patched: We want to consider the pay meths that have no paymentMethodIds!
    // WARN: we are changing the definition of paymentMethods by doing this; some code may need to use paymentMethodsWithPaymentMethodId instead
    List<String> paymentMethodsWithPaymentMethodId = cart.getPaymentMethodIds();
    paymentMethods.addAll(cart.getPaymentMethodTypeIdsNoPaymentMethodIds()); // add offline, cod, etc, so they can auto calculate totals

    List<String> paymentTypes = cart.getPaymentMethodTypeIds();
    if (paymentTypes.contains("EXT_BILLACT") && paymentTypes.size() == 1 && (paymentMethods.size() == 0
            || (paymentMethods.size() == 1 && paymentMethods.contains("EXT_BILLACT")))) { // SCIPIO: length 1 check added
        if (cart.getGrandTotal().compareTo(availableAmount) > 0) {
            errMsg = UtilProperties.getMessage(resource_error,
                    "checkevents.insufficient_credit_available_on_account",
                    (cart != null ? cart.getLocale() : Locale.getDefault()));
            return ServiceUtil.returnError(errMsg);
        }
    }

    // validate any gift card balances
    this.validateGiftCardAmounts();

    // update the selected payment methods amount with valid numbers
    if (paymentMethods != null) {
        List<String> nullPaymentIds = new ArrayList<String>();
        for (String paymentMethodId : paymentMethods) {
            BigDecimal paymentAmount = cart.getPaymentAmount(paymentMethodId);
            if (paymentAmount == null || paymentAmount.compareTo(BigDecimal.ZERO) == 0) {
                if (Debug.verboseOn())
                    Debug.logVerbose("Found null paymentMethodId - " + paymentMethodId, module);
                nullPaymentIds.add(paymentMethodId);
            }
        }
        for (String paymentMethodId : nullPaymentIds) {
            BigDecimal selectedPaymentTotal = cart.getPaymentTotal();
            BigDecimal requiredAmount = cart.getGrandTotal();
            BigDecimal newAmount = requiredAmount.subtract(selectedPaymentTotal);
            boolean setOverflow = false;

            ShoppingCart.CartPaymentInfo info = cart.getPaymentInfo(paymentMethodId);

            if (Debug.verboseOn())
                Debug.logVerbose("Remaining total is - " + newAmount, module);
            if (newAmount.compareTo(BigDecimal.ZERO) > 0) {
                info.amount = newAmount;
                if (Debug.verboseOn())
                    Debug.logVerbose("Set null paymentMethodId - " + info.paymentMethodId + " / " + info.amount,
                            module);
            } else {
                info.amount = BigDecimal.ZERO;
                if (Debug.verboseOn())
                    Debug.logVerbose("Set null paymentMethodId - " + info.paymentMethodId + " / " + info.amount,
                            module);
            }
            if (!setOverflow) {
                info.overflow = setOverflow = true;
                if (Debug.verboseOn())
                    Debug.logVerbose("Set overflow flag on payment - " + info.paymentMethodId, module);
            }
        }
    }

    // verify the selected payment method amounts will cover the total
    BigDecimal reqAmtPreParse = cart.getGrandTotal().subtract(cart.getBillingAccountAmount());
    BigDecimal selectedPmnt = cart.getPaymentTotal();

    BigDecimal selectedPaymentTotal = selectedPmnt.setScale(scale, rounding);
    BigDecimal requiredAmount = reqAmtPreParse.setScale(scale, rounding);

    if (UtilValidate.isNotEmpty(paymentMethods) && requiredAmount.compareTo(selectedPaymentTotal) > 0) {
        Debug.logError("Required Amount : " + requiredAmount + " / Selected Amount : " + selectedPaymentTotal,
                module);
        errMsg = UtilProperties.getMessage(resource_error, "checkevents.payment_not_cover_this_order",
                (cart != null ? cart.getLocale() : Locale.getDefault()));
        return ServiceUtil.returnError(errMsg);
    }
    if (UtilValidate.isNotEmpty(paymentMethods) && requiredAmount.compareTo(selectedPaymentTotal) < 0) {
        BigDecimal changeAmount = selectedPaymentTotal.subtract(requiredAmount);
        if (!paymentTypes.contains("CASH")) {
            Debug.logError("Change Amount : " + changeAmount + " / No cash.", module);
            // SCIPIO: Use less cryptic message
            //errMsg = UtilProperties.getMessage(resource_error, "checkhelper.change_returned_cannot_be_greater_than_cash", (cart != null ? cart.getLocale() : Locale.getDefault()));
            errMsg = UtilProperties.getMessage(resource_error,
                    "checkevents.payment_cannot_be_greater_than_order",
                    (cart != null ? cart.getLocale() : Locale.getDefault()));
            return ServiceUtil.returnError(errMsg);
        } else {
            int cashIndex = paymentTypes.indexOf("CASH");
            String cashId = paymentTypes.get(cashIndex);
            BigDecimal cashAmount = cart.getPaymentAmount(cashId);
            if (cashAmount.compareTo(changeAmount) < 0) {
                Debug.logError("Change Amount : " + changeAmount + " / Cash Amount : " + cashAmount, module);
                // SCIPIO: Use less cryptic message
                //errMsg = UtilProperties.getMessage(resource_error, "checkhelper.change_returned_cannot_be_greater_than_cash", (cart != null ? cart.getLocale() : Locale.getDefault()));
                errMsg = UtilProperties.getMessage(resource_error,
                        "checkevents.payment_cannot_be_greater_than_order",
                        (cart != null ? cart.getLocale() : Locale.getDefault()));
                return ServiceUtil.returnError(errMsg);
            }
        }
    }
    return ServiceUtil.returnSuccess();
}

From source file:com.github.jonmarsh.waveform_processing_for_imagej.WaveformUtils.java

/**
 * Extra precise sqrt function for use with BigDecimal class. Uses Newton's
 * method to roughly double the number of significant digits of typical
 * floating-point sqrt function. (This gem was found on StackOverflow.com)
 *
 * @param value//  w  w  w .  j ava 2  s .co  m
 * @param mc
 * @return square root of {@code value}
 */
public static final BigDecimal sqrt(BigDecimal value, MathContext mc) {
    BigDecimal x = new BigDecimal(Math.sqrt(value.doubleValue()), mc);
    return x.add(new BigDecimal(value.subtract(x.multiply(x)).doubleValue() / (x.doubleValue() * 2.0), mc));
}

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

/**
 * {@inheritDoc}//from ww w .  j  a v a  2 s  .c  o m
 */
public String getHtmlForm(final String cardHolderName, final String locale, final BigDecimal amount,
        final String currencyCode, final String orderReference, final Payment payment) {

    final StringBuilder form = new StringBuilder();

    form.append(getHiddenFieldValue("button", "buynow"));
    form.append(getHiddenFieldValue("cmd", "_cart"));
    form.append(getHiddenFieldValue("upload", "1"));
    form.append(getHiddenFieldValue("paymentaction", "sale"));

    form.append(getHiddenFieldParam("business", PPB_USER));
    form.append(getHiddenFieldParam("env", PPB_ENVIRONMENT));
    form.append(getHiddenFieldParam("notify_url", PPB_NOTIFYURL));
    form.append(getHiddenFieldParam("return", PPB_RETURNURL));
    form.append(getHiddenFieldParam("cancel_return", PPB_CANCELURL));

    form.append(getHiddenFieldValue("currency_code", currencyCode));
    form.append(getHiddenFieldValue("invoice", orderReference));
    form.append(getHiddenFieldValue("custom", orderReference));

    form.append(getHiddenFieldValue("lc", paymentLocaleTranslator.translateLocale(this, locale)));
    form.append(getHiddenFieldValue("charset", "UTF-8"));

    if (payment.getBillingAddress() != null) {
        form.append(getHiddenFieldValue("first_name", payment.getBillingAddress().getFirstname()));
        form.append(getHiddenFieldValue("last_name", payment.getBillingAddress().getLastname()));
        form.append(getHiddenFieldValue("email", payment.getBillingEmail()));
    }
    if (payment.getShippingAddress() != null) {
        form.append(getHiddenFieldValue("address1", payment.getShippingAddress().getAddrline1()));
        form.append(getHiddenFieldValue("address2", payment.getShippingAddress().getAddrline2()));
        form.append(getHiddenFieldValue("city", payment.getShippingAddress().getCity()));
        form.append(getHiddenFieldValue("country", payment.getShippingAddress().getCountryCode()));
        form.append(getHiddenFieldValue("state", payment.getShippingAddress().getStateCode()));
        form.append(getHiddenFieldValue("zip", payment.getShippingAddress().getPostcode()));
        form.append(getHiddenFieldValue("address_override", "1"));
    }

    BigDecimal totalItems = Total.ZERO;

    int i = 1;
    for (final PaymentLine item : payment.getOrderItems()) {
        form.append(getHiddenFieldValue("item_name_" + i, item.getSkuName()));
        form.append(getHiddenFieldValue("item_number_" + i, item.getSkuCode()));
        // PayPal can only handle whole values, so do ceil
        final BigDecimal ppQty = item.getQuantity().setScale(0, BigDecimal.ROUND_CEILING);
        form.append(getHiddenFieldValue("quantity_" + i, ppQty.toPlainString()));

        final BigDecimal taxUnit = MoneyUtils.isFirstBiggerThanSecond(item.getTaxAmount(), Total.ZERO)
                ? item.getTaxAmount().divide(item.getQuantity(), Total.ZERO.scale(), RoundingMode.HALF_UP)
                : Total.ZERO;
        final BigDecimal itemAmount = item.getUnitPrice().subtract(taxUnit);
        form.append(getHiddenFieldValue("amount_" + i, itemAmount.toPlainString()));
        //            form.append(getHiddenFieldValue("tax_" + i, taxUnit.setScale(Total.ZERO.scale(), RoundingMode.HALF_UP).toPlainString()));
        if (ppQty.compareTo(item.getQuantity()) != 0) {
            // If we have decimals in qty need to save it as item option
            form.append(getHiddenFieldValue("on0_" + i, "x"));
            form.append(getHiddenFieldValue("on1_" + i, item.getQuantity().toPlainString()));
        }
        i++;
        totalItems = totalItems.add(itemAmount.multiply(item.getQuantity()));
    }

    final BigDecimal payNet = payment.getPaymentAmount().subtract(payment.getTaxAmount());
    if (payNet.compareTo(totalItems) < 0) {
        form.append(getHiddenFieldValue("discount_amount_cart", totalItems.subtract(payNet)
                .setScale(Total.ZERO.scale(), RoundingMode.HALF_UP).toPlainString()));
    }
    form.append(getHiddenFieldValue("tax_cart", payment.getTaxAmount().toPlainString()));

    return form.toString();
}

From source file:com.opengamma.bloombergexample.loader.DemoEquityOptionCollarPortfolioLoader.java

private void addNodes(ManageablePortfolioNode rootNode, String underlying, boolean includeUnderlying,
        Period[] expiries) {//from  ww w  . j a v  a2  s  .c o  m
    ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying);
    ManageableSecurity underlyingSecurity = null;
    if (includeUnderlying) {
        underlyingSecurity = getOrLoadEquity(ticker);
    }

    ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker)
            : underlyingSecurity.getExternalIdBundle();
    HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle);
    double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo);
    Set<ExternalId> optionChain = getOptionChain(ticker);

    //TODO: reuse positions/nodes?
    String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName();
    String formattedName = MessageFormatter.format("[{}] {}", underlying, longName);
    ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName);

    BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike),
            BigDecimal.ROUND_HALF_EVEN);

    if (includeUnderlying) {
        addPosition(equityNode, underlyingAmount, ticker);
    }

    TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>();
    for (ExternalId optionTicker : optionChain) {
        s_logger.debug("Got option {}", optionTicker);

        BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker);
        s_logger.debug("Got option info {}", optionInfo);

        LocalDate key = optionInfo.getExpiry();
        Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key);
        if (set == null) {
            set = new HashSet<BloombergTickerParserEQOption>();
            optionsByExpiry.put(key, set);
        }
        set.add(optionInfo);
    }
    Set<ExternalId> tickersToLoad = new HashSet<ExternalId>();

    BigDecimal expiryCount = BigDecimal.valueOf(expiries.length);
    BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN);
    BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE);
    int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue();

    for (int i = 0; i < expiries.length; i++) {
        Period bucketPeriod = expiries[i];

        ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1));

        LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run
        LocalDate targetExpiry = nowish.plus(bucketPeriod);
        LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry);
        if (chosenExpiry == null) {
            s_logger.warn("No options for {} on {}", targetExpiry, underlying);
            continue;
        }
        s_logger.info("Using time {} for bucket {} ({})",
                new Object[] { chosenExpiry, bucketPeriod, targetExpiry });

        Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry);
        TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (BloombergTickerParserEQOption option : optionsAtExpiry) {
            //        s_logger.info("option {}", option);
            double key = option.getStrike();
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key);
            if (pair == null) {
                pair = Pair.of(null, null);
            }
            if (option.getOptionType() == OptionType.CALL) {
                pair = Pair.of(option, pair.getSecond());
            } else {
                pair = Pair.of(pair.getFirst(), option);
            }
            optionsByStrike.put(key, pair);
        }

        //cascading collar?
        BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry;

        s_logger.info(" est strike {}", estimatedCurrentStrike);
        Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]);

        int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike);
        if (strikeIndex < 0) {
            strikeIndex = -(1 + strikeIndex);
        }
        s_logger.info("strikes length {} index {} strike of index {}",
                new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex),
                        Double.valueOf(strikes[strikeIndex]) });

        int minIndex = strikeIndex - _numOptions;
        minIndex = Math.max(0, minIndex);
        int maxIndex = strikeIndex + _numOptions;
        maxIndex = Math.min(strikes.length - 1, maxIndex);

        s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex));
        StringBuffer sb = new StringBuffer("strikes: [");
        for (int j = minIndex; j <= maxIndex; j++) {
            sb.append(" ");
            sb.append(strikes[j]);
        }
        sb.append(" ]");
        s_logger.info(sb.toString());

        //Short Calls
        ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = minIndex; j < strikeIndex; j++) {
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            calls.add(pair);
        }
        spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying,
                calls.size());

        // Long Puts
        ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>();
        for (int j = strikeIndex + 1; j <= maxIndex; j++) {
            Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike
                    .get(strikes[j]);
            if (pair == null) {
                throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]);
            }
            puts.add(pair);
        }
        spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying,
                puts.size());

        if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) {
            equityNode.addChildNode(bucketNode); //Avoid generating empty nodes   
        }
    }

    for (ExternalId optionTicker : tickersToLoad) {
        ManageableSecurity loaded = getOrLoadSecurity(optionTicker);
        if (loaded == null) {
            throw new OpenGammaRuntimeException("Unexpected option type " + loaded);
        }

        //TODO [LAPANA-29] Should be able to do this for index options too
        if (includeUnderlying) {
            try {
                HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker,
                        loaded.getExternalIdBundle());
                if (loadedTs == null) {
                    throw new OpenGammaRuntimeException("Failed to get time series for " + loaded);
                }
            } catch (Exception ex) {
                s_logger.error("Failed to get time series for " + loaded, ex);
            }
        }
    }

    if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) {
        rootNode.addChildNode(equityNode);
    }
}

From source file:org.egov.works.web.actions.measurementbook.MeasurementBookAction.java

private BigDecimal getAmountsForCurrentMB(final List<MBDetails> mbDetailsList, final double negoPerc,
        final String tenderType) {

    BigDecimal currentMBTenderedAmt = BigDecimal.ZERO;
    BigDecimal currMBAmount = BigDecimal.ZERO;
    BigDecimal tenderedMBAmount = BigDecimal.ZERO;
    BigDecimal currMBTotal = BigDecimal.ZERO;

    if (tenderType.equalsIgnoreCase(WorksConstants.PERC_TENDER)) {
        for (final MBDetails mbd : mbDetailsList)
            if (mbd.getWorkOrderActivity().getActivity().getRevisionType() == null)
                currentMBTenderedAmt = currentMBTenderedAmt.add(BigDecimal.valueOf(mbd.getAmount()));
        currMBAmount = mbHeader.getTotalMBAmount();

        // applying percentage on tendered items
        if (currentMBTenderedAmt != null)
            tenderedMBAmount = currentMBTenderedAmt
                    .add(currentMBTenderedAmt.multiply(BigDecimal.valueOf(negoPerc / 100)));
        // adding tendered amount with the non tendered items amount, to get
        // the total mb amount
        currMBTotal = tenderedMBAmount.add(currMBAmount.subtract(currentMBTenderedAmt));
    } else//w w w.j  av  a 2  s.c  o  m
        currMBTotal = mbHeader.getTotalMBAmount();

    return currMBTotal.setScale(2, RoundingMode.HALF_UP);
}