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:savant.chromatogram.ChromatogramPlugin.java

@Override
public void init(JPanel panel) {

    NavigationUtils.addLocationChangedListener(new Listener<LocationChangedEvent>() {
        @Override//from  www . j  av a  2  s . com
        public void handleEvent(LocationChangedEvent event) {
            updateChromatogram();
        }
    });
    GenomeUtils.addGenomeChangedListener(new Listener<GenomeChangedEvent>() {
        @Override
        public void handleEvent(GenomeChangedEvent event) {
            updateChromatogram();
        }
    });
    panel.setLayout(new GridBagLayout());
    panel.setBorder(BorderFactory.createEtchedBorder());
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.EAST;
    panel.add(new JLabel("File:"), gbc);

    pathField = new JTextField();
    gbc.gridwidth = 3;
    gbc.weightx = 1.0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    panel.add(pathField, gbc);

    JButton browseButton = new JButton("Browse\u2026");
    browseButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            File f = DialogUtils.chooseFileForOpen("Chromatogram File", null, null);
            if (f != null) {
                try {
                    pathField.setText(f.getAbsolutePath());
                    if (canvas != null) {
                        canvas.getParent().remove(canvas);
                        canvas = null;
                    }
                    chromatogram = ChromatogramFactory.create(f);
                    updateEndField();
                    updateChromatogram();
                } catch (UnsupportedChromatogramFormatException x) {
                    DialogUtils.displayMessage("Unable to Open Chromatogram", String.format(
                            "<html><i>%s</i> does not appear to be a valid chromatogram file.<br><br><small>Supported formats are ABI and SCF.</small></html>",
                            f.getName()));
                } catch (Exception x) {
                    DialogUtils.displayException("Unable to Open Chromatogram",
                            String.format("<html>There was an error opening <i>%s</i>.</html>", f.getName()),
                            x);
                }
            }
        }
    });
    gbc.weightx = 0.0;
    gbc.fill = GridBagConstraints.NONE;
    panel.add(browseButton, gbc);

    JLabel startLabel = new JLabel("Start Base:");
    gbc.gridy++;
    gbc.gridwidth = 1;
    gbc.anchor = GridBagConstraints.EAST;
    panel.add(startLabel, gbc);

    startField = new JTextField("0");
    startField.setColumns(12);
    startField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            updateEndField();
        }
    });
    gbc.weightx = 0.5;
    gbc.anchor = GridBagConstraints.WEST;
    panel.add(startField, gbc);

    JLabel endLabel = new JLabel("End Base:");
    gbc.weightx = 0.0;
    gbc.anchor = GridBagConstraints.EAST;
    panel.add(endLabel, gbc);

    endField = new JTextField();
    endField.setColumns(12);
    endField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                NumberFormat numberParser = NumberFormat.getIntegerInstance();
                int endBase = numberParser.parse(endField.getText()).intValue();
                if (chromatogram != null) {
                    int startBase = endBase - chromatogram.getSequenceLength();
                    startField.setText(String.valueOf(startBase));
                    if (canvas != null) {
                        canvas.updatePos(startBase);
                    }
                }
            } catch (ParseException x) {
                Toolkit.getDefaultToolkit().beep();
            }
        }
    });
    gbc.weightx = 0.5;
    gbc.anchor = GridBagConstraints.WEST;
    panel.add(endField, gbc);

    JCheckBox fillCheck = new JCheckBox("Fill Background");
    fillCheck.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            canvas.updateFillbackground(((JCheckBox) ae.getSource()).isSelected());
        }
    });
    gbc.gridy++;
    gbc.gridx = 1;
    gbc.weightx = 0.0;
    panel.add(fillCheck, gbc);

    // Add a filler panel at the bottom to force our components to the top.
    gbc.gridy++;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weighty = 1.0;
    panel.add(new JPanel(), gbc);
}

From source file:org.jboss.pnc.datastore.predicates.rsql.RSQLNodeTravellerPredicate.java

public java.util.function.Predicate<Entity> getStreamPredicate() {
    return instance -> {
        RSQLNodeTraveller<Boolean> visitor = new RSQLNodeTraveller<Boolean>() {

            public Boolean visit(LogicalNode node) {
                logger.trace("Parsing LogicalNode {}", node);
                Iterator<Node> iterator = node.iterator();
                if (node instanceof AndNode) {
                    boolean result = true;
                    while (iterator.hasNext()) {
                        Node next = iterator.next();
                        result &= visit(next);
                    }/*from w w w  . j a  va 2  s . co  m*/
                    return result;
                } else if (node instanceof OrNode) {
                    boolean result = false;
                    while (iterator.hasNext()) {
                        Node next = iterator.next();
                        result |= visit(next);
                    }
                    return result;
                } else {
                    throw new UnsupportedOperationException("Logical operation not supported");
                }
            }

            public Boolean visit(ComparisonNode node) {
                logger.trace("Parsing ComparisonNode {}", node);

                String fieldName = node.getSelector();
                String argument = node.getArguments().get(0);

                try {
                    String propertyValue = BeanUtils.getProperty(instance, fieldName);

                    if (node.getOperator().equals(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(LIKE)) {
                        argument = argument.replaceAll(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);
                }
            }
        };

        return rootNode.accept(visitor);
    };
}

From source file:xml.sk.Parser.java

/**
 * Parses AgeSk.xml.//from w ww  . jav  a  2  s. c o  m
 *
 * @param manager age manager to store data
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 */
public void parseAgeSk(AgeManagerImpl manager) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, ParseException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("src/main/java/xml/sk/AgeSk.xml");

    NodeList educationList = doc.getElementsByTagName("PRAC_strMzdyVek");
    for (int i = 0; i < educationList.getLength(); i++) {
        Element educationNode = (Element) educationList.item(i);

        if (!"EUR".equals(educationNode.getElementsByTagName("MJ").item(0).getTextContent()))
            continue;

        String ageStr = educationNode.getElementsByTagName("UKAZ2").item(0).getTextContent();
        Scanner in = new Scanner(ageStr).useDelimiter("[^0-9]+");
        Integer age1 = in.nextInt();
        Integer age2 = null;
        if (in.hasNext())
            age2 = in.nextInt();

        String sex = educationNode.getElementsByTagName("UKAZ1").item(0).getTextContent();
        String[] splited = sex.split(" ");
        sex = splited[splited.length - 1];

        NodeList years = educationNode.getChildNodes();

        for (int j = 0; j < years.getLength(); j++) {
            if (years.item(j).getNodeType() == Node.TEXT_NODE) {
                continue;
            }
            Element yearNode = (Element) years.item(j);
            if ("MJ".equals(yearNode.getNodeName()) || "UKAZ".equals(yearNode.getNodeName().substring(0, 4)))
                continue;

            String year = yearNode.getNodeName().substring(1);
            if (".".equals(yearNode.getTextContent()) || "".equals(yearNode.getTextContent())) {
                continue;
            }
            String salaryStr = yearNode.getTextContent().replaceAll(" ", "");
            NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
            Number number = format.parse(salaryStr);
            double salaryDouble = number.doubleValue();

            Age age = new Age();

            if (age2 == null) {
                if (age1 == 19) {
                    age1 = 0;
                    age2 = 19;
                }
                if (age1 == 60)
                    age2 = 99;
            }
            age.setAgeFrom(age1);
            age.setAgeTo(age2);
            age.setCountry("sk");
            age.setYear(year);
            age.setAverageSalary(salaryDouble);
            if (!"spolu".equals(sex))
                age.setSex(sex);

            manager.createAge(age);
        }
    }
}

From source file:com.skubit.satoshidice.placebet.PlaceBetFragment.java

private void updatePayoutField() {
    String text = mPayoutEdit.getText().toString();
    String payoutStr = text.isEmpty() ? "64290" : text.toString();

    NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
    Number number;/*w  w  w  .  jav  a 2s. co  m*/
    try {
        number = format.parse(payoutStr);
    } catch (ParseException e) {
        e.printStackTrace();
        return;
    }

    BetParameters bp = BetParameters.calculateWithPayoutMultiple(number.doubleValue());
    mSeekbar.setProgress(bp.getNumberToRollUnder());
    setTextFields(bp);
}

From source file:xml.sk.Parser.java

/**
 * Parses ClassificationSk.xml./*from w  w  w  .ja  va 2  s  .  com*/
 *
 * @param manager classification manager to store data
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 */
public void parseClassificationSk(ClassificationManagerImpl manager)
        throws ParserConfigurationException, SAXException, IOException, ParseException {
    Map<String, String> nameMap = new HashMap<>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    // file with statistics 2012 - 2013
    Document doc = builder.parse("src/main/java/xml/sk/Classification1Sk.xml");

    NodeList classificationList = doc.getElementsByTagName("PRAC_strMzdyZamIsco");
    for (int i = 0; i < classificationList.getLength(); i++) {
        Element classificationNode = (Element) classificationList.item(i);

        String name = classificationNode.getElementsByTagName("UKAZ2").item(0).getTextContent();
        String[] splited = name.split(" ", 2);
        if (!nameMap.containsKey(splited[0]))
            nameMap.put(splited[0], splited[1]);

        NodeList years = classificationNode.getChildNodes();

        for (int j = 0; j < years.getLength(); j++) {
            if (years.item(j).getNodeType() == Node.TEXT_NODE) {
                continue;
            }
            Element yearNode = (Element) years.item(j);
            if ("MJ".equals(yearNode.getNodeName()) || "UKAZ".equals(yearNode.getNodeName().substring(0, 4)))
                continue;

            String year = yearNode.getNodeName().substring(1);
            if (".".equals(yearNode.getTextContent()) || "".equals(yearNode.getTextContent())) {
                continue;
            }
            String salaryStr = yearNode.getTextContent().replaceAll(" ", "");
            NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
            Number number = format.parse(salaryStr);
            double salaryDouble = number.doubleValue();

            Classification classification = new Classification();
            classification.setCode(splited[0]);
            classification.setName(splited[1]);
            classification.setCountry("sk");
            classification.setYear(year);
            classification.setAverageSalary(salaryDouble);

            manager.createClassification(classification);
        }
    }

    //file with statistics 1998, 2009 - 2011
    doc = builder.parse("src/main/java/xml/sk/Classification2Sk.xml");
    classificationList = doc.getElementsByTagName("PRAC_strMzdyZam");
    for (int i = 0; i < classificationList.getLength(); i++) {
        Element classificationNode = (Element) classificationList.item(i);

        if (!"EUR".equals(classificationNode.getElementsByTagName("MJ").item(0).getTextContent()))
            continue;

        String name = classificationNode.getElementsByTagName("UKAZ2").item(0).getTextContent();
        String[] splited = name.split(" ", 2);

        NodeList years = classificationNode.getChildNodes();

        for (int j = 0; j < years.getLength(); j++) {
            if (years.item(j).getNodeType() == Node.TEXT_NODE) {
                continue;
            }
            Element yearNode = (Element) years.item(j);
            if ("MJ".equals(yearNode.getNodeName()) || "UKAZ".equals(yearNode.getNodeName().substring(0, 4)))
                continue;

            String year = yearNode.getNodeName().substring(1);
            if (".".equals(yearNode.getTextContent()) || "".equals(yearNode.getTextContent())) {
                continue;
            }
            String salaryStr = yearNode.getTextContent().replaceAll(" ", "");
            NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
            Number number = format.parse(salaryStr);
            double salaryDouble = number.doubleValue();

            Classification classification = new Classification();
            classification.setCode(splited[0]);
            classification.setName(nameMap.get(splited[0]));
            classification.setCountry("sk");
            classification.setYear(year);
            classification.setAverageSalary(salaryDouble);

            manager.createClassification(classification);
        }
    }
}

From source file:org.apache.nifi.processors.kite.TestConvertAvroSchema.java

private Record convertBasic(Record inputRecord, Locale locale) {
    Record result = new Record(OUTPUT_SCHEMA);
    result.put("id", Long.parseLong(inputRecord.get("id").toString()));
    result.put("color", inputRecord.get("primaryColor").toString());
    if (inputRecord.get("price") == null) {
        result.put("price", null);
    } else {//ww  w.j a va 2s .co m
        final NumberFormat format = NumberFormat.getInstance(locale);
        double price;
        try {
            price = format.parse(inputRecord.get("price").toString()).doubleValue();
        } catch (ParseException e) {
            // Shouldn't happen
            throw new RuntimeException(e);
        }
        result.put("price", price);
    }
    return result;
}

From source file:web.UpdatebusinessController.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/*ww  w .j a  v  a  2  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 (!WebUtil.isProductPremiumSubscription()) {
        return handleError("Cannot access this feature in non premimu subscription version.");
    }

    if (!DiaryAdmin.isDiaryAdmin(login)) {
        return handleError("User is not diaryAdmin, cannot updateBusiness" + login);
    }

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

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

    String bsearch = request.getParameter(DbConstants.BSEARCH);
    if (!RegexStrUtil.isNull(bsearch)) {
        if (!bsearch.equals(DbConstants.BSEARCH_ALLOW) && (!bsearch.equals(DbConstants.BSEARCH_DISALLOW))) {
            return handleError("bsearch is invalid in UpdatebusinessController");
        }
    } else {
        return handleError("bsearch is null in UpdatebusinessController");
    }

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

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

    String pname = request.getParameter(DbConstants.PNAME);
    if (!RegexStrUtil.isNull(pname)) {
        if (pname.length() > GlobalConst.pNameSize) {
            pname = pname.substring(0, GlobalConst.pNameSize);
        }
        pname = RegexStrUtil.goodNameStr(pname);
    }

    String bname = request.getParameter(DbConstants.BNAME);
    if (!RegexStrUtil.isNull(bname)) {
        if (bname.length() > GlobalConst.bNameSize) {
            bname = bname.substring(0, GlobalConst.bNameSize);
        }
        bname = RegexStrUtil.goodText(bname);
    }

    // check cWebsite
    String bwebsite = request.getParameter(DbConstants.BWEBSITE);
    if (!RegexStrUtil.isNull(bwebsite)) {
        if (bwebsite.length() > GlobalConst.cWebsiteSize)
            bwebsite = bwebsite.substring(0, GlobalConst.cWebsiteSize);
        bwebsite = RegexStrUtil.goodText(bwebsite);
    }

    String bstreet = request.getParameter(DbConstants.BSTREET);
    if (!RegexStrUtil.isNull(bstreet)) {
        if (bstreet.length() > GlobalConst.streetSize)
            bstreet = bstreet.substring(0, GlobalConst.streetSize);
        bstreet = RegexStrUtil.goodText(bstreet);
    }

    String bcity = request.getParameter(DbConstants.BCITY);
    if (!RegexStrUtil.isNull(bcity)) {
        if (bcity.length() > GlobalConst.bCitySize) {
            bcity = bcity.substring(0, GlobalConst.bCitySize);
        }
        bcity = RegexStrUtil.goodText(bcity);
    }

    String bstate = request.getParameter(DbConstants.BSTATE);
    if (!RegexStrUtil.isNull(bstate)) {
        if (bstate.length() > GlobalConst.bStateSize) {
            bstate = bstate.substring(0, GlobalConst.bStateSize);
        }
        bstate = RegexStrUtil.goodText(bstate);
    }
    String bzipcode = request.getParameter(DbConstants.BZIPCODE);
    if (!RegexStrUtil.isNull(bzipcode)) {
        if (bzipcode.length() > GlobalConst.bZipcodeSize) {
            bzipcode = bzipcode.substring(0, GlobalConst.bZipcodeSize);
        }
        bzipcode = RegexStrUtil.goodText(bzipcode);
    }

    String bcountry = request.getParameter(DbConstants.BCOUNTRY);
    if (!RegexStrUtil.isNull(bcountry)) {
        if (bcountry.length() > GlobalConst.bCountrySize) {
            bcountry = bcountry.substring(0, GlobalConst.bCountrySize);
        }
        bcountry = RegexStrUtil.goodText(bcountry);
    }

    // check bPhoneSize
    String pphone = request.getParameter(DbConstants.PPHONE);
    if (!RegexStrUtil.isNull(pphone)) {
        if (pphone.length() > GlobalConst.bPhoneSize) {
            pphone = pphone.substring(0, GlobalConst.bPhoneSize);
        }
        pphone = RegexStrUtil.goodText(pphone);
    }

    String bein = request.getParameter(DbConstants.BEIN);
    if (!RegexStrUtil.isNull(bein)) {
        if (bein.length() > GlobalConst.bEinSize) {
            bein = bein.substring(0, GlobalConst.bEinSize);
        }
        bein = RegexStrUtil.goodText(bein);
    }

    List bizList = null;
    try {
        BusinessDao businessDao = (BusinessDao) getDaoMapper().getDao(DbConstants.BUSINESS);
        if (businessDao == null) {
            return handleError("businessDao is null, in UpdatebusinessController." + login);
        }
        businessDao.updateBusiness(login, bid, bname, pname, pphone, bwebsite, bein, bstreet, bcity, bstate,
                bcountry, bzipcode, bsearch);
        bizList = businessDao.getBizList(login, DbConstants.READ_FROM_MASTER);
    } catch (BaseDaoException e) {
        return handleError("Exception in updateBusiness() login " + login, e);
    }

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

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

    String viewName = DbConstants.LIST_BUSINESS;
    Map myModel = new HashMap();
    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.BIZ_LIST, bizList);
    return new ModelAndView(viewName, "model", myModel);
}

From source file:org.talend.dq.indicators.preview.table.ChartDataEntity.java

/**
 * check the inString is a validate value.
 * /*from  ww  w. j a  va 2 s  .  co  m*/
 * @param inString
 * @return
 */
public boolean isOutOfValue(String inString) {

    if (inString.equals(PluginConstant.NA_STRING)) { // $NON-NLS-1$
        return true;
    }

    boolean isOutOfValue = false;

    // the default value check
    isPercent = inString.indexOf('%') > 0; // $NON-NLS-1$
    if (isPercent) {
        NumberFormat nFromat = NumberFormat.getPercentInstance();
        try {
            Number number = nFromat.parse(inString);

            if (number instanceof Double) {
                Double doubleString = (Double) number;
                if (doubleString < 0 || doubleString > 1) {
                    isOutOfValue = true;
                }
            } else if (number instanceof Long) {
                Long longString = (Long) number;
                if (longString < 0 || longString > 1) {
                    isOutOfValue = true;
                }
            }
        } catch (ParseException e) {
            isOutOfValue = false;
        }
    } else {
        Double douString = Double.valueOf(inString);
        if (douString < 0) {
            isOutOfValue = true;
        }
    }
    return isOutOfValue;
}

From source file:web.DirectorydeleteallController.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//ww w . j a  v  a 2  s.  com
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // ***************************************************************************
    // This will initialize common data in the abstract class and the return result is of no value.
    // The abstract class initializes protected variables, login, directory, logininfo.
    // Which can be accessed in all controllers if they want to.
    // ***************************************************************************
    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }

    if (!WebUtil.isLicenseProfessional(login)) {
        return handleError("Cannot access manage (delete) directory feature in deluxe version.");
    }

    // ***************************************************************************
    // 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 redirectory to extend SessionObject.
    // ***************************************************************************
    outOfSession(request, response);

    if (RegexStrUtil.isNull(login)) {
        return handleUserpageError("Login is null in DirectorydeleteallController.");
    }

    String directoryId = request.getParameter(DbConstants.DIRECTORY_ID);
    if (RegexStrUtil.isNull(directoryId)) {
        return handleError("request, directoryId is null, for directorydeleteController " + login);
    }
    if (directoryId.length() > GlobalConst.directoryidSize) {
        return handleError("directoryId.length() > WebConstants.directoryIdSize DirectoryController ");
    }
    directoryId = RegexStrUtil.goodNameStr(directoryId);

    String deleteAll = request.getParameter("Delete All");
    String delete = request.getParameter(DbConstants.DELETE);
    if (RegexStrUtil.isNull(delete) && RegexStrUtil.isNull(deleteAll)) {
        return handleError("Delete && deleteAll are null, DirectorydeleteallController() for login " + login);
    }

    String size = request.getParameter(DbConstants.SIZE);
    if (RegexStrUtil.isNull(size)) {
        return handleError("collabrum list size is null, DirectorydeleteallController() for login " + login);
    }

    String urlCnt = request.getParameter(DbConstants.URL_CNT);
    if (RegexStrUtil.isNull(urlCnt)) {
        return handleError("url list size is null, DirectorydeleteallController() for login " + login);
    }

    int colListSize = new Integer(size).intValue();
    String val = "";
    ArrayList collabrumIdList = new ArrayList();
    for (int i = 0; i < colListSize; i++) {
        val = new Integer(i).toString();
        if (!RegexStrUtil.isNull(request.getParameter(val))) {
            if ((delete != null) && delete.equals(DbConstants.DELETE)) {
                if (request.getParameter(val).equalsIgnoreCase("on")) {
                    StringBuffer myString = new StringBuffer("col");
                    myString.append(val);
                    collabrumIdList.add(RegexStrUtil.goodNameStr(request.getParameter(myString.toString())));
                }
            } else {
                StringBuffer myString = new StringBuffer("col");
                myString.append(val);
                collabrumIdList.add(RegexStrUtil.goodNameStr(request.getParameter(myString.toString())));
            }
        }
    }

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

    int webListSize = new Integer(urlCnt).intValue();
    ArrayList webList = new ArrayList();
    for (int i = 0; i < webListSize; i++) {
        val = new Integer(i).toString();
        if (!RegexStrUtil.isNull(request.getParameter(val))) {
            if ((delete != null) && delete.equals(DbConstants.DELETE)) {
                if (request.getParameter(val).equalsIgnoreCase("on")) {
                    StringBuffer myString = new StringBuffer(DbConstants.URL);
                    myString.append(val);
                    webList.add(RegexStrUtil.goodNameStr(request.getParameter(myString.toString())));
                }
            } else {
                StringBuffer myString = new StringBuffer(DbConstants.URL);
                myString.append(val);
                webList.add(RegexStrUtil.goodNameStr(request.getParameter(myString.toString())));
            }
        }
    }

    DirectoryDao directoryDao = (DirectoryDao) daoMapper.getDao(DbConstants.DIRECTORY);
    if (directoryDao == null) {
        return handleError("DirectoryDao is null in DirectorydeleteallController directory, " + login);
    }

    String loginId = null;
    if (loginInfo != null) {
        loginId = loginInfo.getValue(DbConstants.LOGIN_ID);
    }

    try {
        if (!directoryDao.isUserAuthor(directoryId, loginId, login)) {
            return handleError(
                    "User is not an author, cannot delete directory, DirectorydeleteallController directory, "
                            + login);
        }
    } catch (BaseDaoException e) {
        return handleError("isUserAuthor() is null, in DirectorydeleteallController directory, " + login, e);
    }

    CollabrumDao collabrumDao = (CollabrumDao) daoMapper.getDao(DbConstants.COLLABRUM);
    if (collabrumDao == null) {
        return handleError("CollabrumDao null, DirectorydeleteallController, login " + login);
    }
    try {
        collabrumDao.deleteDirCollabrums(directoryId, collabrumIdList, loginId, login);
    } catch (BaseDaoException e) {
        return handleError("Exception occured in DirectorydeleteallController() for member " + login, e);
    }

    DirWebsiteDao websiteDirDao = (DirWebsiteDao) daoMapper.getDao(DbConstants.DIR_WEBSITE);
    if (websiteDirDao == null) {
        return handleError("DirWebsiteDao is null in DirwebsitedeleteController directory, " + login);
    }
    try {
        websiteDirDao.deleteAllWebsites(webList, loginId, login, directoryId);
    } catch (BaseDaoException e) {
        return handleError(
                "Exception occured in DirectorydeleteallController() for login " + login + "login = " + login,
                e);
    }

    List parentResult = null;
    try {
        parentResult = directoryDao.deleteDirectory(directoryId, loginId, login);
    } catch (BaseDaoException e) {
        return handleError(
                "Exception occured in deleteDirectory() for member " + login + " directoryId = " + directoryId,
                e);
    }

    Directory dir = null;
    if (parentResult == null) {
        return handleError("Exception occured in retrieving the parent in deleteDirectory, login " + login
                + " directoryId = " + directoryId);
    } else {
        if (parentResult.size() > 0) {
            String parentid = ((Directory) parentResult.get(0)).getValue(DbConstants.PARENT_ID);
            if (RegexStrUtil.isNull(parentid)) {
                return handleError(
                        "parentid is null, deleteDirectory, login " + login + " directoryId = " + directoryId);
            }
            try {
                dir = directoryDao.viewDirectory(parentid, loginId, login, DbConstants.READ_FROM_MASTER,
                        DbConstants.BLOB_READ_FROM_SLAVE, DbConstants.READ_FROM_SLAVE);
            } catch (BaseDaoException e) {
                return handleError("Exception occured in directoryDeleteController() for member " + login
                        + " ErrorMsg=" + e.getMessage(), e);
            }
        }
    }

    String viewName = DbConstants.VIEW_DIRECTORY;
    Map myModel = new HashMap();
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.DIRECTORY, dir);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.SHARE_INFO, shareInfo);
    myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);
}

From source file:org.gnucash.android.test.ui.TransactionsActivityTest.java

private void validateEditTransactionFields(Transaction transaction) {

    String name = mSolo.getEditText(0).getText().toString();
    assertEquals(transaction.getName(), name);

    String amountString = mSolo.getEditText(1).getText().toString();
    NumberFormat formatter = NumberFormat.getInstance();
    try {/*from ww w. ja v a2 s .  c o m*/
        amountString = formatter.parse(amountString).toString();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Money amount = new Money(amountString, Currency.getInstance(Locale.getDefault()).getCurrencyCode());
    assertEquals(transaction.getAmount(), amount);

    String description = mSolo.getEditText(2).getText().toString();
    assertEquals(transaction.getDescription(), description);

    String expectedValue = TransactionFormFragment.DATE_FORMATTER.format(transaction.getTimeMillis());
    TextView dateView = (TextView) mSolo.getView(R.id.input_date);
    String actualValue = dateView.getText().toString(); //mSolo.getText(6).getText().toString();
    assertEquals(expectedValue, actualValue);

    expectedValue = TransactionFormFragment.TIME_FORMATTER.format(transaction.getTimeMillis());
    TextView timeView = (TextView) mSolo.getView(R.id.input_time);
    actualValue = timeView.getText().toString();// mSolo.getText(7).getText().toString();
    assertEquals(expectedValue, actualValue);
}