Example usage for java.math BigDecimal doubleValue

List of usage examples for java.math BigDecimal doubleValue

Introduction

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

Prototype

@Override
public double doubleValue() 

Source Link

Document

Converts this BigDecimal to a double .

Usage

From source file:com.salesmanager.central.cart.AddProduct.java

/**
 * Synchronize Session objects with passed parameters
 * Validates input parameters/*from ww  w. j  a  v  a 2  s.  co  m*/
 * Then delegates to OrderService for OrderTotalSummary calculation
 * @param products
 */
public OrderTotalSummary calculate(OrderProduct[] products, ShippingInformation shippingMethodLine) {

    //subtotal
    //quantity
    //tax
    //shipping
    //handling
    //other prices

    HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();

    Context ctx = (Context) req.getSession().getAttribute(ProfileConstants.context);

    Order order = SessionUtil.getOrder(req);

    String currency = null;

    try {

        MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
        MerchantStore store = mservice.getMerchantStore(ctx.getMerchantid());

        currency = store.getCurrency();

        if (order != null && !StringUtils.isBlank(order.getCurrency())) {
            currency = order.getCurrency();
        }

    } catch (Exception e) {
        log.error(e);
    }

    OrderTotalSummary total = new OrderTotalSummary(currency);

    Customer customer = SessionUtil.getCustomer(req);

    Locale locale = LocaleUtil.getLocale(req);

    //Shipping
    ShippingInformation shippingInfo = SessionUtil.getShippingInformation(req);

    Shipping shipping = null;

    if (shippingInfo == null) {
        shippingInfo = new ShippingInformation();
    }

    if (shippingMethodLine != null && shippingMethodLine.getShippingMethodId() == null) {//reset shipping
        //shippingMethodLine = new ShippingInformation();

        if (req.getSession().getAttribute("PRODUCTLOADED") != null) {
            shipping = new Shipping();
            shipping.setHandlingCost(shippingInfo.getHandlingCost());
            shipping.setShippingCost(shippingInfo.getShippingCost());
            shipping.setShippingDescription(shippingInfo.getShippingMethod());
            shipping.setShippingModule(shippingInfo.getShippingModule());
            req.getSession().removeAttribute("PRODUCTLOADED");

        } else {

            shippingInfo.setShippingCostText(
                    CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal("0"), ctx.getCurrency()));
            shippingInfo.setShippingMethodId(null);
            shippingInfo.setShippingMethod(null);
            shippingInfo.setShippingCost(new BigDecimal("0"));
            try {
                SessionUtil.removeShippingInformation(req);
            } catch (Exception e) {
                log.error(e);
            }

        }

    } else { //retreive shipping info in http session
        shipping = new Shipping();
        Map shippingOptionsMap = SessionUtil.getShippingMethods(req);
        String method = shippingMethodLine.getShippingMethodId();

        if (shippingInfo.getShippingCost() != null && shippingInfo.getShippingMethod() != null) {

            shipping.setHandlingCost(shippingInfo.getHandlingCost());
            shipping.setShippingCost(shippingInfo.getShippingCost());
            shipping.setShippingDescription(shippingInfo.getShippingMethod());
            shipping.setShippingModule(shippingInfo.getShippingModule());

        } else {

            if (shippingOptionsMap == null || method == null) {
                shippingMethodLine.setShippingCostText(
                        CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal("0"), ctx.getCurrency()));
                shippingInfo = shippingMethodLine;
            } else {//after a selection
                //retreive shipping option
                ShippingOption option = (ShippingOption) shippingOptionsMap.get(method);

                //get the latest shipping information (handling, free ...)

                shippingInfo.setShippingMethodId(option.getOptionId());
                shippingInfo.setShippingOptionSelected(option);
                shippingInfo.setShippingMethod(option.getDescription());

                shippingInfo.setShippingCost(option.getOptionPrice());
                shippingInfo.setShippingModule(option.getModule());

                shipping.setHandlingCost(shippingInfo.getHandlingCost());
                shipping.setShippingCost(shippingInfo.getShippingCost());
                shipping.setShippingDescription(option.getDescription());
                shipping.setShippingModule(option.getModule());

                //total.setShipping(true);

            }

        }
    }

    List productList = new ArrayList();

    try {

        //validate numeric quantity

        //validate numeric price
        if (products != null) {

            //get products from httpsession
            Map savedOrderProducts = SessionUtil.getOrderProducts(req);
            Map currentProducts = new HashMap();

            if (savedOrderProducts == null) {
                savedOrderProducts = SessionUtil.createSavedOrderProducts(req);
            }

            total.setOrderProducts(products);

            if (order == null) {
                log.error("No order exist for the price calculation");
                total.setErrorMessage(LabelUtil.getInstance().getText(locale, "messages.genericmessage"));
                return total;
            }

            //validates amounts
            BigDecimal oneTimeSubTotal = total.getOneTimeSubTotal();

            for (int i = 0; i < products.length; i++) {
                OrderProduct product = products[i];

                currentProducts.put(String.valueOf(product.getLineId()), product);

                //get the original line
                OrderProduct oproduct = (OrderProduct) savedOrderProducts
                        .get(String.valueOf(product.getLineId()));

                if (oproduct == null) {
                    oproduct = this.createOrderProduct(product.getProductId());
                }

                if (product.getProductQuantity() > oproduct.getProductQuantityOrderMax()) {
                    product.setProductQuantity(oproduct.getProductQuantityOrderMax());
                }

                productList.add(oproduct);

                //check that productid match
                if (product.getProductId() != oproduct.getProductId()) {//set an error message
                    oproduct.setErrorMessage(
                            LabelUtil.getInstance().getText(locale, "messages.invoice.product.invalid"));
                    oproduct.setPriceText("0");
                    oproduct.setProductPrice(new BigDecimal(0));
                    oproduct.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal(0),
                            ctx.getCurrency()));
                    continue;
                }

                //validate and set the final price
                try {
                    product.setPriceErrorMessage(null);//reset any error message
                    product.setErrorMessage(null);
                    //set price submited
                    BigDecimal price = CurrencyUtil.validateCurrency(product.getPriceText(), ctx.getCurrency());
                    oproduct.setPriceText(product.getPriceText());
                    oproduct.setProductPrice(price);
                    oproduct.setPriceFormated(
                            CurrencyUtil.displayFormatedAmountWithCurrency(price, ctx.getCurrency()));
                    oproduct.setProductQuantity(product.getProductQuantity());
                    oproduct.setPriceErrorMessage(null);
                    oproduct.setErrorMessage(null);

                    double finalPrice = price.doubleValue() * product.getProductQuantity();
                    BigDecimal bdFinalPrice = new BigDecimal(finalPrice);

                    //price calculated
                    oproduct.setCostText(
                            CurrencyUtil.displayFormatedAmountWithCurrency(bdFinalPrice, ctx.getCurrency()));
                    oproduct.setFinalPrice(bdFinalPrice);

                } catch (NumberFormatException nfe) {
                    oproduct.setPriceErrorMessage(
                            LabelUtil.getInstance().getText(locale, "messages.price.invalid"));
                    oproduct.setPriceText("0");
                    oproduct.setProductPrice(new BigDecimal(0));
                    oproduct.setCostText(CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal(0),
                            ctx.getCurrency()));
                    oproduct.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal(0),
                            ctx.getCurrency()));
                    //set shipping to 0
                    ShippingInformation info = new ShippingInformation();
                    shippingMethodLine.setShippingCostText(CurrencyUtil
                            .displayFormatedAmountWithCurrency(new BigDecimal("0"), ctx.getCurrency()));
                    total.setShippingLine(info);
                    total.setShippingTotal(new BigDecimal("0"));

                } catch (com.opensymphony.xwork2.validator.ValidationException e) {
                    oproduct.setPriceErrorMessage(
                            LabelUtil.getInstance().getText(locale, "messages.price.invalid"));
                    oproduct.setPriceText("0");
                    oproduct.setProductPrice(new BigDecimal(0));
                    oproduct.setCostText(CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal(0),
                            ctx.getCurrency()));
                    oproduct.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal(0),
                            ctx.getCurrency()));
                    //set shipping to 0
                    ShippingInformation info = new ShippingInformation();
                    shippingMethodLine.setShippingCostText(CurrencyUtil
                            .displayFormatedAmountWithCurrency(new BigDecimal("0"), ctx.getCurrency()));
                    total.setShippingLine(info);
                    total.setShippingTotal(new BigDecimal("0"));

                } catch (Exception e) {
                    log.error(e);
                }

            }

            List removable = null;
            //cleanup http session
            Iterator it = savedOrderProducts.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                if (!currentProducts.containsKey(key)) {
                    if (removable == null) {
                        removable = new ArrayList();
                    }
                    removable.add(key);
                }
            }

            if (removable != null) {
                Iterator removIt = removable.iterator();
                while (removIt.hasNext()) {
                    String key = (String) removIt.next();
                    SessionUtil.removeOrderTotalLine(key, req);
                }
            }

            OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);
            total = oservice.calculateTotal(order, productList, customer, shipping, ctx.getCurrency(),
                    LocaleUtil.getLocale(req));

            OrderProduct[] opArray = new OrderProduct[productList.size()];
            OrderProduct[] o = (OrderProduct[]) productList.toArray(opArray);
            total.setOrderProducts(o);

            total.setShippingLine(shippingInfo);

            Order savedOrder = SessionUtil.getOrder(req);
            savedOrder.setTotal(total.getTotal());
            savedOrder.setOrderTax(total.getTaxTotal());
            SessionUtil.setOrder(savedOrder, req);

        }

    } catch (Exception e) {
        log.error(e);
        total = new OrderTotalSummary(currency);
        total.setErrorMessage(LabelUtil.getInstance().getText(locale, "messages.genericmessage"));
    }

    ShippingInformation shippingLine = total.getShippingLine();
    if (shippingLine != null) {
        shippingLine.setShippingCostText(CurrencyUtil
                .displayFormatedAmountWithCurrency(shippingLine.getShippingCost(), ctx.getCurrency()));
    } else {
        shippingLine = new ShippingInformation();
        shippingLine.setShippingCostText(
                CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal("0"), ctx.getCurrency()));
    }

    if (shippingLine.getHandlingCost() != null) {
        shippingLine.setHandlingCostText(CurrencyUtil
                .displayFormatedAmountWithCurrency(shippingMethodLine.getHandlingCost(), ctx.getCurrency()));
    }

    if (total.getShippingTotal() != null) {
        total.setShippingTotalText(
                CurrencyUtil.displayFormatedAmountWithCurrency(total.getShippingTotal(), ctx.getCurrency()));
    }

    if (total.getOneTimeSubTotal() != null) {
        total.setOneTimeSubTotalText(
                CurrencyUtil.displayFormatedAmountWithCurrency(total.getOneTimeSubTotal(), ctx.getCurrency()));
    }

    if (total.getRecursiveSubTotal() != null) {
        total.setRecursiveSubTotalText(CurrencyUtil
                .displayFormatedAmountWithCurrency(total.getRecursiveSubTotal(), ctx.getCurrency()));
    }

    if (total.getTotal() != null) {
        total.setTotalText(CurrencyUtil.displayFormatedAmountWithCurrency(total.getTotal(), ctx.getCurrency()));
    }
    return total;

}

From source file:com.encens.khipus.service.production.RawMaterialPayRollServiceBean.java

@Override
public Double getReservProducer(Date startDate, Date endDate) {
    BigDecimal result = (BigDecimal) getEntityManager()
            .createNativeQuery("select IFNULL(sum(monto),0.0) from DESCUENTORESERVA\n"
                    + "where FECHAINI = :startDate\n " + "and FECHAFIN  = :endDate")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE).getSingleResult();

    return result.doubleValue();
}

From source file:vteaexploration.plottools.panels.XYExplorationPanel.java

public void makeOverlayImage(ArrayList gates, int x, int y, int xAxis, int yAxis) {
    //convert gate to chart x,y path

    Gate gate;/*from  w w  w .  ja va  2s .  c  o m*/
    ListIterator<Gate> gate_itr = gates.listIterator();

    //.get

    int total = 0;
    int gated = 0;
    int selected = 0;
    int gatedSelected = 0;

    int gatecount = gates.size();

    while (gate_itr.hasNext()) {
        gate = gate_itr.next();
        if (gate.getSelected()) {
            Path2D path = gate.createPath2DInChartSpace();

            ArrayList<MicroObject> result = new ArrayList<MicroObject>();

            ArrayList<MicroObject> volumes = (ArrayList) this.plotvalues.get(1);
            MicroObjectModel volume;

            double xValue = 0;
            double yValue = 0;

            ListIterator<MicroObject> it = volumes.listIterator();
            try {
                while (it.hasNext()) {
                    volume = it.next();
                    if (volume != null) {
                        xValue = ((Number) processPosition(xAxis, (MicroObject) volume)).doubleValue();
                        yValue = ((Number) processPosition(yAxis, (MicroObject) volume)).doubleValue();
                        if (path.contains(xValue, yValue)) {
                            result.add((MicroObject) volume);
                        }
                    }
                }
            } catch (NullPointerException e) {
            }
            ;

            Overlay overlay = new Overlay();

            int count = 0;
            BufferedImage placeholder = new BufferedImage(impoverlay.getWidth(), impoverlay.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);

            ImageStack gateOverlay = new ImageStack(impoverlay.getWidth(), impoverlay.getHeight());

            selected = getSelectedObjects();

            total = volumes.size();

            gated = getGatedObjects(impoverlay);

            gatedSelected = getGatedSelected(impoverlay);

            for (int i = 0; i <= impoverlay.getNSlices(); i++) {
                BufferedImage selections = new BufferedImage(impoverlay.getWidth(), impoverlay.getHeight(),
                        BufferedImage.TYPE_INT_ARGB);

                Graphics2D g2 = selections.createGraphics();

                ImageRoi ir = new ImageRoi(0, 0, placeholder);
                ListIterator<MicroObject> vitr = result.listIterator();

                while (vitr.hasNext()) {
                    try {
                        MicroObject vol = (MicroObject) vitr.next();

                        int[] x_pixels = vol.getXPixelsInRegion(i);
                        int[] y_pixels = vol.getYPixelsInRegion(i);

                        for (int c = 0; c < x_pixels.length; c++) {

                            g2.setColor(gate.getColor());
                            g2.drawRect(x_pixels[c], y_pixels[c], 1, 1);
                        }
                        ir = new ImageRoi(0, 0, selections);
                        count++;

                    } catch (NullPointerException e) {
                    }
                }

                ir.setPosition(i);
                ir.setOpacity(0.4);
                overlay.add(ir);

                gateOverlay.addSlice(ir.getProcessor());

                java.awt.Font f = new Font("Arial", Font.BOLD, 12);
                BigDecimal percentage = new BigDecimal(selected);
                BigDecimal totalBD = new BigDecimal(total);
                percentage = percentage.divide(totalBD, 4, BigDecimal.ROUND_UP);

                BigDecimal percentageGated = new BigDecimal(gated);
                BigDecimal totalGatedBD = new BigDecimal(total);
                percentageGated = percentageGated.divide(totalGatedBD, 4, BigDecimal.ROUND_UP);

                BigDecimal percentageGatedSelected = new BigDecimal(gatedSelected);
                BigDecimal totalGatedSelectedBD = new BigDecimal(total);
                percentageGatedSelected = percentageGatedSelected.divide(totalGatedSelectedBD, 4,
                        BigDecimal.ROUND_UP);

                // System.out.println("PROFILING: gate fraction: " + percentage.toString());
                if (impoverlay.getWidth() > 256) {

                    TextRoi textTotal = new TextRoi(5, 10,
                            selected + "/" + total + " gated (" + 100 * percentage.doubleValue() + "%)");

                    if (gated > 0) {
                        textTotal = new TextRoi(5, 10, selected + "/" + total + " total ("
                                + 100 * percentage.doubleValue() + "%)" + "; " + gated + "/" + total + " roi ("
                                + 100 * percentageGated.doubleValue() + "%)" + "; " + gatedSelected + "/"
                                + total + " overlap (" + 100 * percentageGatedSelected.doubleValue() + "%)", f);
                    }
                    //TextRoi textImageGated = new TextRoi(5, 18, selected + "/" + total + " gated objects (" + 100 * percentage.doubleValue() + "%)", f);
                    textTotal.setPosition(i);
                    //textImageGated.setPosition(i);
                    overlay.add(textTotal);
                } else {
                    f = new Font("Arial", Font.PLAIN, 10);
                    TextRoi line1 = new TextRoi(5, 5,
                            selected + "/" + total + " gated" + "(" + 100 * percentage.doubleValue() + "%)", f);
                    overlay.add(line1);
                    if (gated > 0) {
                        f = new Font("Arial", Font.PLAIN, 10);
                        TextRoi line2 = new TextRoi(5, 18,
                                gated + "/" + total + " roi (" + 100 * percentageGated.doubleValue() + "%)", f);
                        overlay.add(line2);
                        TextRoi line3 = new TextRoi(5, 31, gatedSelected + "/" + total + " overlap ("
                                + 100 * percentageGatedSelected.doubleValue() + "%)", f);
                        overlay.add(line3);
                    }
                    line1.setPosition(i);

                }
            }
            impoverlay.setOverlay(overlay);

            //ImagePlus gateMaskImage = new ImagePlus("gates", gateOverlay);

            //gateMaskImage.show();

            gate.setGateOverlayStack(gateOverlay);

        }

        impoverlay.draw();
        impoverlay.setTitle(this.getTitle());

        if (impoverlay.getDisplayMode() != IJ.COMPOSITE) {
            impoverlay.setDisplayMode(IJ.COMPOSITE);
        }

        if (impoverlay.getSlice() == 1) {
            impoverlay.setZ(Math.round(impoverlay.getNSlices() / 2));
        } else {
            impoverlay.setSlice(impoverlay.getSlice());
        }
        impoverlay.show();
    }
}

From source file:com.shengpay.website.common.service.impl.DepositeLimitServiceImpl.java

@Override
public DepositLimitResponse queryLimit(String ptid, String ruleID, BigDecimal currentDepositAmount) {
    DepositLimitResponse response = new DepositLimitResponse();

    DepositLimitDO limitDO = null;//from   w  w  w .  j  a  v  a  2s.c o m
    try {
        limitDO = depositLimitDAO.queryLimitRecordByRule(ruleID);
        if (null != limitDO) {
            String productCode = limitDO.getProductCode(); //??
            String depositCode = limitDO.getDepositCode(); //?
            String depositChannel = limitDO.getDepositChannel(); //?
            Long validTimeType = limitDO.getValidTime(); //    0  1  2
            if (null != validTimeType) {
                response.setValidTimeType(validTimeType.intValue());
            }

            //??
            FundsStatQueryRequest request = new FundsStatQueryRequest();
            request.setMemberId(ptid);
            request.setRulePackageId(2L);
            ProductPaymentPackage[] productGroups = buildProductPaymentPackage(productCode, depositCode,
                    depositChannel);
            request.setProductGroup(productGroups);

            StatisPeriodEnum requestStatisPeriodEnum = null;
            if (0L == validTimeType) {
                requestStatisPeriodEnum = StatisPeriodEnum.DAY; //
            } else if (1L == validTimeType) {
                requestStatisPeriodEnum = StatisPeriodEnum.MONTH; //
            } else if (2L == validTimeType) {
                requestStatisPeriodEnum = StatisPeriodEnum.YEAR; //
            }
            request.setPeriod(requestStatisPeriodEnum);

            String sourceCode = "442";
            request.setSourceCode(sourceCode);
            FundsStatQueryResponse fundsStatQueryResponse = fundsStatQueryService.query(request);
            int limitTimes = -1;
            BigDecimal limitAmount = null;
            if (null != fundsStatQueryResponse) {
                String returnCode = fundsStatQueryResponse.getReturnCode();
                if (null != returnCode) {
                    if ("0000".equals(returnCode) || "0002".equals(returnCode)) {
                        try {
                            limitTimes = fundsStatQueryResponse.getStatTimes();
                            limitAmount = new BigDecimal(fundsStatQueryResponse.getStatResult());
                            response.setDepositeAmount(limitAmount);
                        } catch (Throwable t) {
                            logger.error("Execute limit amount from FundsStatQueryService.query() make error!",
                                    t);
                        }
                    }
                }

            }

            Long timesRule = limitDO.getDepositTimes();
            Long amountRule = limitDO.getDepositAmount();

            if (null != timesRule) {
                response.setRuleTimes(timesRule);
                if (limitTimes >= timesRule) {
                    response.setTimesLimit(Boolean.TRUE);
                }
            }
            if (null != amountRule) {
                response.setRuleAmount(amountRule);
                if (null != limitAmount) {
                    if (currentDepositAmount != null) {
                        //??+?? ??
                        limitAmount = limitAmount.add(currentDepositAmount);
                    }
                    if (limitAmount.doubleValue() > amountRule) {
                        response.setAmountLimit(Boolean.TRUE);
                    }
                }
            }
            response.setSuccess(Boolean.TRUE);
        } else {
            response.setSuccess(Boolean.FALSE);
            response.setErrorMessage("By ruleID[" + ruleID + "] query db is null.");
        }
    } catch (Throwable t) {
        response.setSuccess(Boolean.FALSE);
        response.setErrorMessage("Not found ruleID [" + ruleID + "].");
        logger.error("execute query depositlimit make error!", t);
    }

    return response;
}

From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java

@Override
@Transactional/*  w ww.j  a v a2  s  .  com*/
public FinanceOverzichtGroep graphiekOverzichtGroep(Date beginDate, Date eindDate,
        Integer showBedragPublicGroep) {
    List<? extends Bedragen> bedragInPeriode = bedragenDao.BedragInPeriode(beginDate, eindDate, null,
            showBedragPublicGroep, userInfo.getPersoon().getPk_id());

    FinanceOverzichtGroep financeOverzichtGroep = new FinanceOverzichtGroep();

    List<? extends Bedragen> lstBedragen = bedragInPeriode;

    Map<Groepen, Map<String, BigDecimal>> bedragenOverzicht = OverviewRekeningGroep(bedragInPeriode);

    BigDecimal totaalKosten = new BigDecimal(0);
    BigDecimal totaalOpbrengsten = new BigDecimal(0);

    List<OverzichtGroep> overzichtGroepen = new ArrayList<OverzichtGroep>();
    for (Entry entry : bedragenOverzicht.entrySet()) {

        GroepenSrvPojo groep = new GroepenSrvPojo((Groepen) entry.getKey());

        if (groep.getCodeId() == null) {
            groep.setCodeId("NULL");
        }

        if (!groep.getCodeId().equals("INTER_REKENING")) {
            OverzichtGroep overzichtGroep = new OverzichtGroep();
            overzichtGroep.setGroepId(groep.getPk_id());
            overzichtGroep.setNaam(groep.getNaam());

            Map<String, BigDecimal> bedragen = (Map<String, BigDecimal>) entry.getValue();
            overzichtGroep.setTotaal_kosten(bedragen.get(NEGATIEF).doubleValue());
            overzichtGroep.setTotaal_opbrengsten(bedragen.get(POSITIEF).doubleValue());

            overzichtGroepen.add(overzichtGroep);

            totaalKosten = totaalKosten.add(bedragen.get(NEGATIEF));
            totaalOpbrengsten = totaalOpbrengsten.add(bedragen.get(POSITIEF));
        }
    }
    financeOverzichtGroep.setTotaal_kosten(totaalKosten.doubleValue());
    financeOverzichtGroep.setTotaal_opbrengsten(totaalOpbrengsten.doubleValue());

    financeOverzichtGroep.setOverzichtGroep(overzichtGroepen);

    return financeOverzichtGroep;
}

From source file:com.salesmanager.central.invoice.InvoiceDetailsAction.java

/**
 * Gather all invoice lines and persist to the appropriate order tables
 * /*from   w w w .  j  a  v a  2s  .c  om*/
 * @return
 */
public String saveInvoice() {

    try {

        this.prepareInvoiceReferences();

        // gather cart lines
        /**
         * <tr>
         * <td class="item">
         * <input type="hidden" name ="cartlineid-+data.lineId+"
         * id="cartlineid- +data.lineId+ " value=" + data.lineId+ "> <input
         * type="hidden"
         * name="productid-"+data.lineId+" id="productid-" +data.lineId+ "
         * value=" + data.productId + "> <input type="hidden" name="ids[]"
         * value="+data.lineId+"> <input type="hidden"
         * name="productname-"+data
         * .lineId+" id="productname-" +data.lineId+ "
         * value=" + data.productName + "> <div
         * id="productText">" + data.productName + " </div> " + prop + "</td>
         * <td class="quantity">"; <div
         * id="qmessage-"+data.lineId+"\"></div> <input type="text"
         * name="quantity-" +data.lineId+
         * " value="1" id="quantity-" +data.lineId+ " maxlength="3" />";</td>
         * <td class="price"><div
         * id="pmessage-"+data.lineId+"></div><input type="
         * text" name="price-" +data.lineId+ " value=" + data.priceText + "
         * id="price-" +data.lineId+ " size="5" maxlength="5" /></td>
         * </tr>
         */

        Context ctx = super.getContext();

        // check that customer.customerId is there

        // order
        Order savedOrder = SessionUtil.getOrder(super.getServletRequest());

        // check sdate edate
        savedOrder.setDatePurchased(DateUtil.getDate(sdate));
        savedOrder.setOrderDateFinished(DateUtil.getDate(edate));
        savedOrder.setOrderId(this.getOrder().getOrderId());
        savedOrder.setDisplayInvoicePayments(this.getOrder().isDisplayInvoicePayments());

        OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService);

        Customer customer = SessionUtil.getCustomer(super.getServletRequest());
        customer.setLocale(super.getLocale());

        this.setCustomerText(formatCustomer(customer));

        // get latest shipping information
        ShippingInformation shippingInformation = SessionUtil.getShippingInformation(super.getServletRequest());

        Shipping shipping = null;

        if (shippingInformation != null && shippingInformation.getShippingMethodId() != null) {
            shipping = new Shipping();
            shipping.setHandlingCost(shippingInformation.getHandlingCost());
            shipping.setShippingCost(shippingInformation.getShippingCost());
            shipping.setShippingDescription(shippingInformation.getShippingMethod());

            shipping.setShippingModule(shippingInformation.getShippingModule());
        }

        int cartLines = 0;

        List ids = this.getIds();

        List processProducts = new ArrayList();

        Map products = SessionUtil.getOrderProducts(super.getServletRequest());

        if (ids == null || ids.size() == 0) {
            MessageUtil.addErrorMessage(super.getServletRequest(),
                    LabelUtil.getInstance().getText(super.getLocale(), "error.cart.recalculate"));
            return ERROR;
        }

        Iterator idIterator = ids.iterator();
        boolean hasError = false;

        OrderProduct op = null;

        while (idIterator.hasNext()) {
            Object o = idIterator.next();

            int iKey = -1;
            try {
                iKey = (Integer) o;
            } catch (Exception ignore) {
                continue;
            }
            try {
                cartLines = cartLines + iKey;
                // now get the productid, quantity and price
                String sProductId = super.getServletRequest().getParameter("productid-" + iKey);
                String sQuantity = super.getServletRequest().getParameter("quantity-" + iKey);
                String sPrice = super.getServletRequest().getParameter("price-" + iKey);
                // get orderproduct
                op = (OrderProduct) products.get(String.valueOf(iKey));
                if (op == null) {
                    // throw an exception
                    MessageUtil.addErrorMessage(super.getServletRequest(),
                            LabelUtil.getInstance().getText(super.getLocale(), "error.cart.recalculate"));
                    return ERROR;
                }

                op.setPriceText(sPrice);
                op.setQuantityText(sQuantity);

                processProducts.add(op);

                // validate quantity and price

                long productId = Long.parseLong(sProductId);

                int quantity = 0;
                try {
                    quantity = Integer.parseInt(sQuantity);
                } catch (Exception e) {
                    // TODO: handle exception
                    hasError = true;
                    if (op != null) {
                        op.setErrorMessage(
                                LabelUtil.getInstance().getText(super.getLocale(), "errors.quantity.invalid"));
                    }
                }

                BigDecimal price = new BigDecimal("0");
                try {
                    price = CurrencyUtil.validateCurrency(sPrice, ctx.getCurrency());
                } catch (Exception e) {
                    // TODO: handle exception
                    hasError = true;
                    if (op != null) {
                        op.setPriceErrorMessage(
                                LabelUtil.getInstance().getText(super.getLocale(), "messages.price.invalid"));
                    }
                }

                // set the submited data
                op.setProductQuantity(quantity);
                op.setProductPrice(price);

                op.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(price, ctx.getCurrency()));

                double finalPrice = price.doubleValue();
                BigDecimal bdFinalPrice = new BigDecimal(finalPrice);
                op.setCostText(CurrencyUtil.displayFormatedAmountWithCurrency(bdFinalPrice, ctx.getCurrency()));
                op.setPriceText(CurrencyUtil.displayFormatedAmountNoCurrency(price, ctx.getCurrency()));

                BigDecimal bdFinalPriceQty = bdFinalPrice.multiply(new BigDecimal(quantity));

                //op.setFinalPrice(bdFinalPrice);
                op.setFinalPrice(bdFinalPriceQty);

            } catch (Exception e) {
                log.error(e);
                super.setTechnicalMessage();
                hasError = true;
            }

        }

        summary = oservice.calculateTotal(savedOrder, processProducts, customer, shipping, ctx.getCurrency(),
                super.getLocale());
        OrderProduct[] opArray = new OrderProduct[processProducts.size()];
        OrderProduct[] objects = (OrderProduct[]) processProducts.toArray(opArray);
        summary.setOrderProducts(objects);

        MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
        MerchantStore store = mservice.getMerchantStore(ctx.getMerchantid());

        super.getServletRequest().setAttribute("ORDERTOTALSUMMARY", summary);

        if (hasError) {
            return ERROR;
        }

        oservice.saveInvoice(ctx.getMerchantid(), savedOrder.getOrderId(), savedOrder.getDatePurchased(),
                savedOrder.getOrderDateFinished(), this.getComments(), savedOrder.isDisplayInvoicePayments(),
                processProducts, customer, shipping, store, super.getLocale());

        // url
        LabelUtil lhelper = LabelUtil.getInstance();
        lhelper.setLocale(super.getLocale());
        StringBuffer url = new StringBuffer().append("<a href='")
                .append(FileUtil.getInvoiceUrl(savedOrder, customer)).append("&request_locale=")
                .append(customer.getCustomerLang()).append("_").append(super.getLocale().getCountry())
                .append("' target='_blank'>");
        url.append(lhelper.getText(customer.getCustomerLang(), "label.email.invoice.viewinvoice"))
                .append("</a>");

        this.setInvoiceUrl(url.toString());

        super.setSuccessMessage();

        return SUCCESS;

    } catch (Exception e) {
        log.error(e);
        super.setTechnicalMessage();
        return ERROR;
    }

}

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/*  ww  w .j a  v  a 2  s  .c om*/
 * @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:com.github.jonmarsh.waveform_processing_for_imagej.WaveformUtils.java

/**
 * Computes real roots for quadratic equation of the form
 * {@code ax^2 + bx + c = 0}, given real coefficients {@code a}, {@code b},
 * and {@code c}. If there are two distinct roots, they are returned in a
 * two-element array. If there is a single root or two identical roots, the
 * result is returned in a single-element array. If there are no real-valued
 * roots, the function returns a zero-length array. Note that the
 * discriminant {@code b*b-4*a*c} contains the potential for catastrophic
 * cancellation if its two terms are nearly equal, so in this case the
 * algorithm uses {@code BigDecimal}s and methods described by W. Kahan in
 * "On the Cost of Floating-Point Computation Without Extra-Precise
 * Arithmetic"/*from w  w  w. jav  a  2s. c  om*/
 * (<a href="http://www.cs.berkeley.edu/~wkahan/Qdrtcs.pdf">www.cs.berkeley.edu/~wkahan/Qdrtcs.pdf/</a>),
 * which references TJ Dekker (A Floating-Point Technique for Extending the
 * Available Precision,? pp 234-242 in Numerische Mathematik 18, 1971).
 *
 * @param a quadratic coefficient
 * @param b linear coefficient
 * @param c constant term
 * @return array of distinct roots in order from least to greatest, or
 *         zero-length array if there are no real-valued roots
 */
public static final double[] quadraticRoots(double a, double b, double c) {
    if (a == 0.0) {
        if (b == 0.0) {
            return new double[0];
        } else {
            return new double[] { -c / b };
        }
    } else if (b == 0.0) {
        if (c == 0.0) {
            return new double[] { 0.0 };
        } else {
            double q = Math.sqrt(-c / a);
            return new double[] { -q, q };
        }
    } else if (c == 0.0) {
        if (a == 0.0) {
            return new double[] { 0.0 };
        } else {
            double r = -b / a;
            if (r < 0.0) {
                return new double[] { r, 0.0 };
            } else {
                return new double[] { 0.0, r };
            }
        }
    } else {
        double p = b * b;
        double q = 4.0 * a * c;
        double d = p - q;
        double sqrtD = Math.sqrt(d);
        double pie = 3; // see reference cited in javadoc for the origin of this number
        if (pie * Math.abs(d) < p + q) {
            BigDecimal aBD = new BigDecimal(a, MathContext.DECIMAL64);
            BigDecimal bBD = new BigDecimal(b, MathContext.DECIMAL64);
            BigDecimal cBD = new BigDecimal(c, MathContext.DECIMAL64);
            BigDecimal pBD = bBD.multiply(bBD);
            BigDecimal qBD = aBD.multiply(cBD).multiply(new BigDecimal(4, MathContext.DECIMAL64));
            BigDecimal dBD = pBD.subtract(qBD);
            if (dBD.doubleValue() < 0) { // discriminant < 0.0
                return new double[0];
            } else if (dBD.doubleValue() == 0) { // discriminant is truly zero to double precision
                return new double[] { -b / (2.0 * a) };
            }
            sqrtD = sqrt(dBD, MathContext.DECIMAL64).doubleValue();
        }
        double s = -0.5 * (b + Math.signum(b) * sqrtD);
        double r1 = s / a;
        double r2 = c / s;
        if (r1 < r2) {
            return new double[] { r1, r2 };
        } else if (r1 > r2) {
            return new double[] { r2, r1 };
        } else {
            return new double[] { r1 };
        }
    }
}

From source file:com.facebook.appevents.AppEventsLogger.java

/**
 * Logs a purchase event with Facebook, in the specified amount and with the specified currency.
 * Additional detail about the purchase can be passed in through the parameters bundle.
 *
 * @param purchaseAmount Amount of purchase, in the currency specified by the 'currency'
 *                       parameter. This value will be rounded to the thousandths place (e.g.,
 *                       12.34567 becomes 12.346).
 * @param currency       Currency used to specify the amount.
 * @param parameters     Arbitrary additional information for describing this event. This should
 *                       have no more than 10 entries, and keys should be mostly consistent from
 *                       one purchase event to the next.
 *///  www.  j  ava  2s. c  om
public void logPurchase(BigDecimal purchaseAmount, Currency currency, Bundle parameters) {

    if (purchaseAmount == null) {
        notifyDeveloperError("purchaseAmount cannot be null");
        return;
    } else if (currency == null) {
        notifyDeveloperError("currency cannot be null");
        return;
    }

    if (parameters == null) {
        parameters = new Bundle();
    }
    parameters.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, currency.getCurrencyCode());

    logEvent(AppEventsConstants.EVENT_NAME_PURCHASED, purchaseAmount.doubleValue(), parameters);
    eagerFlush();
}

From source file:edu.ku.brc.specify.tasks.services.CollectingEventLocalityKMLGenerator.java

/**
 * Generates a KML chunk describing the given collecting event.
 * @param kmlDocument /*from www  .j  a  v  a 2s .c o  m*/
 *
 * @param ce the event
 * @param label the label for the event
 * @return the KML string
 */
protected void generatePlacemark(Element kmlDocument, final CollectingEvent ce, final String label) {
    if (ce == null || ce.getLocality() == null || ce.getLocality().getLatitude1() == null
            || ce.getLocality().getLongitude1() == null) {
        return;
    }

    // get all of the important information
    Locality loc = ce.getLocality();
    BigDecimal lat = loc.getLatitude1();
    BigDecimal lon = loc.getLongitude1();

    // get event times
    Calendar start = ce.getStartDate();
    DateFormat dfStart = DateFormat.getDateInstance();

    String startString = "";
    if (start != null) {
        dfStart.setCalendar(start);
        startString = dfStart.format(start.getTime());
    }

    Calendar end = ce.getEndDate();
    DateFormat dfEnd = DateFormat.getDateInstance();

    String endString = "";
    if (end != null) {
        dfEnd.setCalendar(end);
        endString = dfEnd.format(end.getTime());
    }

    // build the placemark
    Element placemark = kmlDocument.addElement("Placemark");
    placemark.addElement("styleUrl").addText("#custom");

    StringBuilder name = new StringBuilder();
    if (label != null) {
        name.append(label);
    }

    if (StringUtils.isNotEmpty(startString)) {
        name.append(startString);
        if (StringUtils.isNotEmpty(endString) && !startString.equals(endString)) {
            name.append(" - ");
            name.append(endString);
        }
    }

    placemark.addElement("name").addText(name.toString());
    // build the fancy HTML popup description

    placemark.addElement("description").addCDATA(generateHtmlDesc(ce));

    GenericKMLGenerator.buildPointAndLookAt(placemark,
            new Pair<Double, Double>(lat.doubleValue(), lon.doubleValue()));
}