Example usage for java.text ParsePosition setIndex

List of usage examples for java.text ParsePosition setIndex

Introduction

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

Prototype

public void setIndex(int index) 

Source Link

Document

Set the current parse position.

Usage

From source file:org.osaf.cosmo.eim.schema.text.TriageStatusFormat.java

public Object parseObject(String source, ParsePosition pos) {
    if (pos.getIndex() > 0)
        return null;

    int index = 0;

    String[] chunks = source.split(" ", 3);
    if (chunks.length != 3) {
        parseException = new ParseException("Incorrect number of chunks: " + chunks.length, 0);
        pos.setErrorIndex(index);/*  ww w  .j  a  v a2 s.co m*/
        return null;
    }

    TriageStatus ts = entityFactory.createTriageStatus();

    try {
        pos.setIndex(index);
        Integer code = new Integer(chunks[0]);
        // validate the code as being known
        TriageStatusUtil.label(code);
        ts.setCode(code);
        index += chunks[0].length() + 1;
    } catch (Exception e) {
        parseException = new ParseException(e.getMessage(), 0);
        pos.setErrorIndex(index);
        return null;
    }

    try {
        pos.setIndex(index);
        BigDecimal rank = new BigDecimal(chunks[1]);
        if (rank.scale() != 2)
            throw new NumberFormatException("Invalid rank value " + chunks[1]);
        ts.setRank(rank);
        index += chunks[1].length() + 1;
    } catch (NumberFormatException e) {
        parseException = new ParseException(e.getMessage(), 0);
        pos.setErrorIndex(index);
        return null;
    }

    if (chunks[2].equals(AUTOTRIAGE_ON))
        ts.setAutoTriage(Boolean.TRUE);
    else if (chunks[2].equals(AUTOTRIAGE_OFF))
        ts.setAutoTriage(Boolean.FALSE);
    else {
        parseException = new ParseException("Invalid autotriage value " + chunks[2], 0);
        pos.setErrorIndex(index);
        return null;
    }
    index += chunks[2].length();

    pos.setIndex(index);

    return ts;
}

From source file:org.alfresco.util.CachingDateFormat.java

/**
 * Parses and caches date strings.//from ww w. j  a  va2  s  . c  om
 * 
 * @see java.text.DateFormat#parse(java.lang.String,
 *      java.text.ParsePosition)
 */
public Date parse(String text, ParsePosition pos) {
    Date cached = cacheDates.get(text);
    if (cached == null) {
        Date date = super.parse(text, pos);
        if ((date != null) && (pos.getIndex() == text.length())) {
            cacheDates.put(text, date);
            Date clonedDate = (Date) date.clone();
            return clonedDate;
        } else {
            return date;
        }
    } else {
        pos.setIndex(text.length());
        Date clonedDate = (Date) cached.clone();
        return clonedDate;
    }
}

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

@Override
public Object parseObject(String source, ParsePosition pos) {
    source = source.trim();/* w ww .j a  v a  2s  .  co  m*/
    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.opendatakit.common.android.utilities.WebUtils.java

@SuppressLint("SimpleDateFormat")
private Date parseDateSubset(String value, String[] parsePatterns, Locale l, TimeZone tz) {
    // borrowed from apache.commons.lang.DateUtils...
    Date d = null;//from   w  ww  .  j  a  v  a2s  .  com
    SimpleDateFormat parser = null;
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {
        if (i == 0) {
            if (l == null) {
                parser = new SimpleDateFormat(parsePatterns[0]);
            } else {
                parser = new SimpleDateFormat(parsePatterns[0], l);
            }
        } else {
            parser.applyPattern(parsePatterns[i]);
        }
        parser.setTimeZone(tz); // enforce UTC for formats without timezones
        pos.setIndex(0);
        d = parser.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    return d;
}

From source file:Unsigned.java

/**
 * Parse a binary number into a Number object. If up to 8 bits are parsed,
 * returns a Byte. If more than 8 and up to 16 bits are parsed, return a
 * Short. If more than 16 and up to 32 bits are parsed, return an Integer.
 * If more than 32 and up to 64 bits are parsed, return a Long.
 * /*from w w w .j  av  a2  s  .  c o m*/
 * @param text
 *            a binary number
 * @param parsePosition
 *            position to start parsing from
 * @return return an integer form of Number object if parse is successful;
 *         <CODE>null</CODE> otherwise
 * 
 * @since 1.0
 */
public Number parse(String text, ParsePosition parsePosition) {
    boolean skipWhitespace = true;
    int startIndex, bits;

    // remove whitespace
    StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex());
    for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) {
        if (skipWhitespace && Character.isWhitespace(c)) {
            // skip whitespace
            continue;
        }
    }
    parsePosition.setIndex(iter.getIndex());

    startIndex = parsePosition.getIndex();
    Number result = (Number) parseObject(text, parsePosition);

    if (result == null) {
        return (result);
    }

    bits = parsePosition.getIndex() - startIndex;
    if (bits <= 8) {
        result = new Byte(result.byteValue());
    } else if (bits <= 16) {
        result = new Short(result.shortValue());
    } else if (bits <= 32) {
        result = new Integer(result.intValue());
    } else if (bits <= 64) {
        result = new Long(result.longValue());
    }
    return (result);
}

From source file:org.jboss.forge.roaster.model.impl.PropertyImpl.java

@Override
public PropertySource<O> setName(final String name) {
    if (StringUtils.isBlank(name)) {
        throw new IllegalStateException("Property name cannot be null/empty/blank");
    }// ww  w  .j  ava  2  s . c om

    if (hasField()) {
        getField().setName(name);
    }

    final String oldName = this.name;
    final boolean visitDocTags = true;

    final ASTVisitor renameVisitor = new ASTVisitor(visitDocTags) {
        @Override
        public boolean visit(SimpleName node) {
            if (Objects.equals(oldName, node.getIdentifier())) {
                node.setIdentifier(name);
            }
            return super.visit(node);
        }

        @Override
        public boolean visit(TextElement node) {
            final String text = node.getText();
            if (!text.contains(oldName)) {
                return super.visit(node);
            }
            final int matchLength = oldName.length();
            final int textLength = text.length();
            final StringBuilder buf = new StringBuilder(text.length());
            final ParsePosition pos = new ParsePosition(0);

            while (pos.getIndex() < textLength) {
                final int index = pos.getIndex();
                final char c = text.charAt(index);
                if (Character.isJavaIdentifierStart(c)) {
                    final int next = index + matchLength;

                    if (next <= textLength && Objects.equals(oldName, text.substring(index, next))) {
                        buf.append(name);
                        pos.setIndex(next);
                        continue;
                    }
                }
                buf.append(c);
                pos.setIndex(index + 1);
            }

            node.setText(buf.toString());
            return super.visit(node);
        }
    };

    if (isAccessible()) {
        final MethodSource<O> accessor = getAccessor();
        final String prefix = accessor.getReturnType().isType(boolean.class) ? "is" : "get";
        accessor.setName(methodName(prefix, name));
        ((MethodDeclaration) accessor.getInternal()).accept(renameVisitor);
    }

    if (isMutable()) {
        final MethodSource<O> mutator = getMutator();
        mutator.setName(methodName("set", name));
        ((MethodDeclaration) mutator.getInternal()).accept(renameVisitor);
    }

    this.name = name;

    return this;
}

From source file:HexFormat.java

/**
 * Parse a hex number into a Number object. Hexadecimal numbers may be
 * indicated with a leading character designation of '0x'. If up to 1 byte
 * is parsed, returns a Byte. If more than 1 and up to 2 bytes are parsed,
 * return a Short. If more than 2 and up to 4 bytes are parsed, return an
 * Integer. If more than 4 and up to 8 bytes are parsed, return a Long.
 * //w  w w. j a  v  a 2 s  . co m
 * @param text
 *            a hexadecimal number
 * @param parsePosition
 *            position to start parsing from
 * @return return an integer form of Number object if parse is successful;
 *         <CODE>null</CODE> otherwise
 * 
 * @since 1.0
 */
public Number parse(String text, ParsePosition parsePosition) {
    boolean skipWhitespace = true;
    int startIndex, nibbles;

    // remove whitespace
    StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex());
    for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) {
        if (skipWhitespace && Character.isWhitespace(c)) {
            // skip whitespace
            continue;
        }
        break;
    }

    // skip a leading hex designation of the characters '0x'
    if (text.regionMatches(iter.getIndex(), "0x", 0, 2)) {
        parsePosition.setIndex(iter.getIndex() + 2);
    } else {
        parsePosition.setIndex(iter.getIndex());
    }

    startIndex = parsePosition.getIndex();
    Number result = (Number) parseObject(text, parsePosition);

    if (result == null) {
        return (result);
    }

    nibbles = parsePosition.getIndex() - startIndex;
    if (nibbles <= 2) {
        result = new Byte(result.byteValue());
    } else if (nibbles <= 4) {
        result = new Short(result.shortValue());
    } else if (nibbles <= 8) {
        result = new Integer(result.intValue());
    } else if (nibbles <= 16) {
        result = new Long(result.longValue());
    }
    return (result);
}

From source file:com.s3d.webapps.util.time.DateUtils.java

/**
 * <p>Parses a string representing a date by trying a variety of different parsers.</p>
 * /*from   www  .  ja  v a  2  s .c o m*/
 * <p>The parse will try each parse pattern in turn.
 * A parse is only deemed successful if it parses the whole of the input string.
 * If no parse patterns match, a ParseException is thrown.</p>
 * 
 * @param str  the date to parse, not null
 * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
 * @param lenient Specify whether or not date/time parsing is to be lenient.
 * @return the parsed date
 * @throws IllegalArgumentException if the date string or pattern array is null
 * @throws ParseException if none of the date patterns were suitable
 * @see java.util.Calender#isLenient()
 */
private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient)
        throws ParseException {
    if (str == null || parsePatterns == null) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }

    SimpleDateFormat parser = new SimpleDateFormat();
    parser.setLenient(lenient);
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {

        String pattern = parsePatterns[i];

        // LANG-530 - need to make sure 'ZZ' output doesn't get passed to SimpleDateFormat
        if (parsePatterns[i].endsWith("ZZ")) {
            pattern = pattern.substring(0, pattern.length() - 1);
        }

        parser.applyPattern(pattern);
        pos.setIndex(0);

        String str2 = str;
        // LANG-530 - need to make sure 'ZZ' output doesn't hit SimpleDateFormat as it will ParseException
        if (parsePatterns[i].endsWith("ZZ")) {
            int signIdx = indexOfSignChars(str2, 0);
            while (signIdx >= 0) {
                str2 = reformatTimezone(str2, signIdx);
                signIdx = indexOfSignChars(str2, ++signIdx);
            }
        }

        Date date = parser.parse(str2, pos);
        if (date != null && pos.getIndex() == str2.length()) {
            return date;
        }
    }
    throw new ParseException("Unable to parse the date: " + str, -1);
}

From source file:com.application.utils.FastDateParser.java

@Override
public Date parse(final String source, final ParsePosition pos) {
    final int offset = pos.getIndex();
    final Matcher matcher = parsePattern.matcher(source.substring(offset));
    if (!matcher.lookingAt()) {
        return null;
    }//from w ww  . ja v a 2 s .  c  o m
    // timing tests indicate getting new instance is 19% faster than cloning
    final Calendar cal = Calendar.getInstance(timeZone, locale);
    cal.clear();

    for (int i = 0; i < strategies.length;) {
        final Strategy strategy = strategies[i++];
        strategy.setCalendar(this, cal, matcher.group(i));
    }
    pos.setIndex(offset + matcher.end());
    return cal.getTime();
}

From source file:org.sqlite.date.FastDateParser.java

/**
 * This implementation updates the ParsePosition if the parse succeeeds.
 * However, unlike the method {@link java.text.SimpleDateFormat#parse(String, ParsePosition)}
 * it is not able to set the error Index - i.e. {@link ParsePosition#getErrorIndex()} -  if the parse fails.
 * <p>/*  w ww.ja  va2 s .c  o m*/
 * To determine if the parse has succeeded, the caller must check if the current parse position
 * given by {@link ParsePosition#getIndex()} has been updated. If the input buffer has been fully
 * parsed, then the index will point to just after the end of the input buffer.
 *
 * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition)
 * {@inheritDoc}
 */
public Date parse(final String source, final ParsePosition pos) {
    final int offset = pos.getIndex();
    final Matcher matcher = parsePattern.matcher(source.substring(offset));
    if (!matcher.lookingAt()) {
        return null;
    }
    // timing tests indicate getting new instance is 19% faster than cloning
    final Calendar cal = Calendar.getInstance(timeZone, locale);
    cal.clear();

    for (int i = 0; i < strategies.length;) {
        final Strategy strategy = strategies[i++];
        strategy.setCalendar(this, cal, matcher.group(i));
    }
    pos.setIndex(offset + matcher.end());
    return cal.getTime();
}