Example usage for java.math BigDecimal longValue

List of usage examples for java.math BigDecimal longValue

Introduction

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

Prototype

@Override
public long longValue() 

Source Link

Document

Converts this BigDecimal to a long .

Usage

From source file:org.egov.wtms.web.controller.application.MeterReadingController.java

private BigDecimal calculateAmountTobePaid(final WaterConnectionDetails waterConnectionDetails,
        final BigDecimal noOfUnitsPerMonth) {
    MeteredRates meteredRates = null;/*from  w  w w  .  ja v  a  2 s .  c  o m*/
    UsageSlab usageSlab = null;
    if (!noOfUnitsPerMonth.equals(BigDecimal.ZERO))
        usageSlab = usageSlabService.getUsageSlabForWaterVolumeConsumed(
                waterConnectionDetails.getUsageType().getName(), noOfUnitsPerMonth.longValue());
    if (usageSlab != null && usageSlab.getSlabName() != null)
        meteredRates = meteredRatesService.findBySlabName(usageSlab.getSlabName());
    else if (!noOfUnitsPerMonth.equals(BigDecimal.ZERO))
        throw new ApplicationRuntimeException("err.usageslab.not.present");
    BigDecimal amountToBeCollected;
    if (meteredRates == null || meteredRates.getSlabName() == null)
        throw new ApplicationRuntimeException(ERROR_METER_RATE_NOT_PRESENT);
    else
        amountToBeCollected = getAmountToBeCollected(meteredRates, usageSlab, noOfUnitsPerMonth);
    return amountToBeCollected;
}

From source file:semanticweb.hws14.movapp.activities.MovieDetail.java

private void setData(final MovieDet movie) {
    Thread picThread = new Thread(new Runnable() {
        public void run() {
            try {
                ImageView img = (ImageView) findViewById(R.id.imageViewMovie);
                URL url = new URL(movie.getPoster());
                HttpGet httpRequest;// ww  w  .  jav  a  2s.co  m

                httpRequest = new HttpGet(url.toURI());

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httpRequest);

                HttpEntity entity = response.getEntity();
                BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
                InputStream input = b_entity.getContent();

                Bitmap bitmap = BitmapFactory.decodeStream(input);

                img.setImageBitmap(bitmap);

            } catch (Exception ex) {
                Log.d("MovieDetail Picture Error ", ex.toString());
            }
        }
    });
    picThread.start();

    if (!"".equals(movie.getTitle())) {
        TextView movieTitle = (TextView) findViewById(R.id.tvMovieTitle);
        movieTitle.setText(movie.getTitle());
        movieTitle.setVisibility(View.VISIBLE);
    }

    if (!"".equals(movie.getPlot())) {
        TextView moviePlot = (TextView) findViewById(R.id.tvPlot);
        moviePlot.setText(movie.getPlot());
        moviePlot.setVisibility(View.VISIBLE);
    }

    TextView ageRestriction = (TextView) findViewById(R.id.tvAgeRestriction);
    TextView arHc = (TextView) findViewById(R.id.tvAgeRestrictionHC);
    String aR = String.valueOf(movie.getRated());

    //Decode the ageRestriction
    if (!aR.equals("")) {
        ageRestriction.setVisibility(View.VISIBLE);
        arHc.setVisibility(View.VISIBLE);
        if (aR.equals("X")) {
            ageRestriction.setText("18+");
        } else if (aR.equals("R")) {
            ageRestriction.setText("16+");
        } else if (aR.equals("M")) {
            ageRestriction.setText("12+");
        } else if (aR.equals("G")) {
            ageRestriction.setText("6+");
        } else {
            ageRestriction.setVisibility(View.GONE);
            arHc.setVisibility(View.GONE);
        }
    }

    TextView ratingCount = (TextView) findViewById(R.id.tvMovieRatingCount);
    TextView ratingCountHc = (TextView) findViewById(R.id.tvMovieRatingCountHC);
    String ratingCountText = movie.getVoteCount();
    ratingCount.setText(ratingCountText);
    manageEmptyTextfields(ratingCountHc, ratingCount, ratingCountText, false);

    if (!"".equals(movie.getImdbRating())) {
        TextView movieRating = (TextView) findViewById(R.id.tvMovieRating);
        if (movie.getImdbRating().equals("0 No Rating")) {
            movieRating.setText("No Rating");
        } else if (movie.getImdbRating().equals("0 No Data")) {
            movieRating.setText("");
        } else {
            movieRating.setText(movie.getImdbRating() + "/10");
        }
        movieRating.setVisibility(View.VISIBLE);
        findViewById(R.id.tvMovieRatingHC).setVisibility(View.VISIBLE);
    }

    TextView metaScore = (TextView) findViewById(R.id.tvMetaScore);
    TextView metaScoreHc = (TextView) findViewById(R.id.tvMetaScoreHC);
    String metaSoreText = String.valueOf(movie.getMetaScore());
    metaScore.setText(metaSoreText + "/100");
    manageEmptyTextfields(metaScoreHc, metaScore, metaSoreText, false);

    TextView tvGenreHc = (TextView) findViewById(R.id.tvGenreHC);
    TextView genre = (TextView) findViewById(R.id.tvGenre);
    String genreText = String.valueOf(movie.createTvOutOfList(movie.getGenres()));
    genre.setText(genreText);
    manageEmptyTextfields(tvGenreHc, genre, genreText, true);

    TextView releaseYear = (TextView) findViewById(R.id.tvReleaseYear);
    TextView releaseYearHc = (TextView) findViewById(R.id.tvReleaseYearHC);
    String releaseYearText = String.valueOf(movie.getReleaseYear());
    releaseYear.setText(releaseYearText);
    manageEmptyTextfields(releaseYearHc, releaseYear, releaseYearText, true);

    TextView runtime = (TextView) findViewById(R.id.tvRuntime);
    TextView runTimeHc = (TextView) findViewById(R.id.tvRuntimeHC);
    String runtimeText = "";
    try {
        runtimeText = runtimeComputation(Float.parseFloat(movie.getRuntime()));
    } catch (Exception e) {
        runtimeText = movie.getRuntime();
    }
    runtime.setText(runtimeText);
    manageEmptyTextfields(runTimeHc, runtime, runtimeText, true);

    TextView budget = (TextView) findViewById(R.id.tvBudget);
    TextView budgetHc = (TextView) findViewById(R.id.tvBudgetHC);
    String budgetText = movie.getBudget();
    //Decode the budget
    if (budgetText.contains("E")) {
        BigDecimal myNumber = new BigDecimal(budgetText);
        long budgetLong = myNumber.longValue();
        NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US);
        budgetText = formatter.format(budgetLong);
        budgetText = String.valueOf(budgetText);
        budgetText = budgetComputation(budgetText);
        budget.setText(budgetText);
        manageEmptyTextfields(budgetHc, budget, budgetText, true);
    }

    TextView awards = (TextView) findViewById(R.id.tvAwards);
    TextView awardsHc = (TextView) findViewById(R.id.tvAwardsHC);
    String awardsText = movie.getAwards();
    awards.setText(awardsText);
    manageEmptyTextfields(awardsHc, awards, awardsText, true);

    TextView tvDirHc = (TextView) findViewById(R.id.tvDirectorsHC);
    TextView directors = (TextView) findViewById(R.id.tvDirectors);
    String directorText = String.valueOf(movie.createTvOutOfList(movie.getDirectors()));
    directors.setText(directorText);
    manageEmptyTextfields(tvDirHc, directors, directorText, true);

    TextView tvWriterHc = (TextView) findViewById(R.id.tvWritersHC);
    TextView writers = (TextView) findViewById(R.id.tvWriters);
    String writerText = String.valueOf(movie.createTvOutOfList(movie.getWriters()));
    writers.setText(writerText);
    manageEmptyTextfields(tvWriterHc, writers, writerText, true);

    TextView tvActorsHc = (TextView) findViewById(R.id.tvActorsHC);
    TextView actors = (TextView) findViewById(R.id.tvActors);
    String actorText = String.valueOf(movie.createTvOutOfList(movie.getActors()));
    actors.setText(actorText);
    manageEmptyTextfields(tvActorsHc, actors, actorText, true);
    colorIt(actors);

    if (movie.getActors().size() > 0) {
        btnActorList.setVisibility(View.VISIBLE);
    }

    btnRandomRelatedMovies.setVisibility(View.VISIBLE);
    btnRelatedMovies.setVisibility(View.VISIBLE);

    TextView tvRolesHc = (TextView) findViewById(R.id.tvRolesHC);
    TextView roles = (TextView) findViewById(R.id.tvRoles);
    ArrayList<String> roleList = movie.getRoles();

    if (roleList.size() > 0) {
        roles.setVisibility(View.VISIBLE);
        tvRolesHc.setVisibility(View.VISIBLE);
        roles.setText(String.valueOf(movie.createTvOutOfList(roleList)));
    }

    TextView wikiAbstract = (TextView) findViewById(R.id.tvWikiAbstract);
    wikiAbstract.setText(movie.getWikiAbstract());
    if (!"".equals(movie.getImdbId())) {
        btnImdbPage.setVisibility(View.VISIBLE);
    }
    if (!"".equals(movie.getWikiAbstract())) {
        btnSpoiler.setVisibility(View.VISIBLE);
    }
    try {
        picThread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    setProgressBarIndeterminateVisibility(false);
}

From source file:org.openvpms.component.system.common.jxpath.OpenVPMSTypeConverter.java

/**
 * Convert a {@link BigDecimal} to another type
 * /*  w  ww.  ja  va 2 s  . c  o  m*/
 * @param type
 *            the class to convert too
 * @param value
 *            the value to convert
 * @return Number
 *            the converted number of null.
 *            
 */
protected Number allocateNumber(Class type, BigDecimal value) {
    if (type == Byte.class || type == byte.class) {
        return new Byte(value.byteValue());
    }
    if (type == Short.class || type == short.class) {
        return new Short(value.shortValue());
    }
    if (type == Integer.class || type == int.class) {
        return new Integer(value.intValue());
    }
    if (type == Long.class || type == long.class) {
        return new Long(value.longValue());
    }
    if (type == Float.class || type == float.class) {
        return new Float(value.floatValue());
    }
    if (type == Double.class || type == double.class) {
        return new Double(value.doubleValue());
    }
    if (type == BigDecimal.class) {
        return value;
    }
    if (type == BigInteger.class) {
        return BigInteger.valueOf(value.longValue());
    }

    if (type == Money.class) {
        return new Money((BigDecimal) value);
    }

    return null;
}

From source file:org.apache.drill.exec.store.solr.SolrRecordReader.java

private void processRecord(ValueVector vv, Object fieldValue, int recordCounter) {
    String fieldValueStr = null;// ww w  .j  a  v  a  2s.  c om
    byte[] record = null;
    try {
        fieldValueStr = fieldValue.toString();
        record = fieldValueStr.getBytes(Charsets.UTF_8);

        if (vv.getClass().equals(NullableVarCharVector.class)) {
            NullableVarCharVector v = (NullableVarCharVector) vv;
            v.getMutator().setSafe(recordCounter, record, 0, record.length);
            v.getMutator().setValueLengthSafe(recordCounter, record.length);
        } else if (vv.getClass().equals(NullableBigIntVector.class)) {
            NullableBigIntVector v = (NullableBigIntVector) vv;
            BigDecimal bd = new BigDecimal(fieldValueStr);
            v.getMutator().setSafe(recordCounter, bd.longValue());
        } else if (vv.getClass().equals(NullableIntVector.class)) {
            NullableIntVector v = (NullableIntVector) vv;
            v.getMutator().setSafe(recordCounter, Integer.parseInt(fieldValueStr));
        } else if (vv.getClass().equals(NullableFloat8Vector.class)) {
            NullableFloat8Vector v = (NullableFloat8Vector) vv;
            Double d = Double.parseDouble(fieldValueStr);
            v.getMutator().setSafe(recordCounter, d);
        } else if (vv.getClass().equals(DateVector.class)) {
            DateVector v = (DateVector) vv;
            long dtime = 0L;
            try {
                TemporalAccessor accessor = SolrRecordReader.timeFormatter.parse(fieldValueStr);
                Date date = Date.from(Instant.from(accessor));
                dtime = date.getTime();
            } catch (Exception e) {
                SimpleDateFormat dateParser = new SimpleDateFormat(SolrRecordReader.defaultDateFormat);
                dtime = dateParser.parse(fieldValueStr).getTime();
            }

            v.getMutator().setSafe(recordCounter, dtime);
        } else if (vv.getClass().equals(NullableTimeStampVector.class)) {
            NullableTimeStampVector v = (NullableTimeStampVector) vv;
            DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
            long dtime = 0L;

            try {
                TemporalAccessor accessor = timeFormatter.parse(fieldValueStr);
                Date date = Date.from(Instant.from(accessor));
                dtime = date.getTime();
            } catch (Exception e) {
                SimpleDateFormat dateParser = new SimpleDateFormat(SolrRecordReader.defaultDateFormat);
                dtime = dateParser.parse(fieldValueStr).getTime();
            }
            v.getMutator().setSafe(recordCounter, dtime);
        }
    } catch (Exception e) {
        SolrRecordReader.logger.error("Error processing record: " + e.getMessage() + vv.getField().getPath()
                + " Field type " + vv.getField().getType() + " " + vv.getClass());
    }
}

From source file:org.egov.works.web.actions.contractoradvance.ContractorAdvanceRequisitionAction.java

public String save() {
    String actionName = "";
    try {/* w  w  w.j  a  va 2s  . c  om*/
        if (parameters.get(ACTION_NAME) != null && parameters.get(ACTION_NAME)[0] != null)
            actionName = parameters.get(ACTION_NAME)[0];

        if (!(CANCEL_ACTION.equals(actionName) || REJECT_ACTION.equals(actionName))) {
            final BigDecimal totalEstimateValueIncludingREValue = contractorAdvanceService
                    .getTotalEstimateValueIncludingRE(
                            contractorAdvanceRequisition.getWorkOrderEstimate().getEstimate());
            if (advancePaid.add(contractorAdvanceRequisition.getAdvanceRequisitionAmount())
                    .longValue() > totalEstimateValueIncludingREValue.longValue())
                throw new ValidationException(Arrays
                        .asList(new ValidationError("advancerequisition.validate.advancepaid.estimatevalue",
                                "advancerequisition.validate.advancepaid.estimatevalue")));
        }

        contractorAdvanceRequisition.setArftype(ARF_TYPE);
        contractorAdvanceService.save(contractorAdvanceRequisition, actionName, advanceAccountCode);
    } catch (final ValidationException validationException) {
        final List<ValidationError> errorList = validationException.getErrors();
        for (final ValidationError error : errorList)
            if (error.getMessage().contains("DatabaseSequenceFirstTimeException")) {
                prepare();
                throw new ValidationException(Arrays.asList(new ValidationError("error", error.getMessage())));
            } else
                throw new ValidationException(validationException.getErrors());
    }

    if (SAVE_ACTION.equals(actionName))
        messageKey = "advancerequisition.save.success";
    else
        messageKey = "advancerequisition." + actionName;
    addActionMessage(getText(messageKey, messageKey));

    getDesignation(contractorAdvanceRequisition);

    if (SAVE_ACTION.equals(actionName))
        sourcepage = "inbox";
    return SAVE_ACTION.equals(actionName) ? EDIT : SUCCESS;
}

From source file:ru.orangesoftware.financisto2.db.BudgetsTotalCalculator.java

public Total calculateTotalInHomeCurrency() {
    long t0 = System.currentTimeMillis();
    try {/*  w w w  . j  av a2s .  c o  m*/
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal balance = BigDecimal.ZERO;
        ExchangeRateProvider rates = db.getLatestRates();
        Currency homeCurrency = db.getHomeCurrency();
        for (Budget b : budgets) {
            Currency currency = b.getBudgetCurrency();
            ExchangeRate r = rates.getRate(currency, homeCurrency);
            if (r == ExchangeRate.NA) {
                return new Total(homeCurrency, TotalError.lastRateError(currency));
            } else {
                amount = amount.add(convert(r, b.spent));
                balance = balance.add(convert(r, b.amount + b.spent));
            }
        }
        Total total = new Total(homeCurrency, true);
        total.amount = amount.longValue();
        total.balance = balance.longValue();
        return total;
    } finally {
        long t1 = System.currentTimeMillis();
        Log.d("BUDGET TOTALS", (t1 - t0) + "ms");
    }
}

From source file:com.salesmanager.checkout.cart.ShoppingCartAction.java

protected void assembleShoppingCartItems(Collection<ShoppingCartProduct> items) throws Exception {
    /** Initial order **/
    // create an order with merchantId and all dates
    // will need to create a new order id when submited
    Order order = new Order();
    order.setMerchantId(store.getMerchantId());
    order.setCurrency(store.getCurrency());
    order.setDatePurchased(new Date());
    SessionUtil.setOrder(order, getServletRequest());
    /******//*from  w w w . j a v  a 2 s .  c om*/

    if (items != null & items.size() > 0) {

        Iterator i = items.iterator();
        while (i.hasNext()) {

            ShoppingCartProduct v = (ShoppingCartProduct) i.next();

            // Prepare order
            OrderProduct orderProduct = CheckoutUtil.createOrderProduct(v.getProductId(), getLocale(),
                    store.getCurrency());
            if (orderProduct.getProductQuantityOrderMax() > 1) {
                orderProduct.setProductQuantity(v.getQuantity());
            } else {
                orderProduct.setProductQuantity(1);
            }

            orderProduct.setProductId(v.getProductId());

            List<OrderProductAttribute> attributes = new ArrayList<OrderProductAttribute>();
            if (v.getAttributes() != null && v.getAttributes().size() > 0) {
                for (ShoppingCartProductAttribute attribute : v.getAttributes()) {

                    ProductAttribute pAttr = cservice.getProductAttribute(attribute.getAttributeId(),
                            super.getLocale().getLanguage());
                    if (pAttr != null && pAttr.getProductId() != orderProduct.getProductId()) {
                        LogMerchantUtil.log(store.getMerchantId(),
                                getText("error.validation.product.attributes.ids",
                                        new String[] { String.valueOf(attribute.getAttributeId()),
                                                String.valueOf(v.getProductId()) }));
                        continue;
                    }

                    if (pAttr != null && pAttr.getProductId() == v.getProductId()) {
                        OrderProductAttribute orderAttr = new OrderProductAttribute();
                        orderAttr.setProductOptionValueId(pAttr.getOptionValueId());
                        attributes.add(orderAttr);

                        // get order product value
                        ProductOptionValue pov = pAttr.getProductOptionValue();
                        if (pov != null) {
                            orderAttr.setProductOptionValue(pov.getName());
                        }

                        BigDecimal attrPrice = pAttr.getOptionValuePrice();

                        BigDecimal price = orderProduct.getProductPrice();
                        if (attrPrice != null && attrPrice.longValue() > 0) {
                            price = price.add(attrPrice);
                        }

                        // string values
                        if (!StringUtils.isBlank(attribute.getTextValue())) {
                            orderAttr.setProductOptionValue(attribute.getTextValue());
                        }
                    } else {
                        LogMerchantUtil.log(store.getMerchantId(),
                                getText("error.validation.product.attributes.ids",
                                        new String[] { String.valueOf(attribute.getAttributeId()),
                                                String.valueOf(v.getProductId()) }));
                    }
                }
            }

            BigDecimal price = orderProduct.getProductPrice();
            orderProduct.setFinalPrice(price);
            orderProduct.setProductPrice(price);
            orderProduct.setPriceText(CurrencyUtil.displayFormatedAmountNoCurrency(price, store.getCurrency()));
            orderProduct.setPriceFormated(
                    CurrencyUtil.displayFormatedAmountWithCurrency(price, store.getCurrency()));

            // original price
            orderProduct.setOriginalProductPrice(price);

            if (!attributes.isEmpty()) {
                CheckoutUtil.addAttributesToProduct(attributes, orderProduct, store.getCurrency(), getLocale());
            }

            Set attributesSet = new HashSet(attributes);
            orderProduct.setOrderattributes(attributesSet);

            SessionUtil.addOrderProduct(orderProduct, getServletRequest());

        } // end for

    } // end if

    // because this is a submission, cannot continue browsing, so that's it
    // for the OrderProduct
    Map orderProducts = SessionUtil.getOrderProducts(super.getServletRequest());

    // transform to a list
    List products = new ArrayList();
    if (orderProducts != null) {
        Iterator ii = orderProducts.keySet().iterator();
        while (ii.hasNext()) {
            String line = (String) ii.next();
            OrderProduct op = (OrderProduct) orderProducts.get(line);
            products.add(op);
        }
    }

    OrderTotalSummary summary = super.updateOrderTotal(order, products, store);

    this.setSummary(summary);

}

From source file:com.ipcglobal.fredimport.xls.DistinctCategoriesSpreadsheet.java

/**
 * Populate cell./*from   ww w.jav  a 2s. c  o  m*/
 *
 * @param rowData the row data
 * @param colCnt the col cnt
 * @param dataType the data type
 * @param obj the obj
 * @throws Exception the exception
 */
private void populateCell(Row rowData, int colCnt, DataType dataType, Object obj) throws Exception {
    int cellType = 0;

    if (dataType == DataType.Numeric)
        cellType = XSSFCell.CELL_TYPE_NUMERIC;
    else if (dataType == DataType.NumericDec2)
        cellType = XSSFCell.CELL_TYPE_NUMERIC;
    else if (dataType == DataType.Text)
        cellType = XSSFCell.CELL_TYPE_STRING;
    else if (dataType == DataType.Date)
        cellType = XSSFCell.CELL_TYPE_STRING;
    else if (dataType == DataType.Accounting)
        cellType = XSSFCell.CELL_TYPE_NUMERIC;
    else if (dataType == DataType.Percent)
        cellType = XSSFCell.CELL_TYPE_NUMERIC;
    Cell cellData = rowData.createCell(colCnt, cellType);

    short findFormat = -1;
    if (dataType == DataType.Date)
        findFormat = formatMmDdYyyy;
    else if (dataType == DataType.Percent)
        findFormat = formatPercent;
    else if (dataType == DataType.Accounting)
        findFormat = formatAccounting;
    else if (dataType == DataType.Numeric)
        findFormat = formatNumeric;
    else if (dataType == DataType.NumericDec2)
        findFormat = formatNumericDec2;
    else
        findFormat = formatGeneral;
    CellStyle style = findCellStyle("Arial", HSSFColor.BLACK.index, (short) 11, XSSFFont.BOLDWEIGHT_NORMAL,
            cellStyleFromDataAlign(findAlignByDataType(dataType)), XSSFCellStyle.VERTICAL_TOP, BG_COLOR_NONE,
            CellBorder.All_Thin, findFormat);
    cellData.setCellStyle(style);

    if (dataType == DataType.Numeric || dataType == DataType.NumericDec2 || dataType == DataType.Accounting
            || dataType == DataType.Percent) {
        if (obj == null)
            ; // leave the cell empty
        else if (obj instanceof BigDecimal) {
            BigDecimal value = (BigDecimal) obj;
            if (value != null)
                cellData.setCellValue(value.doubleValue());
        } else if (obj instanceof Integer) {
            Integer value = (Integer) obj;
            if (value != null)
                cellData.setCellValue(value.intValue());
        } else if (obj instanceof Long) {
            Long value = (Long) obj;
            if (value != null)
                cellData.setCellValue(value.longValue());
        } else if (obj instanceof Double) {
            Double value = (Double) obj;
            if (value != null)
                cellData.setCellValue(value.doubleValue());
        } else if (obj instanceof Short) {
            Short value = (Short) obj;
            if (value != null)
                cellData.setCellValue(value.shortValue());
        } else if (obj instanceof String) {
            String value = (String) obj;
            if (value != null)
                cellData.setCellValue(value);
        } else
            throw new Exception("Unsupported numeric type: " + obj.getClass().getSimpleName());
    } else if (dataType == DataType.Date) {
        Date date = (Date) obj;
        if (date != null)
            cellData.setCellValue(date);
    } else {
        cellData.setCellValue((String) obj);
    }
}

From source file:com.salesmanager.checkout.cart.ShoppingCartAction.java

protected void assembleItems(List<CheckoutParams> params) throws Exception {

    // create an order with merchantId and all dates
    // will need to create a new order id when submited
    Order order = SessionUtil.getOrder(getServletRequest());
    if (order == null) {
        order = new Order();
        order.setMerchantId(store.getMerchantId());
        order.setDatePurchased(new Date());
        order.setCurrency(store.getCurrency());
    }/*from   www . java  2  s . co  m*/

    SessionUtil.setOrder(order, getServletRequest());

    if (params != null & params.size() > 0) {

        Iterator i = params.iterator();
        while (i.hasNext()) {

            CheckoutParams v = (CheckoutParams) i.next();

            boolean quantityUpdated = false;

            // check if order product already exist. If that orderproduct
            // already exist
            // and has no ptoperties, so just update the quantity
            if (v.getAttributeId() == null || (v.getAttributeId() != null && v.getAttributeId().size() == 0)) {
                Map savedProducts = SessionUtil.getOrderProducts(getServletRequest());
                if (savedProducts != null) {
                    Iterator it = savedProducts.keySet().iterator();
                    while (it.hasNext()) {
                        String line = (String) it.next();
                        OrderProduct op = (OrderProduct) savedProducts.get(line);
                        if (op.getProductId() == v.getProductId()) {
                            Set attrs = op.getOrderattributes();
                            if (attrs.size() == 0) {
                                int qty = op.getProductQuantity();
                                qty = qty + v.getQty();
                                op.setProductQuantity(qty);
                                quantityUpdated = true;
                                break;
                            }
                        }
                    }
                }
            }

            if (!quantityUpdated) {// new submission

                // Prepare order
                OrderProduct orderProduct = CheckoutUtil.createOrderProduct(v.getProductId(), getLocale(),
                        store.getCurrency());
                if (orderProduct.getProductQuantityOrderMax() > 1) {
                    orderProduct.setProductQuantity(v.getQty());
                } else {
                    orderProduct.setProductQuantity(1);
                }

                orderProduct.setProductId(v.getProductId());

                List<OrderProductAttribute> attributes = new ArrayList<OrderProductAttribute>();
                if (v.getAttributeId() != null && v.getAttributeId().size() > 0) {
                    for (Long attrId : v.getAttributeId()) {
                        if (attrId != null && attrId != 0) {
                            ProductAttribute pAttr = cservice.getProductAttribute(attrId,
                                    super.getLocale().getLanguage());
                            if (pAttr != null && pAttr.getProductId() != orderProduct.getProductId()) {
                                LogMerchantUtil.log(v.getMerchantId(),
                                        getText("error.validation.product.attributes.ids", new String[] {
                                                String.valueOf(attrId), String.valueOf(v.getProductId()) }));
                                continue;
                            }

                            if (pAttr != null && pAttr.getProductId() == v.getProductId()) {
                                OrderProductAttribute orderAttr = new OrderProductAttribute();
                                orderAttr.setProductOptionValueId(pAttr.getOptionValueId());
                                attributes.add(orderAttr);

                                // get order product value
                                ProductOptionValue pov = pAttr.getProductOptionValue();
                                if (pov != null) {
                                    orderAttr.setProductOptionValue(pov.getName());
                                }

                                BigDecimal attrPrice = pAttr.getOptionValuePrice();

                                BigDecimal price = orderProduct.getProductPrice();
                                if (attrPrice != null && attrPrice.longValue() > 0) {
                                    price = price.add(attrPrice);
                                }

                                // string values
                                if (v.getAttributeValue() != null) {

                                    Map attrValues = v.getAttributeValue();
                                    String sValue = (String) attrValues.get(attrId);
                                    if (!StringUtils.isBlank(sValue)) {
                                        orderAttr.setProductOptionValue(sValue);
                                    }
                                }
                            } else {
                                LogMerchantUtil.log(v.getMerchantId(),
                                        getText("error.validation.product.attributes.ids", new String[] {
                                                String.valueOf(attrId), String.valueOf(v.getProductId()) }));
                            }
                        }
                    }

                    BigDecimal price = orderProduct.getProductPrice();
                    orderProduct.setFinalPrice(price);
                    orderProduct.setProductPrice(price);
                    orderProduct.setPriceText(
                            CurrencyUtil.displayFormatedAmountNoCurrency(price, store.getCurrency()));
                    orderProduct.setPriceFormated(
                            CurrencyUtil.displayFormatedAmountWithCurrency(price, store.getCurrency()));

                    // original price
                    orderProduct.setOriginalProductPrice(price);

                }

                if (!attributes.isEmpty()) {
                    CheckoutUtil.addAttributesToProduct(attributes, orderProduct, store.getCurrency(),
                            getLocale());
                }

                Set attributesSet = new HashSet(attributes);
                orderProduct.setOrderattributes(attributesSet);

                SessionUtil.addOrderProduct(orderProduct, getServletRequest());

            }

        }

    }

    // because this is a submission, cannot continue browsing, so that's it
    // for the OrderProduct
    Map orderProducts = SessionUtil.getOrderProducts(super.getServletRequest());

    // transform to a list
    List products = new ArrayList();
    if (orderProducts != null) {
        Iterator ii = orderProducts.keySet().iterator();
        while (ii.hasNext()) {
            String line = (String) ii.next();
            OrderProduct op = (OrderProduct) orderProducts.get(line);
            products.add(op);
        }
    }

    /**
     * Order total calculation
     */
    OrderTotalSummary summary = super.updateOrderTotal(order, products, store);

    this.setSummary(summary);
    ActionContext.getContext().getSession().put("TOKEN", String.valueOf(store.getMerchantId()));// set session token

}

From source file:org.apache.openjpa.jdbc.sql.SolidDBDictionary.java

@Override
public void setBigDecimal(PreparedStatement stmnt, int idx, BigDecimal val, Column col) throws SQLException {
    int type = (val == null || col == null) ? JavaTypes.BIGDECIMAL : col.getJavaType();
    switch (type) {
    case JavaTypes.DOUBLE:
    case JavaTypes.DOUBLE_OBJ:
        setDouble(stmnt, idx, val.doubleValue(), col);
        break;/*  www.  j ava2s  .c  o m*/
    case JavaTypes.FLOAT:
    case JavaTypes.FLOAT_OBJ:
        setFloat(stmnt, idx, val.floatValue(), col);
        break;
    case JavaTypes.LONG:
    case JavaTypes.LONG_OBJ:
        setLong(stmnt, idx, val.longValue(), col);
        break;
    default:
        super.setBigDecimal(stmnt, idx, val, col);
    }
}