Example usage for java.text ParsePosition getIndex

List of usage examples for java.text ParsePosition getIndex

Introduction

In this page you can find the example usage for java.text ParsePosition getIndex.

Prototype

public int getIndex() 

Source Link

Document

Retrieve the current parse position.

Usage

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler.java

public Object getTheValue(Field field, String[] paramValue, String desiredClassName) throws Exception {
    if (paramValue == null || paramValue.length == 0)
        return null;

    if (desiredClassName.equals("byte")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Byte((byte) 0);
        else//from   w  w w .  ja va2  s . co m
            return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals("short")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Short((short) 0);
        else
            return Short.decode(paramValue[0]);
    } else if (desiredClassName.equals("int")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Integer(0);
        else
            return Integer.decode(paramValue[0]);
    } else if (desiredClassName.equals("long")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Long(0L);
        else
            return Long.decode(paramValue[0]);
    } else if (desiredClassName.equals(Byte.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals(Short.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Short.decode(paramValue[0]);

    } else if (desiredClassName.equals(Integer.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Integer.decode(paramValue[0]);

    } else if (desiredClassName.equals(Long.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Long.decode(paramValue[0]);

    } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")
            || desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")
            || desiredClassName.equals(BigDecimal.class.getName())) {

        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();

        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale(LocaleManager.currentLang()));
        if (desiredClassName.equals(BigDecimal.class.getName()))
            df.setParseBigDecimal(true);
        String pattern = getFieldPattern(field);
        if (pattern != null && !"".equals(pattern)) {
            df.applyPattern(pattern);
        } else {
            df.applyPattern("###.##");
        }
        ParsePosition pp = new ParsePosition(0);
        Number num = df.parse(paramValue[0], pp);
        if (paramValue[0].length() != pp.getIndex() || num == null) {
            log.debug("Error on parsing value");
            throw new ParseException("Error parsing value", pp.getIndex());
        }

        if (desiredClassName.equals(BigDecimal.class.getName())) {
            return num;
        } else if (desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")) {
            return new Float(num.floatValue());
        } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")) {
            return new Double(num.doubleValue());
        }
    } else if (desiredClassName.equals(BigInteger.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return new BigInteger(paramValue[0]);

    }
    throw new IllegalArgumentException("Invalid class for NumericFieldHandler: " + desiredClassName);
}

From source file:org.webguitoolkit.ui.controls.util.validation.PositiveNumberValidator.java

public void validate(String object) throws ValidationException {
    try {//w  ww .j  ava 2s. c  om
        // no mandatory field: empty means value zero.
        if (StringUtils.isEmpty(object)) {
            return;
        } else {
            DecimalFormat formatter;
            formatter = new DecimalFormat(pattern, new DecimalFormatSymbols(TextService.getLocale()));

            ParsePosition pos = new ParsePosition(0);
            Number num = formatter.parse(object, pos);

            if (num == null)
                throw new ValidationException(TextService.getString(
                        "converter.PositiveNumberValidator.message.conversion@Cannot convert into number."));
            if (pos.getIndex() < object.length()) {
                throw new ValidationException(TextService.getString(
                        "converter.PositiveNumberValidator.message.conversion@Cannot convert into number."));
            }

            Double f = new Double(num.doubleValue());
            if (f.doubleValue() < 0) {
                throw new ValidationException(TextService.getString(
                        "validator.PositiveNumberValidator.message@The entered number must be positive."));
            }
        }
    } catch (NumberFormatException e) {
        throw new ValidationException(TextService
                .getString("validator.PositiveNumberValidator.message.conversion@Cannot convert into number."));
    }
}

From source file:ISO8601DateFormat.java

/**
 * @see java.text.DateFormat#parse(String, ParsePosition)
 *//*from   w  w w. j a  va2  s.  c  o  m*/
public Date parse(String text, ParsePosition pos) {

    int i = pos.getIndex();

    try {
        int year = Integer.valueOf(text.substring(i, i + 4)).intValue();
        i += 4;

        if (text.charAt(i) != '-') {
            throw new NumberFormatException();
        }
        i++;

        int month = Integer.valueOf(text.substring(i, i + 2)).intValue() - 1;
        i += 2;

        if (text.charAt(i) != '-') {
            throw new NumberFormatException();
        }
        i++;

        int day = Integer.valueOf(text.substring(i, i + 2)).intValue();
        i += 2;

        calendar.set(year, month, day);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0); // no parts of a second

        i = parseTZ(i, text);

    } catch (NumberFormatException ex) {
        pos.setErrorIndex(i);
        return null;
    } catch (IndexOutOfBoundsException ex) {
        pos.setErrorIndex(i);
        return null;
    } finally {
        pos.setIndex(i);
    }

    return calendar.getTime();
}

From source file:org.eclipse.riena.ui.ridgets.validation.AbstractValidDate.java

private boolean isDate(final String value, final String pattern, final boolean strict) {
    if (value == null || pattern == null || pattern.length() <= 0) {

        return false;
    }/*from w w  w  .j  a  v  a 2s.c o m*/
    if (strict && value.length() != pattern.length()) {
        return false;
    }
    final SimpleDateFormat formatter = new SimpleDateFormat(pattern);
    formatter.setLenient(false);

    final ParsePosition pos = new ParsePosition(0);
    formatter.parse(value, pos);
    if (pos.getErrorIndex() != -1) {
        return false;
    }
    if (strict) {
        if (pos.getIndex() < value.length()) {
            return false;
        }
    }
    return true;
}

From source file:org.webguitoolkit.ui.controls.util.conversion.NumberAllConverter.java

/**
 * check if the input string is a legal number. It does NOT return a Numberobject.
 * Itseem that this is a bug in BeanUtilBean class (maybe we shopuld update)
 * Try: BeanUtilBean.setProperty( Pump, "hours", new Float(24))
 * with Pump.setHours(int value) taking an int as input.
 * You will see, that it will store '0', because it converts the float into string,
 * then back to int, and get an parseexception.
 * /*  ww  w  .ja va2  s  .c o  m*/
 * @return the input string
 * @exception ConversionException if the input if not a legal number
 */
public Object parse(String textRep) throws ConversionException {
    // no mandatory field, empty means value zero.
    if (StringUtils.isEmpty(textRep))
        return new Float(0f);
    formatter = new DecimalFormat(pattern, new DecimalFormatSymbols(TextService.getLocale()));
    ParsePosition pos = new ParsePosition(0);
    lastNumber = formatter.parse(textRep, pos);
    // to avoid null pointer -return float with 0
    if (lastNumber == null)
        throw new ConversionException(
                TextService.getString("converter.NumberConverter.message@Cannot convert into number."));
    if (pos.getIndex() < textRep.length()) {
        throw new ConversionException(
                TextService.getString("converter.NumberConverter.message@Cannot convert into number."));
    }
    // must decode into string using default locale of system
    // because it is going to be translated back!
    // why is this fucking BeanUtil converter stuff so complicated and error-prone?
    return lastNumber.toString();
}

From source file:org.eclipse.dirigible.runtime.registry.RegistryServlet.java

private Date parseDate(String modifiedSinceHeader) {
    final Calendar calendar = Calendar.getInstance();
    if ((modifiedSinceHeader.length() > 1) && modifiedSinceHeader.startsWith(SINGLE_QUOTE)
            && modifiedSinceHeader.endsWith(SINGLE_QUOTE)) {
        modifiedSinceHeader = modifiedSinceHeader.substring(1, modifiedSinceHeader.length() - 1);
    }//from   w w w  .j  a va2s  .  c  o m
    for (String format : DATE_FORMATS) {
        SimpleDateFormat dateParser = new SimpleDateFormat(format);
        dateParser.set2DigitYearStart(calendar.getTime());
        final ParsePosition pos = new ParsePosition(0);
        final Date result = dateParser.parse(modifiedSinceHeader, pos);
        if (pos.getIndex() != 0) {
            return result;
        }
    }
    return null;
}

From source file:de.betterform.xml.xforms.ui.AbstractFormControl.java

private BigDecimal strictParse(String value, Locale locale) throws ParseException {
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(locale);
    format.setParseBigDecimal(true);/*from  w  w w.  ja  v  a 2  s .  c o  m*/
    value = value.trim();
    ParsePosition pos = new ParsePosition(0);
    BigDecimal number = (BigDecimal) format.parse(value, pos);
    boolean okay = pos.getIndex() == value.length() && pos.getErrorIndex() == -1;
    if (!okay)
        throw new ParseException("Could not parse '" + value + "' as a number", pos.getErrorIndex());
    return number;
}

From source file:org.eredlab.g4.ccl.net.ftp.parser.FTPTimestampParserImpl.java

/** 
 * Implements the one {@link  FTPTimestampParser#parseTimestamp(String)  method}
 * in the {@link  FTPTimestampParser  FTPTimestampParser} interface 
 * according to this algorithm://  w  w w . ja v a2s.c o  m
 * 
 * If the recentDateFormat member has been defined, try to parse the 
 * supplied string with that.  If that parse fails, or if the recentDateFormat
 * member has not been defined, attempt to parse with the defaultDateFormat
 * member.  If that fails, throw a ParseException. 
 * 
 * @see org.apache.commons.net.ftp.parser.FTPTimestampParser#parseTimestamp(java.lang.String)    
 */
/* (non-Javadoc)
 * 
 */
public Calendar parseTimestamp(String timestampStr) throws ParseException {
    Calendar now = Calendar.getInstance();
    now.setTimeZone(this.getServerTimeZone());

    Calendar working = Calendar.getInstance();
    working.setTimeZone(this.getServerTimeZone());
    ParsePosition pp = new ParsePosition(0);

    Date parsed = null;
    if (this.recentDateFormat != null) {
        parsed = recentDateFormat.parse(timestampStr, pp);
    }
    if (parsed != null && pp.getIndex() == timestampStr.length()) {
        working.setTime(parsed);
        working.set(Calendar.YEAR, now.get(Calendar.YEAR));
        if (working.after(now)) {
            working.add(Calendar.YEAR, -1);
        }
    } else {
        pp = new ParsePosition(0);
        parsed = defaultDateFormat.parse(timestampStr, pp);
        // note, length checks are mandatory for us since
        // SimpleDateFormat methods will succeed if less than
        // full string is matched.  They will also accept, 
        // despite "leniency" setting, a two-digit number as
        // a valid year (e.g. 22:04 will parse as 22 A.D.) 
        // so could mistakenly confuse an hour with a year, 
        // if we don't insist on full length parsing.
        if (parsed != null && pp.getIndex() == timestampStr.length()) {
            working.setTime(parsed);
        } else {
            throw new ParseException("Timestamp could not be parsed with older or recent DateFormat",
                    pp.getIndex());
        }
    }
    return working;
}

From source file:com.anrisoftware.sscontrol.hosts.utils.HostFormat.java

@Override
public Object parseObject(String source, ParsePosition pos) {
    source = source.trim();//from w w  w .  j a  v  a 2 s .c om
    TemplateResource template;
    template = templates.getResource(PARSE_TEMPLATE_NAME, locale);
    Pattern pattern = Pattern.compile(template.getText());
    Matcher matcher = pattern.matcher(source);
    if (!matcher.matches()) {
        pos.setErrorIndex(pos.getIndex());
        return null;
    }
    String address = matcher.group(1);
    String name = matcher.group(2);
    Host host = hostFactory.create(name, address);
    String[] aliases = split(matcher.group(3), ",");
    for (int i = 0; i < aliases.length; i++) {
        String alias = aliases[i].replaceAll("[\"']", "");
        host.addAlias(alias);
    }
    pos.setIndex(matcher.end());
    return host;
}

From source file:org.springframework.binding.convert.converters.FormattedStringToNumber.java

@SuppressWarnings("unchecked")
protected Object toObject(String string, Class<?> targetClass) throws Exception {
    ParsePosition parsePosition = new ParsePosition(0);
    NumberFormat format = numberFormatFactory.getNumberFormat();
    Number number = format.parse(string, parsePosition);
    if (number == null) {
        // no object could be parsed
        throw new InvalidFormatException(string, getPattern(format));
    }/*from   www  . j  ava2s . co m*/
    if (!lenient) {
        if (string.length() != parsePosition.getIndex()) {
            // indicates a part of the string that was not parsed; e.g. ".5" in 1234.5 when parsing an Integer
            throw new InvalidFormatException(string, getPattern(format));
        }
    }
    return convertToNumberClass(number, (Class<? extends Number>) targetClass);
}