Example usage for java.text ParseException ParseException

List of usage examples for java.text ParseException ParseException

Introduction

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

Prototype

public ParseException(String s, int errorOffset) 

Source Link

Document

Constructs a ParseException with the specified detail message and offset.

Usage

From source file:org.efaps.webdav4vfs.lock.LockManager.java

/**
 * Evaluate an 'If:' header condition.//  ww  w. j  a va2s . co  m
 * The condition may be a tagged list or an untagged list. Tagged lists define the resource, the condition
 * applies to in front of the condition (ex. 1, 2, 5, 6). Conditions may be inverted by using 'Not' at the
 * beginning of the condition (ex. 3, 4, 6). The list constitutes an OR expression while the list of
 * conditions within braces () constitutes an AND expression.
 * <p/>
 * Evaluate example 2:<br/>
 * <code>
 * URI(/resource1) { (
 * is-locked-with(urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2)
 * AND matches-etag(W/"A weak ETag") )
 * OR ( matches-etag("strong ETag") ) }
 * </code>
 * <p/>
 * Examples:
 * <ol>
 * <li> &lt;http://cid:8080/litmus/unmapped_url&gt; (&lt;opaquelocktoken:cd6798&gt;)</li>
 * <li> &lt;/resource1&gt; (&lt;urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2&gt; [W/"A weak ETag"]) (["strong ETag"])</li>
 * <li> (&lt;urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2&gt;) (Not &lt;DAV:no-lock&gt;)</li>
 * <li> (Not &lt;urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2&gt; &lt;urn:uuid:58f202ac-22cf-11d1-b12d-002035b29092&gt;)</li>
 * <li> &lt;/specs/rfc2518.doc&gt; (["4217"])</li>
 * <li> &lt;/specs/rfc2518.doc&gt; (Not ["4217"])</li>
 * </ol>
 *
 * @param contextObject the contextual resource (needed when the If: condition is not tagged)
 * @param ifCondition   the string of the condition as sent by the If: header
 * @return evaluation of the condition expression
 * @throws ParseException        if the condition does not meet the syntax requirements
 * @throws LockConflictException
 * @throws FileSystemException
 */
public EvaluationResult evaluateCondition(final FileObject contextObject, final String ifCondition)
        throws FileSystemException, LockConflictException, ParseException {
    List<Lock> locks = discoverLock(contextObject);
    final EvaluationResult evaluation = new EvaluationResult();

    if ((ifCondition == null) || ifCondition.isEmpty()) {
        if (locks != null) {
            throw new LockConflictException(locks);
        }
        evaluation.result = true;
        return evaluation;
    }

    final Matcher matcher = IF_PATTERN.matcher(ifCondition);
    FileObject resource = contextObject;
    while (matcher.find()) {
        String token = matcher.group();
        switch (token.charAt(0)) {
        case TOKEN_LOWER_THAN:
            String resourceUri = token.substring(1, token.length() - 1);
            try {
                resource = contextObject.getFileSystem().resolveFile(new URI(resourceUri).getPath());
                locks = discoverLock(resource);
            } catch (URISyntaxException e) {
                throw new ParseException(ifCondition, matcher.start());
            }
            break;
        case TOKEN_LEFT_BRACE:
            LOG.debug(String.format("URI(%s) {", resource));
            Matcher condMatcher = CONDITION_PATTERN.matcher(token.substring(1, token.length() - 1));
            boolean expressionResult = true;
            while (condMatcher.find()) {
                String condToken = condMatcher.group();
                boolean negate = false;
                if (condToken.matches("[Nn][Oo][Tt]")) {
                    negate = true;
                    condMatcher.find();
                    condToken = condMatcher.group();
                }
                switch (condToken.charAt(0)) {
                case TOKEN_LOWER_THAN:
                    String lockToken = condToken.substring(1, condToken.length() - 1);

                    boolean foundLock = false;
                    if (locks != null) {
                        for (Lock lock : locks) {
                            if (lockToken.equals(lock.getToken())) {
                                evaluation.locks.add(lock);
                                foundLock = true;
                                break;
                            }
                        }
                    }
                    final boolean foundLockResult = negate ? !foundLock : foundLock;
                    LOG.debug(String.format("  %sis-locked-with(%s) = %b", negate ? "NOT " : "", lockToken,
                            foundLockResult));
                    expressionResult = expressionResult && foundLockResult;
                    break;
                case TOKEN_LEFT_BRACKET:
                    String eTag = condToken.substring(1, condToken.length() - 1);
                    String resourceETag = Util.getETag(resource);
                    boolean resourceTagMatches = resourceETag.equals(eTag);
                    final boolean matchesEtagResult = negate ? !resourceTagMatches : resourceTagMatches;
                    LOG.debug(String.format("  %smatches-etag(%s) = %b", negate ? "NOT " : "", eTag,
                            matchesEtagResult));
                    expressionResult = expressionResult && matchesEtagResult;
                    break;
                default:
                    throw new ParseException(
                            String.format("syntax error in condition '%s' at %d", ifCondition,
                                    matcher.start() + condMatcher.start()),
                            matcher.start() + condMatcher.start());
                }
            }

            evaluation.result = evaluation.result || expressionResult;
            LOG.debug("} => " + evaluation.result);
            break;
        default:
            throw new ParseException(
                    String.format("syntax error in condition '%s' at %d", ifCondition, matcher.start()),
                    matcher.start());
        }
    }

    // regardless of the evaluation, if the object is locked but there is no valed lock token in the
    // conditions we must fail with a lock conflict too
    if (evaluation.result && (locks != null && !locks.isEmpty()) && evaluation.locks.isEmpty()) {
        throw new LockConflictException(locks);
    }
    return evaluation;
}

From source file:com.stratelia.webactiv.util.DateUtil.java

/**
 * Parse the date in a language specific standard format.
 * @param string The String to convert in Date
 * @param language The current user's language
 * @return A Date representation of the String in the language specific format.
 * @throws java.text.ParseException if the input String is null, empty, or just in an incorrect
 * format.//from   ww w  . ja va2s .c o  m
 */
public static Date stringToDate(String string, String language) throws ParseException {
    SimpleDateFormat format = getDateInputFormat(language);
    try {
        return format.parse(string);
    } catch (ParseException e) {
        throw e;
    } catch (Exception e) {
        throw new ParseException(e.getMessage(), 0);
    }
}

From source file:org.kuali.rice.core.impl.datetime.DateTimeServiceImpl.java

protected Date parseAgainstFormatArray(String dateString, String[] formats) throws ParseException {
    dateString = dateString.trim();//from w  ww .  jav  a  2 s .com
    StringBuffer exceptionMessage = new StringBuffer("Date or date/time string '").append(dateString)
            .append("' could not be converted using any of the accepted formats: ");
    for (String dateFormatString : formats) {
        try {
            return parse(dateString, dateFormatString);
        } catch (ParseException e) {
            exceptionMessage.append(dateFormatString).append(" (error offset=").append(e.getErrorOffset())
                    .append("),");
        }
    }
    throw new ParseException(exceptionMessage.toString().substring(0, exceptionMessage.length() - 1), 0);
}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParser.java

@Override
protected ActivityContext prepareItem(TNTInputStream<?, ?> stream, Object data) throws ParseException {
    Node xmlDoc;//from ww w . jav a  2s .  co m
    String xmlString = null;
    try {
        if (data instanceof Document) {
            xmlDoc = (Document) data;
        } else if (data instanceof Node) {
            xmlDoc = (Node) data;
        } else {
            xmlString = getNextActivityString(data);
            if (StringUtils.isEmpty(xmlString)) {
                return null;
            }
            synchronized (builder) {
                xmlDoc = builder.parse(IOUtils.toInputStream(xmlString, Utils.UTF8));
            }
        }
    } catch (Exception e) {
        ParseException pe = new ParseException(StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ActivityXmlParser.xmlDocument.parse.error"), 0);
        pe.initCause(e);

        throw pe;
    }

    if (xmlString == null) {
        try {
            xmlString = Utils.documentToString(xmlDoc);
        } catch (Exception exc) {
            logger().log(OpLevel.WARNING, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                    "ActivityXmlParser.xmlDocument.toString.error"), exc);
        }
    }

    ActivityContext cData = new ActivityContext(stream, data, xmlDoc);
    cData.setMessage(xmlString);

    return cData;
}

From source file:org.level28.android.moca.json.ScheduleDeserializer.java

/**
 * Pure Java reimplementation of {@link Time#parse3339(String)}.
 * <p>//  w  w  w  .  j ava 2s  .  c o m
 * Due to <a
 * href="http://code.google.com/p/android/issues/detail?id=16002">Issue
 * 16002</a>, {@code Time.parse3339()} leaks memory on short input. However,
 * the same leak happens <em>also</em> if the function is fed a formally
 * invalid RFC3339 timestamp.
 * <p>
 * The safest option is a full rewrite in pure Java, since JNI on Android is
 * a mess (we'd have to ship the same library for three different
 * architectures &mdash; not pretty...).
 * 
 * @param timeString
 *            a date/time specification formatted as an RFC3339 string
 * @return the same date/time specification in milliseconds since the Epoch
 * @throws ParseException
 *             if the string is formally invalid per RFC3339
 * @throws NullPointerException
 *             if the string is {@code null}
 * @throws IllegalArgumentException
 *             if the string is less than 10 characters long
 */
private static long parseTime(String timeString) throws ParseException {
    checkNotNull(timeString, "Time input should not be null");
    final int len = timeString.length();
    checkArgument(len >= 10, "Time input is too short; must be at least 10 characters");
    final char[] s = timeString.toCharArray();

    final Time t = new Time();
    int n;
    boolean inUtc = false;

    // Year
    n = getChar(s, 0, 1000);
    n += getChar(s, 1, 100);
    n += getChar(s, 2, 10);
    n += getChar(s, 3, 1);
    t.year = n;

    // '-'
    checkChar(s, 4, '-');

    // Month
    n = getChar(s, 5, 10);
    n += getChar(s, 6, 1);
    --n;
    t.month = n;

    // '-'
    checkChar(s, 7, '-');

    // Day
    n = getChar(s, 8, 10);
    n += getChar(s, 9, 1);
    t.monthDay = n;

    // Check if we have a time as well
    if (len >= 19) {
        // 'T'
        checkChar(s, 10, 'T');
        t.allDay = false;

        // Hour
        n = getChar(s, 11, 10);
        n += getChar(s, 12, 1);
        int hour = n;

        // ':'
        checkChar(s, 13, ':');

        // Minute
        n = getChar(s, 14, 10);
        n += getChar(s, 15, 1);
        int minute = n;

        // ':'
        checkChar(s, 16, ':');

        // Second
        n = getChar(s, 17, 10);
        n += getChar(s, 18, 1);
        t.second = n;

        // Skip subsecond component (if any)
        int tz_index = 19;
        if (tz_index < len && s[tz_index] == '.') {
            do {
                tz_index++;
            } while (tz_index < len && s[tz_index] >= '0' && s[tz_index] <= '9');
        }

        int offset = 0;
        if (len > tz_index) {
            final char c = s[tz_index];

            switch (c) {
            case 'Z':
                // UTC
                offset = 0;
                break;
            case '-':
                offset = 1;
                break;
            case '+':
                offset = -1;
                break;
            default:
                throw new ParseException("Unexpected character", tz_index);
            }
            inUtc = true;

            if (offset != 0) {
                // Hour
                n = getChar(s, tz_index + 1, 10);
                n += getChar(s, tz_index + 2, 1);
                n *= offset;
                hour += n;

                // ':'
                checkChar(s, tz_index + 3, ':');

                // Minute
                n = getChar(s, tz_index + 4, 10);
                n += getChar(s, tz_index + 5, 1);
                n *= offset;
                minute += n;
            }
        }
        t.hour = hour;
        t.minute = minute;

        if (offset != 0) {
            t.normalize(false);
        }
    } else {
        // We don't
        t.allDay = true;
        t.hour = 0;
        t.minute = 0;
        t.second = 0;
    }

    t.weekDay = 0;
    t.yearDay = 0;
    t.isDst = -1;
    t.gmtoff = 0;

    if (inUtc) {
        t.timezone = Time.TIMEZONE_UTC;
    }

    return t.toMillis(false);
}

From source file:org.deidentifier.arx.DataHandle.java

/**
 * Returns an int value from the specified cell.
 *
 * @param row The cell's row index//from   ww w .j ava2s .  c om
 * @param col The cell's column index
 * @return the int
 * @throws ParseException the parse exception
 */
public Integer getInt(int row, int col) throws ParseException {
    String value = getValue(row, col);
    DataType<?> type = getDataType(getAttributeName(col));
    if (type instanceof ARXInteger) {
        Long _long = ((ARXInteger) type).parse(value);
        return _long == null ? null : _long.intValue();
    } else {
        throw new ParseException("Invalid datatype: " + type.getClass().getSimpleName(), col);
    }
}

From source file:com.icloud.framework.http.heritrix.ArchiveUtils.java

/**
 * Parses an ARC-style date.  If passed String is < 12 characters in length,
 * we pad.  At a minimum, String should contain a year (>=4 characters).
 * Parse will also fail if day or month are incompletely specified.  Depends
 * on the above getXXDigitDate methods./*w ww.  j  av  a 2s .c o m*/
 * @param A 4-17 digit date in ARC style (<code>yyyy</code> to
 * <code>yyyyMMddHHmmssSSS</code>) formatting.  
 * @return A Date object representing the passed String. 
 * @throws ParseException
 */
public static Date getDate(String d) throws ParseException {
    Date date = null;
    if (d == null) {
        throw new IllegalArgumentException("Passed date is null");
    }
    switch (d.length()) {
    case 14:
        date = ArchiveUtils.parse14DigitDate(d);
        break;

    case 17:
        date = ArchiveUtils.parse17DigitDate(d);
        break;

    case 12:
        date = ArchiveUtils.parse12DigitDate(d);
        break;

    case 0:
    case 1:
    case 2:
    case 3:
        throw new ParseException("Date string must at least contain a" + "year: " + d, d.length());

    default:
        if (!(d.startsWith("19") || d.startsWith("20"))) {
            throw new ParseException("Unrecognized century: " + d, 0);
        }
        if (d.length() < 8 && (d.length() % 2) != 0) {
            throw new ParseException("Incomplete month/date: " + d, d.length());
        }
        StringBuilder sb = new StringBuilder(d);
        if (sb.length() < 8) {
            for (int i = sb.length(); i < 8; i += 2) {
                sb.append("01");
            }
        }
        if (sb.length() < 12) {
            for (int i = sb.length(); i < 12; i++) {
                sb.append("0");
            }
        }
        date = ArchiveUtils.parse12DigitDate(sb.toString());
    }

    return date;
}

From source file:org.azkfw.datasource.xml.XmlDatasourceFactory.java

private static XmlRecord readData(final int aRowNum, final XmlRecordEntity aRecord,
        final List<XmlField> aFields) throws ParseException {
    Map<String, Object> data = new HashMap<String, Object>();
    for (int i = 0; i < aFields.size(); i++) {
        XmlField field = aFields.get(i);
        XmlRecordDataEntity d = aRecord.data.get(i);

        String value = d.value;// ww w  .  j av  a2s .c om

        if ("(NULL)".equals(value)) {
            data.put(field.name, null);
        } else {
            if (FieldType.String == field.type) {
                String obj = value;
                data.put(field.name, obj);
            } else if (FieldType.Boolean == field.type) {
                Boolean obj = Boolean.parseBoolean(value);
                data.put(field.name, obj);
            } else if (FieldType.Integer == field.type) {
                Double obj = Double.parseDouble(value);
                data.put(field.name, Integer.valueOf(obj.intValue()));
            } else if (FieldType.Long == field.type) {
                Double obj = Double.parseDouble(value);
                data.put(field.name, Long.valueOf(obj.longValue()));
            } else if (FieldType.Float == field.type) {
                Float obj = Float.parseFloat(value);
                data.put(field.name, obj);
            } else if (FieldType.Double == field.type) {
                Double obj = Double.parseDouble(value);
                data.put(field.name, obj);
            } else if (FieldType.Timestamp == field.type) {
                Timestamp obj = new Timestamp(
                        new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(value).getTime());
                data.put(field.name, obj);
            } else if (FieldType.Date == field.type) {
                Timestamp ts = new Timestamp(new SimpleDateFormat("yyyy/MM/dd").parse(value).getTime());
                Date obj = new Date(ts.getTime());
                data.put(field.name, obj);
            } else if (FieldType.Time == field.type) {
                Timestamp ts = new Timestamp(new SimpleDateFormat("HH:mm:ss").parse(value).getTime());
                Time obj = new Time(ts.getTime());
                data.put(field.name, obj);
            } else {
                throw new ParseException("Undefined type.[" + field.getType() + "]", aRowNum);
            }
        }
    }

    XmlRecord record = new XmlRecord();
    record.data = data;
    return record;
}

From source file:org.dspace.core.Utils.java

/**
 * Utility method to parse durations defined as {@code \d+[smhdwy]} (seconds,
 * minutes, hours, days, weeks, years)//from  www  .j av  a 2s  . co  m
 * 
 * @param duration
 *            specified duration
 * 
 * @return number of milliseconds equivalent to duration.
 * 
 * @throws ParseException
 *             if the duration is of incorrect format
 */
public static long parseDuration(String duration) throws ParseException {
    Matcher m = DURATION_PATTERN.matcher(duration.trim());
    if (!m.matches()) {
        throw new ParseException("'" + duration + "' is not a valid duration definition", 0);
    }

    String units = m.group(2);
    long multiplier = MS_IN_SECOND;

    if ("s".equals(units)) {
        multiplier = MS_IN_SECOND;
    } else if ("m".equals(units)) {
        multiplier = MS_IN_MINUTE;
    } else if ("h".equals(units)) {
        multiplier = MS_IN_HOUR;
    } else if ("d".equals(units)) {
        multiplier = MS_IN_DAY;
    } else if ("w".equals(units)) {
        multiplier = MS_IN_WEEK;
    } else if ("y".equals(units)) {
        multiplier = MS_IN_YEAR;
    } else {
        throw new ParseException(
                units + " is not a valid time unit (must be 'y', " + "'w', 'd', 'h', 'm' or 's')",
                duration.indexOf(units));
    }

    long qint = Long.parseLong(m.group(1));

    return qint * multiplier;
}

From source file:com.lmdna.spider.berkeleydb.ArchiveUtils.java

/**
 * Parses an ARC-style date.  If passed String is < 12 characters in length,
 * we pad.  At a minimum, String should contain a year (>=4 characters).
 * Parse will also fail if day or month are incompletely specified.  Depends
 * on the above getXXDigitDate methods./*from ww  w.j  a  v  a2  s .c o m*/
 * @param A 4-17 digit date in ARC style (<code>yyyy</code> to
 * <code>yyyyMMddHHmmssSSS</code>) formatting.  
 * @return A Date object representing the passed String. 
 * @throws ParseException
 */
public static Date getDate(String d) throws ParseException {
    Date date = null;
    if (d == null) {
        throw new IllegalArgumentException("Passed date is null");
    }
    switch (d.length()) {
    case 14:
        date = ArchiveUtils.parse14DigitDate(d);
        break;

    case 17:
        date = ArchiveUtils.parse17DigitDate(d);
        break;

    case 12:
        date = ArchiveUtils.parse12DigitDate(d);
        break;

    case 0:
    case 1:
    case 2:
    case 3:
        throw new ParseException("Date string must at least contain a" + "year: " + d, d.length());

    default:
        if (!(d.startsWith("19") || d.startsWith("20"))) {
            throw new ParseException("Unrecognized century: " + d, 0);
        }
        if (d.length() < 8 && (d.length() % 2) != 0) {
            throw new ParseException("Incomplete month/date: " + d, d.length());
        }
        StringBuilder sb = new StringBuilder(d);
        if (sb.length() < 8) {
            for (int i = sb.length(); sb.length() < 8; i += 2) {
                sb.append("01");
            }
        }
        if (sb.length() < 12) {
            for (int i = sb.length(); sb.length() < 12; i++) {
                sb.append("0");
            }
        }
        date = ArchiveUtils.parse12DigitDate(sb.toString());
    }

    return date;
}