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.manydesigns.portofino.pageactions.crud.CrudAction4ItsProject.java

private void addFieldToCell(WritableSheet sheet, int i, int j, Field field) throws WriteException {
    if (field instanceof NumericField) {
        NumericField numField = (NumericField) field;
        if (numField.getValue() != null) {
            Number number;//from  w w w  . j a v  a  2  s . co m
            BigDecimal decimalValue = numField.getValue();
            if (numField.getDecimalFormat() == null) {
                number = new Number(j, i, decimalValue == null ? null : decimalValue.doubleValue());
            } else {
                NumberFormat numberFormat = new NumberFormat(numField.getDecimalFormat().toPattern());
                WritableCellFormat writeCellNumberFormat = new WritableCellFormat(numberFormat);
                number = new Number(j, i, decimalValue == null ? null : decimalValue.doubleValue(),
                        writeCellNumberFormat);
            }
            sheet.addCell(number);
        }
    } else if (field instanceof PasswordField) {
        jxl.write.Label label = new jxl.write.Label(j, i, PasswordField.PASSWORD_PLACEHOLDER);
        sheet.addCell(label);
    } else if (field instanceof DateField) {
        DateField dateField = (DateField) field;
        DateTime dateCell;
        Date date = dateField.getValue();
        if (date != null) {
            DateFormat dateFormat = new DateFormat(dateField.getDatePattern());
            WritableCellFormat wDateFormat = new WritableCellFormat(dateFormat);
            dateCell = new DateTime(j, i, dateField.getValue() == null ? null : dateField.getValue(),
                    wDateFormat);
            sheet.addCell(dateCell);
        }
    } else {
        jxl.write.Label label = new jxl.write.Label(j, i, field.getStringValue());
        sheet.addCell(label);
    }
}

From source file:com.autentia.tnt.bean.admin.ProjectBean.java

public String getCostPerProject() {
    BigDecimal total = project.getCostPerProject();
    String totalCost = null;// w  w  w  .  ja v a  2 s .  c  o  m

    NumberFormat format = NumberFormat.getInstance();
    format.setMaximumFractionDigits(2);
    totalCost = format.format(total.doubleValue());

    return totalCost;
}

From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java

@Override
@Transactional(readOnly = true)//from w  w  w.  j  a  v  a2  s.  c  om
public Map<String, Object> getShopDetail(String shopNo, String memberNo) throws Exception {
    String sql = "select " + " tsi.shop_name shopName," + " tsi.status status," + " tsi.shop_logo shopLogo,"
            + " tsi.shop_type_no shopTypeNo," + " tsi.shop_address address," + " tsi.shop_summary summary,"//
            + " tsi.phone phone,"//?
            + " tsi.merch_no memberNo,"//?
            + " tsi.begin_time beginTime,"//?
            + " tsi.end_time endTime,"//??
            + " tsi.shop_sign shopSign,"//
            + " tsi.sell_scope sellScope,"//??
            + " tsi.delivery_type deliveryType,"//??
            + " ifnull(tsi.delivery_fee,0) deliveryFee,"//?
            + " tsi.company_name companyName,"//???
            + " tsi.license_regist_no licenseRegistNo,"//??
            + " if(tsi.is_recommend is null,'0',tsi.is_recommend) isRecommend "
            + " from tbl_shop_info tsi where tsi.shop_no = :shopNo";
    Query query = shopDao.createSQLQuery(sql);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    Map<String, Object> map = (Map<String, Object>) query.uniqueResult();
    String sqlComment = "select avg(tcc.service_grade) serviceGrade,avg(tcc.delivery_grade) deliveryGrade "
            + " from tbl_commodity_comment tcc where tcc.shop_no=:shopNo";
    query = shopDao.createSQLQuery(sqlComment);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    if (map != null) {
        Map<String, Object> mapComment = (Map<String, Object>) query.uniqueResult();
        if (mapComment != null) {
            Double servGrade = mapComment.get("serviceGrade") == null ? 0
                    : Double.valueOf(mapComment.get("serviceGrade").toString());
            BigDecimal serviceGrade = new BigDecimal(servGrade);
            serviceGrade = serviceGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
            map.put("serviceGrade", serviceGrade.doubleValue());
            Double delGrade = mapComment.get("deliveryGrade") == null ? 0
                    : Double.valueOf(mapComment.get("deliveryGrade").toString());
            BigDecimal deliveryGrade = new BigDecimal(delGrade);
            deliveryGrade = deliveryGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
            map.put("deliveryGrade", deliveryGrade.doubleValue());
        } else {
            map.put("serviceGrade", 0);
            map.put("deliveryGrade", 0);
        }
    }

    if (map != null) {
        map.put("promotions", promotionService.getPromotionByShopNo(shopNo, memberNo));
    }
    String sqlProduct = "select IF(tp.prod_name is null,'',tp.prod_name) prodName," + "tp.model model,"
            + " IF(tp.default_pic is null,'',tp.default_pic) prodPic," + " tp.price prodPrice,"
            + " tp.is_groupbuy isGroupbuy," + " tp.prod_no prodNo," + " tp.sort sort,"
            + " ifnull(tp.stock,0) stock," + " ifnull(tp.stock_preemption,0) stockPreemption,"
            + " IF(tp.sell_num is null,0,tp.sell_num) sellNum "
            + " from tbl_product tp left join tbl_commodity tc on tc.commo_no = tp.commo_no"
            + " where tc.seller_no = :shopNo and tc.publish_state ='1' and (tp.is_groupbuy is null or tp.is_groupbuy='1') and tp.delete_flag ='0' order by ifnull(tp.sort,2147483647) asc,tc.publish_time desc";
    query = productDao.createSQLQuery(sqlProduct);
    //      query.setMaxResults(10);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> prods = query.list();
    if (prods != null && !prods.isEmpty()) {
        for (Map<String, Object> r : prods) {
            //????+
            String prodName = (String) (r.get("prodName") == null ? "" : r.get("prodName"));
            String model = (String) (r.get("model") == null ? "" : r.get("model"));
            if (model != null && !model.equals("")) {
                r.put("prodName", prodName + "(" + model + ")");
            }
        }
    }

    if (map != null) {
        map.put("products", prods);
    }
    String sqlGroupBuyProduct = "select IF(tp.prod_name is null,'',tp.prod_name) prodName," + "tp.model model,"
            + " IF(tp.default_pic is null,'',tp.default_pic) prodPic," + " tp.price prodPrice,"
            + " tp.is_groupbuy isGroupbuy," + " tp.prod_no prodNo," + " tp.sort sort,"
            + " ifnull(tp.stock,0) stock," + " tpromotion.promotion_no promotionNo,"
            + " tpromotion.discount_amount groupbuyPrice," + " tpromotion.end_time endTime,"
            + " ifnull(tp.stock_preemption,0) stockPreemption,"
            + " IF(tp.sell_num is null,0,tp.sell_num) sellNum "
            + " from tbl_product tp left join tbl_commodity tc on tc.commo_no = tp.commo_no"
            + " left join tbl_promotion tpromotion on tpromotion.ref_commo_no = tc.commo_no"
            + " where tc.seller_no = :shopNo and tc.publish_state ='1'  and tp.is_groupbuy='2' and tpromotion.status='2' "
            + " and now() between tpromotion.start_time and tpromotion.end_time "
            + " and tpromotion.delete_flag ='0' and tp.delete_flag ='0' order by ifnull(tp.sort,2147483647) asc,tc.publish_time desc";
    query = productDao.createSQLQuery(sqlGroupBuyProduct);
    //      query.setMaxResults(10);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> groupBuyProds = query.list();
    if (groupBuyProds != null && !groupBuyProds.isEmpty()) {
        for (Map<String, Object> gpd : groupBuyProds) {
            //????+
            String prodName = (String) (gpd.get("prodName") == null ? "" : gpd.get("prodName"));
            String model = (String) (gpd.get("model") == null ? "" : gpd.get("model"));
            if (model != null && !model.equals("")) {
                gpd.put("prodName", prodName + "(" + model + ")");
            }

            String promotionNo = (String) gpd.get("promotionNo");
            Order buyerOrder = this.getOrderByBuyer(promotionNo, memberNo);
            if (buyerOrder != null) {
                if (buyerOrder.getBasicState().equals(OrderConstants.BASIC_STATE_WAITING_PAY))
                    gpd.put("buyed", "1");//
                else
                    gpd.put("buyed", "2");//
            } else {
                gpd.put("buyed", "0");
            }
        }
    }
    if (map != null) {
        map.put("groupBuyProds", groupBuyProds);
    }

    String sqlCollect = "select * from tbl_shop_collect tsc where tsc.shop_no = :shopNo ";
    Query queryC = shopCollectDao.createSQLQuery(sqlCollect);
    queryC.setParameter("shopNo", shopNo);
    List listCollect = queryC.list();
    if (map != null) {
        map.put("collectNum", listCollect == null ? 0 : listCollect.size());
    }
    //      Query queryCollect = shopCollectDao.createSQLQuery(sqlCollect+"and tsc.member_no = :memberNo");
    //      queryCollect.setParameter("shopNo", shopNo);
    //      queryCollect.setParameter("memberNo", memberNo);
    //      List list = queryCollect.list();
    //      map.put("isCollect", list!=null&&!list.isEmpty()?"1":"0");
    String sqlCat = "select tc.cat_no catNo," + " IF(tcat.cat_name is null,'',tcat.cat_name) catName "
            + " from tbl_commodity tc " + " left join tbl_commo_category tcat "
            + " on tc.cat_no = tcat.cat_no where seller_no = :shopNo group by(tcat.cat_no)";
    query = commodityCatDao.createSQLQuery(sqlCat);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> cats = query.list();
    if (map != null) {
        map.put("cats", cats);
    }
    if (map != null && map.get("shopSign") == null) {
        map.put("shopSign", "");
    }
    return map;
}

From source file:it.govpay.web.rs.dars.monitoraggio.rendicontazioni.RendicontazioniHandler.java

@Override
public Map<String, Voce<String>> getVoci(Rendicontazione entry, BasicBD bd) throws ConsoleException {
    Map<String, Voce<String>> voci = new HashMap<String, Voce<String>>();

    if (StringUtils.isNotEmpty(entry.getIuv())) {
        voci.put(/*from  www. j  a  va2s  . c  o m*/
                Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".iuv.id"),
                new Voce<String>(Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".iuv.label"), entry.getIuv()));
    }

    if (StringUtils.isNotEmpty(entry.getIur())) {
        voci.put(
                Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".iur.id"),
                new Voce<String>(Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".iur.label"), entry.getIur()));
    }

    StatoRendicontazione stato = entry.getStato();
    if (stato != null) {
        voci.put(
                Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".stato.id"),
                new Voce<String>(this.getSottotitolo(entry, bd), stato.name()));
    }

    EsitoRendicontazione esito = entry.getEsito();
    if (stato != null) {
        voci.put(
                Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".esito.id"),
                new Voce<String>(esito.name(), esito.getCodifica() + ""));
    }

    if (entry.getData() != null) {
        voci.put(
                Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".data.id"),
                new Voce<String>(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                        this.nomeServizio + ".data.label"), this.sdf.format(entry.getData())));
    }

    BigDecimal importoPagato = entry.getImporto() != null ? entry.getImporto() : BigDecimal.ZERO;
    voci.put(
            Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".importo.id"),
            new Voce<String>(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                    this.nomeServizio + ".importo.label"), importoPagato.doubleValue() + ""));

    if (entry.getAnomalie() != null && entry.getAnomalie().size() > 0) {
        voci.put(
                Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".anomalie.id"),
                new Voce<String>(Utils.getInstance(this.getLanguage())
                        .getMessageFromResourceBundle(this.nomeServizio + ".anomalie.label"), ""));

        for (int i = 0; i < entry.getAnomalie().size(); i++) {
            Anomalia anomalia = entry.getAnomalie().get(i);
            voci.put(
                    Utils.getInstance(this.getLanguage())
                            .getMessageFromResourceBundle(this.nomeServizio + ".anomalie.id") + "_" + i,
                    new Voce<String>(anomalia.getCodice(), anomalia.getDescrizione()));
        }
    }
    try {
        Pagamento pagamento = entry.getPagamento(bd);
        String codDominio = null;
        if (pagamento != null) {
            codDominio = pagamento.getCodDominio();

            SingoloVersamento singoloVersamento = pagamento.getSingoloVersamento(bd);
            if (singoloVersamento != null) {
                voci.put(
                        Utils.getInstance(this.getLanguage())
                                .getMessageFromResourceBundle(this.nomeServizio + ".codSingoloVersamento.id"),
                        new Voce<String>(
                                Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                                        this.nomeServizio + ".codSingoloVersamento.label"),
                                singoloVersamento.getCodSingoloVersamentoEnte()));
            }

        } else {
            Fr fr = entry.getFr(bd);
            codDominio = fr.getCodDominio();
        }

        if (StringUtils.isNotEmpty(codDominio)) {
            try {
                Dominio dominio = AnagraficaManager.getDominio(bd, codDominio);
                Domini dominiDars = new Domini();
                DominiHandler dominiDarsHandler = (DominiHandler) dominiDars.getDarsHandler();
                String dominioTitolo = dominiDarsHandler.getTitolo(dominio, bd);
                voci.put(
                        Utils.getInstance(this.getLanguage())
                                .getMessageFromResourceBundle(this.nomeServizio + ".dominio.id"),
                        new Voce<String>(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                                this.nomeServizio + ".dominio.label"), dominioTitolo));
            } catch (NotFoundException e) {
            }
        }
    } catch (ServiceException e) {

    }

    return voci;

}

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

private String generateHtmlDesc(Locality loc) {
    BigDecimal lat = loc.getLatitude1();
    BigDecimal lon = loc.getLongitude1();

    Element desc = DocumentHelper.createElement("div");
    //        desc.addElement("h3").addText(getResourceString("GE_LOCALITY"));

    Element table = desc.addElement("table");
    Element tr = table.addElement("tr");
    tr.addElement("td").addAttribute("style", "color:#" + textColor + "; text-align:right")
            .addText(getResourceString("Latitude") + ":");
    tr.addElement("td").addAttribute("style", "color:#" + textColor).addText("" + lat.doubleValue());

    tr = table.addElement("tr");
    tr.addElement("td").addAttribute("style", "color:#" + textColor + "; text-align:right")
            .addText(getResourceString("Longitude") + ":");
    tr.addElement("td").addAttribute("style", "color:#" + textColor).addText("" + lon.doubleValue());

    if (loc.getGeography() != null) {
        tr = table.addElement("tr");
        tr.addElement("td").addAttribute("style", "color:#" + textColor + "; text-align:right")
                .addText(getResourceString("Geography") + ":");
        tr.addElement("td").addAttribute("style", "color:#" + textColor)
                .addText(loc.getGeography().getFullName());
    }/*from   w  ww  . jav  a  2  s  .  c  om*/

    return XMLtoString(desc);
}

From source file:ejb.session.loan.LoanPaymentSessionBean.java

@Override
public String loanLumsumPaymentFromAccount(String loanAccountNumber, String depositAccountNumber,
        BigDecimal amount) {

    try {//from   w w w.  j  a v a2  s  .com

        DepositAccount fromAccount = depositBean.getAccountFromId(depositAccountNumber);
        LoanAccount loanAccount = loanAccountBean.getLoanAccountByAccountNumber(loanAccountNumber);
        if (fromAccount.getBalance().compareTo(amount) < 0) {
            // not enough money
            return "FAIL1";
        } else {
            System.out.println("success" + amount);
            depositBean.transferFromAccount(fromAccount, amount);
            BigDecimal outPrin = new BigDecimal(loanAccount.getOutstandingPrincipal());
            if (amount.compareTo(outPrin) == 1) {
                return "FAIL2";
            }
            LoanAccount la = loanAccountLumsumPayment(loanAccountNumber, amount.doubleValue());
            futurePaymentBreakdown(la);
            return "SUCCESS";
        }

    } catch (DepositAccountNotFoundException e) {
        System.out.println(
                "DepositAccountNotFoundException LoanRepaymentSessionBean loanLumsumPaymentFromAccount()");
        return "FAIL0";
    }

}

From source file:ch.algotrader.service.OptionServiceImpl.java

/**
 * {@inheritDoc}//w w  w. j a v  a  2s  . c o m
 */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Option getOptionByMinExpirationAndStrikeLimit(final long underlyingId, final Date targetExpirationDate,
        final BigDecimal underlyingSpot, final OptionType optionType) {

    Validate.notNull(targetExpirationDate, "Target expiration date is null");
    Validate.notNull(underlyingSpot, "Underlying spot is null");
    Validate.notNull(optionType, "Option type is null");

    OptionFamily family = this.optionFamilyDao.findByUnderlying(underlyingId);

    Option option = CollectionUtil.getSingleElementOrNull(this.optionDao.findByMinExpirationAndStrikeLimit(1,
            underlyingId, targetExpirationDate, underlyingSpot, optionType));

    // if no future was found, create it if simulating options
    if (this.commonConfig.isSimulation() && this.coreConfig.isSimulateOptions()) {
        if ((option == null)
                || Math.abs(option.getStrike().doubleValue() - underlyingSpot.doubleValue()) > family
                        .getStrikeDistance()) {

            option = createDummyOption(family.getId(), targetExpirationDate, underlyingSpot, optionType);
        }
    }

    if (option == null) {
        throw new ServiceException("no option available for expiration " + targetExpirationDate + " strike "
                + underlyingSpot + " type " + optionType);
    } else {
        return option;
    }

}

From source file:ejb.session.loan.LoanPaymentSessionBean.java

@Override
public String loanRepaymentFromAccount(String loanAccountNumber, String depositAccountNumber,
        BigDecimal amount) {

    try {// w w w . j a  va2s  .co  m
        DepositAccount fromAccount = depositBean.getAccountFromId(depositAccountNumber);
        LoanAccount loanAccount = loanAccountBean.getLoanAccountByAccountNumber(loanAccountNumber);
        if (fromAccount.getBalance().compareTo(amount) < 0) {
            // not enough money
            return "FAIL";
        } else {
            depositBean.transferFromAccount(fromAccount, amount);
            BigDecimal outPrin = new BigDecimal(loanAccount.getOutstandingPrincipal());
            if (amount.compareTo(outPrin) > 0) {
                return "FAIL2";
            }
            if (amount.compareTo(new BigDecimal(10000)) >= 0) {
                return "FAIL3";
            }
            loanAccountRepayment(loanAccountNumber, amount.doubleValue());
            return "SUCCESS";
        }

    } catch (DepositAccountNotFoundException e) {
        System.out
                .println("DepositAccountNotFoundException LoanRepaymentSessionBean loanRepaymentFromAccount()");
        return "FAIL0";
    }

}

From source file:com.cecs492a_group4.sp.SingleEvent.java

public synchronized void getYelpSearchResult(final int index1, final String searchToken, final String Address)
        throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override// ww w  .  j ava 2 s. c om
        public void run() {
            int randPick = ran.nextInt(limit);
            try {
                String name = "ldkfldsjkfd";
                int full = 0;
                do {

                    randPick = ran.nextInt(limit);
                    System.out.println("Event number : " + index1);
                    System.out.println(randPick);
                    System.out.println("Index: " + randPick);
                    response = yelp.searchByLocation(searchToken, Address, SingleEvent.currentRadius);
                    System.out.println("The current radius : " + SingleEvent.currentRadius);
                    System.out.println(searchToken + " gave me this response: " + response);
                    yp.setResponse(response);
                    // yp.parseBusiness();

                    int nameSIndex = response.indexOf("\"name\"", 1) + 8;

                    for (int i = 0; i < randPick; i++) {
                        nameSIndex = response.indexOf("\"name\"", ++nameSIndex) + 8;
                    }
                    int nameEIndex = response.indexOf("\",", ++nameSIndex);

                    String tmp = response;
                    name = tmp.substring(nameSIndex, nameEIndex);
                    System.out.println(name);
                    full++;
                    if (full >= 4) {
                        full = 0;
                        bussinessNames.clear(); //no more options reset array
                    }
                } while (bussinessNames.contains(name));

                try {
                    bussinessNames.add(index1, name);
                } catch (IndexOutOfBoundsException e) {
                    System.out.println("Array size " + bussinessNames.size());
                    bussinessNames.clear();
                }
                int imgSIndex = response.indexOf("\"image_url\"", 1) + 13;
                int ratingSIndex = response.indexOf("\"rating_img_url\"", 1) + 18;
                int urlSIndex = response.indexOf("\"mobile_url\"", 1) + 14;
                int phoneSIndex = response.indexOf("\"phone\":", 1) + 9;
                int addressSIndex = response.indexOf("\"display_address\"", 1) + 19;
                int distanceSIndex = response.indexOf("\"distance\"", 1) + 12;
                System.out.println("Start index :" + distanceSIndex);
                for (int i = 0; i < randPick; i++) {

                    imgSIndex = response.indexOf("\"image_url\"", ++imgSIndex) + 13;
                    ratingSIndex = response.indexOf("\"rating_img_url\"", ++ratingSIndex) + 18;
                    urlSIndex = response.indexOf("\"mobile_url\"", ++urlSIndex) + 14;
                    phoneSIndex = response.indexOf("\"phone\":", ++phoneSIndex) + 9;
                    addressSIndex = response.indexOf("\"display_address\"", ++addressSIndex) + 19;
                    distanceSIndex = response.indexOf("\"distance\"", ++distanceSIndex) + 12;
                }

                int ratingEIndex = response.indexOf("g\"", ++ratingSIndex) + 1;
                int imgEIndex = response.indexOf("g\"", ++imgSIndex) + 1;
                int phoneEIndex = response.indexOf("\",", ++phoneSIndex);
                int urlEIndex = response.indexOf("rating_img_url", ++urlSIndex) - 4;
                int addressEIndex = response.indexOf("\"], ", ++addressSIndex) + 1;

                //System.out.println("distance = " + response.substring(distanceSIndex,distanceSIndex + 9));
                //String distance = yp.getBusinessDistance(randPick);
                String distance = response.substring(distanceSIndex, distanceSIndex + 9);
                System.out.println("Distance: " + distance);
                double dis;
                try {
                    dis = Double.parseDouble(distance);
                } catch (NumberFormatException e) {
                    dis = 0.0;
                }
                System.out.println("Distance in meters:" + dis);
                System.out.println("Distance in miles:" + meters_to_miles(dis));
                BigDecimal bd = new BigDecimal(meters_to_miles(dis));
                bd = bd.round(new MathContext(2));
                dis = bd.doubleValue();
                System.out.println("dis after conversion " + dis);
                //distance = distance.substring(distanceSIndex,distanceEIndex);

                //activity = yp.getBusinessName(randPick);
                activity = name;
                //rating = yp.getBusinessRating(randPick);
                //I am going to parse the url my self fucking yelp!

                // int imgEIndex = response.indexOf("location",imgSIndex) - 4;
                String phoneNumber = response;
                phoneNumber = phoneNumber.substring(phoneSIndex, phoneEIndex);
                System.out.println("Phone number: " + phoneNumber);
                String tmp2 = response;
                tmp2 = tmp2.substring(imgSIndex, imgEIndex);
                System.out.println("mylink " + tmp2);
                //img_url = yp.getBusinessImageURL(randPick);
                img_url = tmp2;
                System.out.println(img_url);
                //rating_url = yp.getBusinessRatingUrl(randPick);
                String ratingURL = response;
                ratingURL = ratingURL.substring(ratingSIndex, ratingEIndex);
                System.out.println(ratingURL);

                String weburl = response;
                weburl = weburl.substring(urlSIndex, urlEIndex);
                System.out.println("Event URL: " + weburl);

                String eventaddress = response;
                eventaddress = eventaddress.substring(addressSIndex, addressEIndex);

                System.out.println("default Event Address" + eventaddress);

                int streaddSindex = eventaddress.indexOf("\"") + 1;

                int streaddEindex = eventaddress.indexOf("\",");
                int cityaddSindex = 1;
                try {
                    cityaddSindex = eventaddress.indexOf("\", \"") + 4;
                } catch (StringIndexOutOfBoundsException e) {
                    cityaddSindex = 0;
                    System.out.println("No city");
                }

                String streetadd = " ";
                try {
                    streetadd = eventaddress.substring(streaddSindex, streaddEindex);
                } catch (StringIndexOutOfBoundsException e) {
                    if (!Character.isDigit(eventaddress.charAt(0))) {
                        System.out.println("Faulty address");
                        streetadd = " ";
                    }
                }
                System.out.println("Street address:" + streetadd);
                String cityadd;
                if (cityaddSindex != 0)
                    cityadd = eventaddress.substring(cityaddSindex).replace("\"", "");
                else
                    cityadd = " ";

                System.out.println("City location: " + cityadd);
                eventaddress = streetadd + " " + cityadd;
                System.out.println("adjusted Event Address: " + eventaddress);

                //System.out.println(ratingURL);
                event_address = eventaddress;
                phoneNum = phoneNumber;
                web_url = weburl;
                rating_url = ratingURL;
                icon_url = new URL(img_url);
                url_rating = new URL(rating_url);
                try {
                    dayevent.add(index1, new DayEvent(activity, icon_url, url_rating, searchToken, dis, web_url,
                            phoneNum, event_address));
                } catch (IndexOutOfBoundsException e) {
                    System.out.println("Size of day event " + dayevent.size());
                }
                //} catch (JSONException e) {
                //e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    });
    thread.start();
    //test by removing the while loops (bad practice)
    /**       while (response == null) {
           }
           while (activity == null) {
           }
           while (web_url == null) {
           }
           while (img_url == null) {
           }
           while (rating_url == null) {
           }**/
    thread.join();

}

From source file:ch.algotrader.service.OptionServiceImpl.java

/**
 * {@inheritDoc}/*from   w w  w.  j  a  v  a  2s. co m*/
 */
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Option getOptionByMinExpirationAndMinStrikeDistance(final long underlyingId,
        final Date targetExpirationDate, final BigDecimal underlyingSpot, final OptionType optionType) {

    Validate.notNull(targetExpirationDate, "Target expiration date is null");
    Validate.notNull(underlyingSpot, "Underlying spot is null");
    Validate.notNull(optionType, "Option type is null");

    Option option = CollectionUtil
            .getSingleElementOrNull(this.optionDao.findByMinExpirationAndMinStrikeDistance(1, underlyingId,
                    targetExpirationDate, underlyingSpot, optionType));

    // if no stock option was found, create it if simulating options
    if (this.commonConfig.isSimulation() && this.coreConfig.isSimulateOptions()) {

        OptionFamily family = this.optionFamilyDao.findByUnderlying(underlyingId);
        if ((option == null)
                || Math.abs(option.getStrike().doubleValue() - underlyingSpot.doubleValue()) > family
                        .getStrikeDistance()) {

            option = createDummyOption(family.getId(), targetExpirationDate, underlyingSpot, optionType);
        }
    }

    if (option == null) {
        throw new ServiceException("no option available for expiration " + targetExpirationDate + " strike "
                + underlyingSpot + " type " + optionType);
    } else {
        return option;
    }

}