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.osk.errors.OskException.java

/** Create an {@link java.text.ParseException} with localized message.
 * @param specifier format specifier (to be translated)
 * @param parts parts to insert in the format (no translation)
 * @return an {@link java.text.ParseException} with localized message
 *//*from   w w w .  jav  a 2s. co m*/
public static ParseException createParseException(final Localizable specifier, final Object... parts) {

    return new ParseException("", 0) {

        /** Serializable UID. */
        private static final long serialVersionUID = 4771367217940584391L;

        /** {@inheritDoc} */
        @Override
        public String getMessage() {
            return buildMessage(Locale.US, specifier, parts);
        }

        /** {@inheritDoc} */
        @Override
        public String getLocalizedMessage() {
            return buildMessage(Locale.getDefault(), specifier, parts);
        }

    };

}

From source file:de.codesourcery.utils.xml.XmlHelper.java

public static String getNodeValue(Node n, String defaultValue, boolean isRequired) throws ParseException {

    if (n == null) {

        if (isRequired) {
            final String msg = "Unable to determine node value";
            log.error("getNodeValue(): " + msg);
            throw new ParseException(msg, -1);
        }/*from  www  . j  a v  a 2  s .c o  m*/
        return defaultValue;
    }

    String result = null;
    if (n.getNodeType() == Node.TEXT_NODE) {
        result = n.getNodeValue();
    } else {
        NodeList children = n.getChildNodes();

        if (children.getLength() == 0) {
            log.trace("getNodeValue(): Node " + n.getLocalName() + " is no TEXT_NODE and has no children");
        } else if (children.getLength() == 1) {
            if (children.item(0).getNodeType() == Node.TEXT_NODE) {
                result = children.item(0).getNodeValue();
            } else {
                log.trace("getNodeValue(): Node " + n.getLocalName() + " doesn't have TEXT_NODE children");
            }
        } else {
            log.error(
                    "getNodeValue(): Node " + n.getLocalName() + " is no TEXT_NODE and has multiple children");
            throw new ParseException("Node " + n.getLocalName() + " is no TEXT_NODE and has multiple children",
                    -1);
        }

    }

    if (StringUtils.isBlank(result)) {
        if (isRequired) {
            final String msg = "Node " + n.getLocalName() + " requires a non-blank value";
            log.error("getNodeValue(): " + msg);
            throw new ParseException(msg, -1);
        } else {
            return defaultValue;
        }
    }

    return result;
}

From source file:wptools.lib.Misc.java

/**
 * Parse an ISO8601 date/time string/*from   ww  w . j a  va  2 s. co m*/
 * @param unparsed  String containing date/time expression.
 * @param zone      Time zone suffix to strip, if present.
 * @return Date parsed into a java.util.Date object. Note
 *         that the Date is only suitable for setting
 *         post_date_gmt, not post_date.
 */
public static Date parseDate(String unparsed, String zone) throws ParseException {
    String munged = unparsed.toUpperCase();
    if (munged.endsWith(zone))
        munged = munged.substring(0, munged.length() - zone.length());
    for (SimpleDateFormat fmt : DATE_FORMATS) {
        ParsePosition pos = new ParsePosition(0);
        Date ret = fmt.parse(munged, pos);
        if (ret != null) {
            return ret;
        }
    }
    throw new ParseException("Unparseable date: " + unparsed, 0);
}

From source file:org.jamwiki.utils.XMLUtil.java

/**
 * Given a <code>File</code> object that points to an XML file, parse the
 * XML and return a parsed <code>Document</code> object.
 *
 * @param file The File object that points to the XML file.
 * @param validating Set to <code>true</code> if the parser should
 *  validate against a DTD./*from   www .  jav a  2 s . co  m*/
 * @return A parsed Document object.
 * @throws FileNotFoundException Thrown if the XML file cannot be found.
 * @throws ParseException Thrown if any error occurs during parsing.
 */
public static Document parseXML(File file, boolean validating) throws FileNotFoundException, ParseException {
    if (!file.exists()) {
        throw new FileNotFoundException("File " + file.getAbsolutePath() + " does not exist");
    }
    FileInputStream stream = null;
    try {
        stream = new FileInputStream(file);
        InputSource source = new InputSource(stream);
        try {
            return XMLUtil.parseXML(source, validating);
        } catch (ParseException e) {
            // wrap the exception in order to report the file path
            ParseException pe = new ParseException(
                    "The file " + file.getAbsolutePath() + " could not be parsed", -1);
            pe.initCause(e);
            throw pe;
        }
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // safe to ignore
            }
        }
    }
}

From source file:org.apache.ws.security.util.XmlSchemaDateFormat.java

private void handleParseError(ParsePosition parse_pos, String error_reason) throws ParseException {
    throw new ParseException("INVALID_XSD_DATETIME: " + error_reason, parse_pos.getErrorIndex());
}

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

/**
 * Resolves PCF parameter value from provided {@link PCFContent}: {@link PCFMessage} or {@link MQCFGR}.
 *
 * @param fDataType//from   w  ww .  j a  v  a  2  s  . c  om
 *            field data type
 * @param path
 *            parameter path as array of PCF parameter identifiers
 * @param pcfContent
 *            PCF content data (message or parameters group)
 * @param i
 *            processed path element index
 * @return raw value resolved by locator, or {@code null} if value is not resolved
 *
 * @throws ParseException
 *             if exception occurs while resolving raw data value
 */
protected Object getParamValue(ActivityFieldDataType fDataType, String[] path, PCFContent pcfContent, int i)
        throws ParseException {
    if (ArrayUtils.isEmpty(path) || pcfContent == null) {
        return null;
    }

    Object val = null;
    String paramStr = path[i];

    if (i == 0 && paramStr.equals(HEAD_MQCFH)) {
        val = resolvePCFHeaderValue(fDataType, path[i + 1], (PCFMessage) pcfContent);
    } else {
        try {
            Integer paramId = WmqUtils.getParamId(paramStr);

            PCFParameter param = pcfContent.getParameter(paramId);

            if (i < path.length - 1 && param instanceof MQCFGR) {
                val = getParamValue(fDataType, path, (MQCFGR) param, ++i);
            } else {
                val = resolvePCFParamValue(fDataType, param);
            }
        } catch (NoSuchElementException exc) {
            throw new ParseException(
                    StreamsResources.getStringFormatted(WmqStreamConstants.RESOURCE_BUNDLE_NAME,
                            "ActivityPCFParser.unresolved.pcf.parameter", paramStr),
                    getPCFPosition(pcfContent));
        }
    }

    return val;
}

From source file:com.thinkberg.webdav.lock.LockManager.java

/**
 * Evaluate an 'If:' header condition./* w ww  .j a  va 2s . c  om*/
 * 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(FileObject contextObject, String ifCondition)
        throws FileSystemException, LockConflictException, ParseException {
    List<Lock> locks = discoverLock(contextObject);
    EvaluationResult evaluation = new EvaluationResult();

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

    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:org.hypertable.hadoop.mapred.TextTableInputFormat.java

public void parseColumnPredicate(JobConf job) throws ParseException {
    ColumnPredicate cp = new ColumnPredicate();
    String str = job.get(COLUMN_PREDICATES);
    if (str == null)
        return;/*from   w  ww .j a  va 2 s .co m*/
    int offset = str.indexOf("=^");
    if (offset != -1) {
        cp.column_family = str.substring(0, offset).trim();
        cp.operation = ColumnPredicateOperation.PREFIX_MATCH;
        cp.value = str.substring(offset + 2).trim();
    } else {
        offset = str.indexOf("=");
        if (offset != -1) {
            cp.column_family = str.substring(0, offset).trim();
            cp.operation = ColumnPredicateOperation.EXACT_MATCH;
            cp.value = str.substring(offset + 1).trim();
        } else
            throw new ParseException("Invalid COLUMN_PREDICATE: " + str, 0);
    }
    m_base_spec.addToColumn_predicates(cp);
}

From source file:com.jkoolcloud.tnt4j.streams.utils.TimestampFormatter.java

/**
 * Parses the value into a timestamp with microsecond accuracy based on the specified units.
 * <p>/* w ww.  j a  v  a  2 s  .c  om*/
 * If {@code value} represents decimal number (as {@link Number} or {@link String}, fraction gets preserved by
 * scaling down {@code value} in {@code units} until numeric value expression gets with low (epsilon is
 * {@code 0.001}) or without fraction or {@code units} gets set to {@link TimeUnit#NANOSECONDS}.
 *
 * @param units
 *            units that value is in
 * @param value
 *            value to convert
 * @return microsecond timestamp
 * @throws ParseException
 *             if an error parsing the specified value
 *
 * @see #scale(double, TimeUnit)
 */
public static UsecTimestamp parse(TimeUnit units, Object value) throws ParseException {
    UsecTimestamp ts;
    try {
        long time;
        if (value instanceof Date) {
            time = ((Date) value).getTime();
            units = TimeUnit.MILLISECONDS;
        } else if (value instanceof Calendar) {
            time = ((Calendar) value).getTimeInMillis();
            units = TimeUnit.MILLISECONDS;
        } else {
            if (units == null) {
                units = TimeUnit.MILLISECONDS;
            }

            double dTime = value instanceof Number ? ((Number) value).doubleValue()
                    : Double.parseDouble(value.toString());

            Pair<Double, TimeUnit> sTimePair = scale(dTime, units);
            dTime = sTimePair.getLeft();
            units = sTimePair.getRight();

            time = (long) dTime;
        }

        switch (units) {
        case NANOSECONDS:
            long scale = 1000000L;
            long mSecs = time / scale;
            long uSecs = (time - mSecs * scale) / 1000L;
            ts = new UsecTimestamp(mSecs, uSecs);
            break;
        case MICROSECONDS:
            scale = 1000L;
            mSecs = time / scale;
            uSecs = time - mSecs * scale;
            ts = new UsecTimestamp(mSecs, uSecs);
            break;
        default:
            ts = new UsecTimestamp(units.toMicros(time));
            break;
        }
    } catch (NumberFormatException nfe) {
        ParseException pe = new ParseException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "TimestampFormatter.failed.parsing", value, nfe.getLocalizedMessage()),
                0);
        pe.initCause(nfe);
        throw pe;
    }
    return ts;
}

From source file:libepg.epg.util.datetime.DateTimeFieldConverter.java

/**
 * ?????java.sql.Timestamp??? <br>
 * MJD ??16 16 ??????246?4210BCD???<br>
 * ?????????????1??? <br>/*from   w ww  .  java2 s.c om*/
 * 93/10/13 12:45:00?0xC079124500????
 *
 * @param source 
 * @return ???Timestamp
 * @throws IndexOutOfBoundsException ?????5???
 * @throws java.text.ParseException ??????1????????????????
 *
 */
public static synchronized java.sql.Timestamp BytesToSqlDateTime(byte[] source) throws ParseException {
    if (source.length != 5) {
        throw new IndexOutOfBoundsException(
                "?????5????????"
                        + " ?=" + Hex.encodeHexString(source));
    }

    if (Arrays.equals(source, UNDEFINED_DATETIME_BLOCK.getData())) {
        throw new ParseException("?????????? ? = "
                + Hex.encodeHexString(source), 0);
    }

    StringBuilder sb = new StringBuilder();

    byte[] mjd = new byte[2];
    System.arraycopy(source, 0, mjd, 0, mjd.length);
    sb.append(mjdToString(mjd));

    byte[] hms = new byte[3];
    System.arraycopy(source, 2, hms, 0, hms.length);
    sb.append(BcdTimeToString(hms));

    String dateStr = sb.toString();

    java.text.SimpleDateFormat dateParser = new java.text.SimpleDateFormat(DATE_PATTERN);
    dateParser.setLenient(false);
    long dt = dateParser.parse(dateStr).getTime();
    if (LOG.isTraceEnabled()) {
        LOG.trace(dt);
    }
    return new java.sql.Timestamp(dt);
}