Example usage for java.text NumberFormat parse

List of usage examples for java.text NumberFormat parse

Introduction

In this page you can find the example usage for java.text NumberFormat parse.

Prototype

public Number parse(String source) throws ParseException 

Source Link

Document

Parses text from the beginning of the given string to produce a number.

Usage

From source file:au.com.onegeek.lambda.core.provider.WebDriverBackedSeleniumProvider.java

public void clickAndWait(String id, String seconds) throws ParseException {
    NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
    Number number = format.parse(seconds);
    this.click(id);
    this.waitForPageToLoad(String.valueOf(number.intValue() * 1000));
}

From source file:org.kuali.rice.krad.demo.uif.lookup.TravelLookupableImpl.java

/**
 * Validates that any numeric value is non-negative.
 *
 * @param form lookup form instance containing the lookup data
 * @param propertyName property name of the search criteria field to be validated
 * @param searchPropertyValue value given for field to search for
 *///from w  ww .j a  va2 s .c o m
protected void validateSearchParameterPositiveValues(LookupForm form, String propertyName,
        String searchPropertyValue) {
    if (StringUtils.isBlank(searchPropertyValue)) {
        return;
    }

    NumberFormat format = NumberFormat.getInstance();
    Number number = null;
    try {
        number = format.parse(searchPropertyValue);
    } catch (ParseException e) {
        return;
    }

    if (Math.signum(number.doubleValue()) < 0) {
        GlobalVariables.getMessageMap().putError(propertyName,
                RiceKeyConstants.ERROR_NEGATIVES_NOT_ALLOWED_ON_FIELD, getCriteriaLabel(form, propertyName));
    }
}

From source file:org.brocalc.calculator.BaseSingleBrokerageSpec.java

public BrokerageResult calculateBrokerageForTrade(String currency, String usdNotional, String tradeDate,
        String settlementDate) throws ParseException {
    NumberFormat format = NumberFormat.getNumberInstance(Locale.US);
    BigDecimal usdAmount = new BigDecimal(format.parse(usdNotional).doubleValue());
    TradeInfo trade = mock(TradeInfo.class);
    when(trade.getCurrency()).thenReturn(Currency.getInstance(currency));
    when(trade.getUsdAmount()).thenReturn(usdAmount);
    if (tradeDate != null) {
        when(trade.getTradeDate()).thenReturn(new LocalDate(tradeDate));
    }/*from   w  w w. jav a 2s . c o m*/
    if (settlementDate != null) {
        when(trade.getSettlementDate()).thenReturn(new LocalDate(settlementDate));
    }
    BrokerageAmount brokerage = brokerageSchedule.calculateBrokerage(trade);
    return BrokerageResult.fromBrokerageAmount(brokerage);
}

From source file:org.kuali.rice.krad.demo.uif.lookup.LookupableTravelImpl.java

/**
 * Validates that any wildcards contained within the search value are valid wildcards and allowed for the
 * property type for which the field is searching.
 *
 * @param inputField attribute field instance for the field that is being searched
 * @param searchPropertyValue value given for field to search for
 *//*from   w  w  w.  j av  a  2 s . c  o m*/
protected void validateSearchParameterPositiveValues(InputField inputField, String searchPropertyValue) {
    if (StringUtils.isBlank(searchPropertyValue)) {
        return;
    }

    NumberFormat format = NumberFormat.getInstance();
    Number number = null;
    try {
        number = format.parse(searchPropertyValue);
    } catch (ParseException e) {
        return;
    }

    if (Math.signum(number.doubleValue()) < 0) {
        String attributeLabel = inputField.getLabel();
        GlobalVariables.getMessageMap().putError(inputField.getPropertyName(),
                RiceKeyConstants.ERROR_NEGATIVES_NOT_ALLOWED_ON_FIELD, attributeLabel);
    }
}

From source file:org.jboss.pnc.facade.rsql.StreamRSQLNodeTraveller.java

@Override
public Boolean visit(ComparisonNode node) {
    logger.trace("Parsing ComparisonNode {}", node);
    String fieldName = node.getSelector();
    String argument = node.getArguments().get(0);
    try {//from  w  w  w.j  a  v a 2 s .co m
        String propertyValue = BeanUtils.getProperty(instance, fieldName);
        if (node.getOperator().equals(RSQLProducerImpl.IS_NULL)) {
            return Boolean.valueOf(propertyValue == null).equals(Boolean.valueOf(argument));
        }
        if (propertyValue == null) {
            // Null values are considered not equal
            return false;
        }
        if (node.getOperator().equals(RSQLOperators.EQUAL)) {
            return propertyValue.equals(argument);
        } else if (node.getOperator().equals(RSQLOperators.NOT_EQUAL)) {
            return !propertyValue.equals(argument);
        } else if (node.getOperator().equals(RSQLOperators.GREATER_THAN)) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            Number argumentNumber = numberFormat.parse(argument);
            return numberFormat.parse(propertyValue).intValue() < argumentNumber.intValue();
        } else if (node.getOperator().equals(RSQLOperators.GREATER_THAN_OR_EQUAL)) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            Number argumentNumber = numberFormat.parse(argument);
            return numberFormat.parse(propertyValue).intValue() <= argumentNumber.intValue();
        } else if (node.getOperator().equals(RSQLOperators.LESS_THAN)) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            Number argumentNumber = numberFormat.parse(argument);
            return numberFormat.parse(propertyValue).intValue() > argumentNumber.intValue();
        } else if (node.getOperator().equals(RSQLOperators.GREATER_THAN_OR_EQUAL)) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            Number argumentNumber = numberFormat.parse(argument);
            return numberFormat.parse(propertyValue).intValue() >= argumentNumber.intValue();
        } else if (node.getOperator().equals(RSQLProducerImpl.LIKE)) {
            argument = argument.replaceAll(RSQLProducerImpl.UNKNOWN_PART_PLACEHOLDER, ".*").replaceAll("%",
                    ".*");
            return propertyValue.matches(argument);
        } else if (node.getOperator().equals(RSQLOperators.IN)) {
            return node.getArguments().contains(propertyValue);
        } else if (node.getOperator().equals(RSQLOperators.NOT_IN)) {
            return !node.getArguments().contains(propertyValue);
        } else {
            throw new UnsupportedOperationException("Not Implemented yet!");
        }
    } catch (NestedNullException e) {
        // If a nested property is null (i.e. idRev.id is null), it is considered a false equality
        return false;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw new IllegalStateException("Reflections exception", e);
    } catch (ParseException e) {
        throw new IllegalStateException("RSQL parse exception", e);
    }
}

From source file:org.jbpm.bpel.tutorial.shipping.ShippingPT_Impl.java

public void init(Object context) throws ServiceException {
    // initialize jms administered objects
    try {/*ww w  .j  av  a 2 s  .c  om*/
        initJmsObjects();
    } catch (Exception e) {
        throw new ServiceException("Could not initialize jms objects", e);
    }

    // retrieve servlet context
    ServletEndpointContext endpointContext = (ServletEndpointContext) context;
    ServletContext servletContext = endpointContext.getServletContext();

    // initialize shipping price parameter
    String shippingPriceString = servletContext.getInitParameter(SHIPPING_PRICE_PARAM);
    if (shippingPriceString == null) {
        throw new ServiceException("Required parameter not found: " + SHIPPING_PRICE_PARAM);
    }

    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
    try {
        shippingPrice = currencyFormat.parse(shippingPriceString).floatValue();
        log.debug("Set parameter: " + SHIPPING_PRICE_PARAM + ", value=" + shippingPrice);
    } catch (ParseException e) {
        throw new ServiceException("Invalid parameter: " + SHIPPING_PRICE_PARAM, e);
    }
}

From source file:org.davidmendoza.esu.web.EstudiaController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/popular/{posicion}", method = RequestMethod.GET)
@ResponseBody//from w w w  . j  a va  2s  . co  m
public Map popular(@PathVariable Integer posicion) throws ParseException {
    log.info("Populares Estudia({})", posicion);
    Map resultado = new HashMap();
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE", new Locale("es"));
    Popular popular = publicacionService.obtieneSiguientePopularEstudia(posicion);
    popular.getPublicacion().getArticulo()
            .setVistas(publicacionService.agregarVista(popular.getPublicacion().getArticulo()));
    Trimestre t = trimestreService
            .obtiene(popular.getPublicacion().getAnio() + popular.getPublicacion().getTrimestre());
    if (t != null) {
        Calendar cal = new GregorianCalendar(Locale.ENGLISH);
        cal.setTime(t.getInicia());
        cal.add(Calendar.SECOND, 1);
        cal.set(Calendar.DAY_OF_WEEK, obtieneDia(popular.getPublicacion().getDia()));
        NumberFormat nf = NumberFormat.getInstance();
        int weeks = ((Long) nf.parse(popular.getPublicacion().getLeccion().substring(1))).intValue();
        if (popular.getPublicacion().getDia().equals("sabado")) {
            weeks--;
        }
        cal.add(Calendar.WEEK_OF_YEAR, weeks);
        Date hoy = cal.getTime();
        resultado.put("dia", hoy);
        resultado.put("diaString", sdf.format(hoy));
    }
    resultado.put("publicacion", popular.getPublicacion());
    resultado.put("posicion", popular.getId());
    return resultado;
}

From source file:web.ShoweditbusinessController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException/*w w  w. j ava2 s  .c om*/
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // ***************************************************************************
    // This is the only line of code you need to get all session info initialized!
    // Always be the first line before anything else is done. Add to each controller's
    // handlRequest method. Also remember to extend SessionObject.
    // ***************************************************************************

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest");
    }
    outOfSession(request, response);

    if (!DiaryAdmin.isDiaryAdmin(login)) {
        return handleError("Access denied as the user is not diary admin, adding business" + login);
    }
    if (!WebUtil.isProductPremiumSubscription()) {
        return handleError("Cannot access this feature in non premimu subscription version.");
    }

    String bid = request.getParameter(DbConstants.BID);
    if (RegexStrUtil.isNull(bid)) {
        return handleError("bid is null in ShoweditbusinessController");
    }

    if (bid.length() > GlobalConst.bidSize) {
        return handleError("bid.length > WebConstants.bidSize, ShoweditbusinessController");
    }
    bid = RegexStrUtil.goodNameStr(bid);

    try {
        NumberFormat nf = NumberFormat.getInstance();
        Number myNum = nf.parse(bid);
    } catch (ParseException e) {
        return handleError("bid has other than [0-9] characters, ShoweditbusinessController.", e);
    }

    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null, in ShoweditbusinessController." + login);
    }

    Business business = null;
    try {
        BusinessDao businessDao = (BusinessDao) getDaoMapper().getDao(DbConstants.BUSINESS);
        if (businessDao == null) {
            return handleError("BusinessDao is null, in ShoweditbusinessController." + login);
        }
        business = businessDao.getBusiness(login, bid, DbConstants.READ_FROM_MASTER);
    } catch (BaseDaoException e) {
        return handleError(
                "Exception occurred in getBusiness(), ShoweditbusinessController, for login " + login, e);
    }

    if (business == null) {
        return handleError("business is null, ShoweditbusinessController, for login " + login);
    }

    /** 
     * cobrand
     */
    Userpage cobrand = null;
    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleError("CobrandDao is null, ShoweditbusinessController");
    }
    try {
        cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("cobrand is null, ShoweditbusinessController.", e);
    }

    Map myModel = new HashMap();
    String viewName = DbConstants.EDIT_BUSINESS;
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.BUSINESS, business);
    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);
}

From source file:web.ShowbusinessusersController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException//from  w  ww. j  a v  a 2  s .co  m
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // ***************************************************************************
    // This is the only line of code you need to get all session info initialized!
    // Always be the first line before anything else is done. Add to each controller's
    // handlRequest method. Also remember to extend SessionObject.
    // ***************************************************************************

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest");
    }
    outOfSession(request, response);

    if (!DiaryAdmin.isDiaryAdmin(login)) {
        return handleError("Access denied as the user is not diary admin, adding business" + login);
    }
    if (!WebUtil.isProductPremiumSubscription()) {
        return handleError("Cannot access this feature in non premimu subscription version.");
    }

    String bid = request.getParameter(DbConstants.BID);
    if (RegexStrUtil.isNull(bid)) {
        return handleError("bid is null in ShowbusinessusersController");
    }

    if (bid.length() > GlobalConst.bidSize) {
        return handleError("bid.length > WebConstants.bidSize, ShowbusinessusersController");
    }

    try {
        NumberFormat nf = NumberFormat.getInstance();
        Number myNum = nf.parse(bid);
    } catch (ParseException e) {
        return handleError("bid has other than [0-9] characters, ShowbusinessusersController.", e);
    }
    bid = RegexStrUtil.goodNameStr(bid);

    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null, in ShowbusinessusersController." + login);
    }

    List userList = null;
    Business business = null;
    try {
        BusinessDao businessDao = (BusinessDao) getDaoMapper().getDao(DbConstants.BUSINESS);
        if (businessDao == null) {
            return handleError("BusinessDao is null, in ShowbusinessusersController." + login);
        }
        business = businessDao.getBusiness(login, bid, DbConstants.READ_FROM_MASTER);
        userList = businessDao.getUserList(login, bid, DbConstants.READ_FROM_MASTER);
    } catch (BaseDaoException e) {
        return handleError(
                "Exception occurred in addContact(), ShowbusinessusersController, for login " + login, e);
    }

    /** 
     * cobrand
     */
    Userpage cobrand = null;
    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleError("CobrandDao is null, ShowbusinessusersController");
    }
    try {
        cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("cobrand is null, ShowbusinessusersController.", e);
    }

    Map myModel = new HashMap();
    String viewName = DbConstants.SHOW_BUSINESS_USERS;
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    myModel.put(DbConstants.BUSINESS, business);
    myModel.put(DbConstants.USER_LIST, userList);
    myModel.put(DbConstants.PAGE_NUM, request.getParameter(DbConstants.PAGE_NUM));
    return new ModelAndView(viewName, "model", myModel);
}

From source file:web.ViewbusinessController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException/*from   ww  w. j av  a2s .c  o m*/
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // ***************************************************************************
    // This is the only line of code you need to get all session info initialized!
    // Always be the first line before anything else is done. Add to each controller's
    // handlRequest method. Also remember to extend SessionObject.
    // ***************************************************************************

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest");
    }

    outOfSession(request, response);

    if (!DiaryAdmin.isDiaryAdmin(login)) {
        return handleError("Access denied as the user is not diary admin, adding business" + login);
    }
    if (!WebUtil.isProductPremiumSubscription()) {
        return handleError("Cannot access this feature in non premimu subscription version.");
    }

    String bid = request.getParameter(DbConstants.BID);
    if (RegexStrUtil.isNull(bid)) {
        return handleError("bid is null in ViewbusinessController");
    }

    if (bid.length() > GlobalConst.bidSize) {
        return handleError("bid.length > WebConstants.bidSize, ViewbusinessController");
    }

    try {
        NumberFormat nf = NumberFormat.getInstance();
        Number myNum = nf.parse(bid);
    } catch (ParseException e) {
        return handleError("bid has other than [0-9] characters, ViewbusinessController.", e);
    }
    bid = RegexStrUtil.goodNameStr(bid);

    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null, in ViewbusinessController." + login);
    }

    Business business = null;
    try {
        BusinessDao businessDao = (BusinessDao) getDaoMapper().getDao(DbConstants.BUSINESS);
        if (businessDao == null) {
            return handleError("BusinessDao is null, in ViewbusinessController." + login);
        }
        business = businessDao.getBusiness(login, bid, DbConstants.READ_FROM_MASTER);
    } catch (BaseDaoException e) {
        return handleError("Exception occurred in getBusiness(), ViewbusinessController, for login " + login,
                e);
    }

    if (business == null) {
        return handleError("business is null " + login);
    }

    /** 
     * cobrand
     */
    Userpage cobrand = null;
    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleError("CobrandDao is null, ViewbusinessController");
    }
    try {
        cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("cobrand is null, ViewbusinessController.", e);
    }

    Map myModel = new HashMap();
    String viewName = DbConstants.VIEW_BUSINESS;
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.BUSINESS, business);
    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);
}