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.apache.jmeter.save.CSVSaveService.java

/**
 * Make a SampleResult given a set of tokens
 * //from   w  w w.  j  a  v a2s.  com
 * @param parts
 *            tokens parsed from the input
 * @param saveConfig
 *            the save configuration (may be updated)
 * @param lineNumber the line number (for error reporting)
 * @return the sample result
 * 
 * @throws JMeterError
 */
private static SampleEvent makeResultFromDelimitedString(final String[] parts,
        final SampleSaveConfiguration saveConfig, // may be updated
        final long lineNumber) {

    SampleResult result = null;
    String hostname = "";// $NON-NLS-1$
    long timeStamp = 0;
    long elapsed = 0;
    String text = null;
    String field = null; // Save the name for error reporting
    int i = 0;
    try {
        if (saveConfig.saveTimestamp()) {
            field = TIME_STAMP;
            text = parts[i++];
            if (saveConfig.printMilliseconds()) {
                try {
                    timeStamp = Long.parseLong(text); // see if this works
                } catch (NumberFormatException e) { // it did not, let's try some other formats
                    log.warn(e.toString());
                    boolean foundMatch = false;
                    for (String fmt : DATE_FORMAT_STRINGS) {
                        SimpleDateFormat dateFormat = new SimpleDateFormat(fmt);
                        dateFormat.setLenient(false);
                        try {
                            Date stamp = dateFormat.parse(text);
                            timeStamp = stamp.getTime();
                            // method is only ever called from one thread at a time
                            // so it's OK to use a static DateFormat
                            log.warn("Setting date format to: " + fmt);
                            saveConfig.setFormatter(dateFormat);
                            foundMatch = true;
                            break;
                        } catch (ParseException e1) {
                            log.info(text + " did not match " + fmt);
                        }
                    }
                    if (!foundMatch) {
                        throw new ParseException("No date-time format found matching " + text, -1);
                    }
                }
            } else if (saveConfig.formatter() != null) {
                Date stamp = saveConfig.formatter().parse(text);
                timeStamp = stamp.getTime();
            } else { // can this happen?
                final String msg = "Unknown timestamp format";
                log.warn(msg);
                throw new JMeterError(msg);
            }
        }

        if (saveConfig.saveTime()) {
            field = CSV_ELAPSED;
            text = parts[i++];
            elapsed = Long.parseLong(text);
        }

        if (saveConfig.saveSampleCount()) {
            result = new StatisticalSampleResult(timeStamp, elapsed);
        } else {
            result = new SampleResult(timeStamp, elapsed);
        }

        if (saveConfig.saveLabel()) {
            field = LABEL;
            text = parts[i++];
            result.setSampleLabel(text);
        }
        if (saveConfig.saveCode()) {
            field = RESPONSE_CODE;
            text = parts[i++];
            result.setResponseCode(text);
        }

        if (saveConfig.saveMessage()) {
            field = RESPONSE_MESSAGE;
            text = parts[i++];
            result.setResponseMessage(text);
        }

        if (saveConfig.saveThreadName()) {
            field = THREAD_NAME;
            text = parts[i++];
            result.setThreadName(text);
        }

        if (saveConfig.saveDataType()) {
            field = DATA_TYPE;
            text = parts[i++];
            result.setDataType(text);
        }

        if (saveConfig.saveSuccess()) {
            field = SUCCESSFUL;
            text = parts[i++];
            result.setSuccessful(Boolean.valueOf(text).booleanValue());
        }

        if (saveConfig.saveAssertionResultsFailureMessage()) {
            i++;
            // TODO - should this be restored?
        }

        if (saveConfig.saveBytes()) {
            field = CSV_BYTES;
            text = parts[i++];
            result.setBytes(Integer.parseInt(text));
        }

        if (saveConfig.saveThreadCounts()) {
            field = CSV_THREAD_COUNT1;
            text = parts[i++];
            result.setGroupThreads(Integer.parseInt(text));

            field = CSV_THREAD_COUNT2;
            text = parts[i++];
            result.setAllThreads(Integer.parseInt(text));
        }

        if (saveConfig.saveUrl()) {
            i++;
            // TODO: should this be restored?
        }

        if (saveConfig.saveFileName()) {
            field = CSV_FILENAME;
            text = parts[i++];
            result.setResultFileName(text);
        }
        if (saveConfig.saveLatency()) {
            field = CSV_LATENCY;
            text = parts[i++];
            result.setLatency(Long.parseLong(text));
        }

        if (saveConfig.saveEncoding()) {
            field = CSV_ENCODING;
            text = parts[i++];
            result.setEncodingAndType(text);
        }

        if (saveConfig.saveSampleCount()) {
            field = CSV_SAMPLE_COUNT;
            text = parts[i++];
            result.setSampleCount(Integer.parseInt(text));
            field = CSV_ERROR_COUNT;
            text = parts[i++];
            result.setErrorCount(Integer.parseInt(text));
        }

        if (saveConfig.saveHostname()) {
            field = CSV_HOSTNAME;
            hostname = parts[i++];
        }

        if (saveConfig.saveIdleTime()) {
            field = CSV_IDLETIME;
            text = parts[i++];
            result.setIdleTime(Long.parseLong(text));
        }
        if (saveConfig.saveConnectTime()) {
            field = CSV_CONNECT_TIME;
            text = parts[i++];
            result.setConnectTime(Long.parseLong(text));
        }

        if (i + saveConfig.getVarCount() < parts.length) {
            log.warn("Line: " + lineNumber + ". Found " + parts.length + " fields, expected " + i
                    + ". Extra fields have been ignored.");
        }

    } catch (NumberFormatException | ParseException e) {
        log.warn("Error parsing field '" + field + "' at line " + lineNumber + " " + e);
        throw new JMeterError(e);
    } catch (ArrayIndexOutOfBoundsException e) {
        log.warn("Insufficient columns to parse field '" + field + "' at line " + lineNumber);
        throw new JMeterError(e);
    }
    return new SampleEvent(result, "", hostname);
}

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

@Override
public Date parse(final String source) throws ParseException {
    final Date date = parse(source, new ParsePosition(0));
    if (date == null) {
        // Add a note re supported date range
        if (locale.equals(JAPANESE_IMPERIAL)) {
            throw new ParseException(
                    "(The " + locale + " locale does not support dates before 1868 AD)\n"
                            + "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(),
                    0);/*from   ww w.j  av a 2  s. c  o  m*/
        }
        throw new ParseException(
                "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0);
    }
    return date;
}

From source file:org.chiba.xml.xforms.xpath.ExtensionFunctionsHelper.java

/**
 * Parses the specified xsd:duration string.
 * <p/>/*from  w ww  . j a  v a2s  .co  m*/
 * Returns an array of length 7:
 * <ul>
 * <li>[0] plus/minus (1 or -1)</li>
 * <li>[1] years</li>
 * <li>[2] months</li>
 * <li>[3] days</li>
 * <li>[4] hours</li>
 * <li>[5] minutes</li>
 * <li>[6] seconds</li>
 * </ul>
 *
 * @param duration the xsd:duration string.
 * @return an array containing the parsed values.
 * @throws ParseException if the duration string could not be parsed.
 */
public static float[] parseISODuration(String duration) throws ParseException {
    // duration format (-)PnYnMnDTnHnMnS
    float[] values = new float[7];
    int index = 0;

    // check minus sign
    if (duration.charAt(index) == '-') {
        values[0] = -1;
        index++;
    } else {
        values[0] = 1;
    }

    // check 'P' designator
    if (duration.charAt(index) == 'P') {
        index++;
    } else {
        throw new ParseException("missing 'P' designator at [" + index + "]", index);
    }

    char designator;
    int offset;
    int slot;
    boolean time = false;
    boolean pending = false;
    String value = null;

    while (index < duration.length()) {
        // get designator
        designator = duration.charAt(index);

        // time designator
        if (designator == 'T') {
            time = true;

            index++;
            continue;
        }

        // field designator
        if (isDesignator(designator)) {
            if (!pending) {
                throw new ParseException("missing value at [" + index + "]", index);
            }

            slot = getDesignatorSlot(designator, time);
            try {
                values[slot] = getDesignatorValue(designator, value);
            } catch (NumberFormatException e) {
                throw new ParseException("malformed value at [" + (index - value.length()) + "]",
                        (index - value.length()));
            }

            pending = false;
            index++;
            continue;
        }

        // field value
        offset = getNumberOffset(duration, index);
        if (offset == index) {
            throw new ParseException("missing value at [" + index + "]", index);
        }
        if (offset == duration.length()) {
            throw new ParseException("missing designator at [" + offset + "]", offset);
        }

        value = duration.substring(index, offset);
        index = offset;
        pending = true;
    }

    return values;
}

From source file:org.araqne.confdb.file.Importer.java

@SuppressWarnings("unchecked")
private Object removeType(List<Object> l) throws ParseException {
    if (l == null)
        throw new ParseException("list can not be null", 0);

    if (l.size() != 2)
        throw new ParseException("list size should be 2", 0);

    String type = (String) l.get(0);
    Object value = l.get(1);/*ww  w  . java 2  s  .  co m*/

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
    try {

        if (type.equals("string")) {
            return (String) value;
        } else if (type.equals("int")) {
            return (Integer) value;
        } else if (type.equals("long")) {
            return Long.valueOf(value.toString());
        } else if (type.equals("bool")) {
            return (Boolean) value;
        } else if (type.equals("ip4")) {
            return (Inet4Address) Inet4Address.getByName((String) value);
        } else if (type.equals("ip6")) {
            return (Inet6Address) Inet6Address.getByName((String) value);
        } else if (type.equals("double")) {
            return (Double) value;
        } else if (type.equals("float")) {
            return Float.valueOf(value.toString());
        } else if (type.equals("date")) {
            return dateFormat.parse((String) value);
        } else if (type.equals("short")) {
            return Short.valueOf(value.toString());
        } else if (type.equals("map")) {
            Map<String, Object> m = (Map<String, Object>) value;

            for (String name : m.keySet()) {
                List<Object> v = (List<Object>) m.get(name);
                m.put(name, removeType(v));
            }

            return m;
        } else if (type.equals("list")) {
            List<Object> newList = new ArrayList<Object>();
            List<Object> values = (List<Object>) value;
            for (Object o : values)
                newList.add(removeType((List<Object>) o));

            return newList;
        } else if (type.equals("null")) {
            return null;
        } else if (type.equals("blob")) {
            String byteString = (String) value;

            return Base64.decode(byteString);
        } else {
            throw new IllegalArgumentException("unsupported value [" + value + "], type [" + type + "]");
        }
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("invalid host [" + value + "]", e);
    }
}

From source file:org.opentides.util.StringUtil.java

@Deprecated
public static Date convertFlexibleDate(String strDate, String[] formats) throws ParseException {
    if (StringUtil.isEmpty(strDate))
        return null;
    for (int i = 0; i < formats.length; i++) {
        try {//from  ww  w  . j  a  v a 2s  .c  o m
            SimpleDateFormat dtFormatter = new SimpleDateFormat(formats[i]);
            dtFormatter.setLenient(false);
            return dtFormatter.parse(strDate.trim());
        } catch (ParseException e) {
            // do nothing... try other format
        }
    }
    // we are unable to convert
    throw new ParseException("No matching date format for " + strDate, 0);
}

From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java

/**
 * Extracts from a {@link JSONObject} the value of the field referenced by the provided path. The received content is treated as
 * {@link String} value which must be parsed into a {@link ZonedDateTime} representation. If the value is a plain {@link ZonedDateTime} value 
 * it is returned right away. {@link ZonedDateTime} values contained inside {@link String} instances are parsed out by {@link SimpleDateFormat#parse(String)}. 
 * If parsing fails or the type is not of the referenced ones the method throws a {@link ParseException}
 * @param jsonObject/*from  w w  w  .j av a2  s. co m*/
 *          The {@link JSONObject} to read the value from (null is not permitted as input)
 * @param fieldPath
 *          Path inside the {@link JSONObject} pointing towards the value of interest (null is not permitted as input)
 * @param formatString
 *          The expected format (eg. YYYY-mm-DD)
 * @return
 *          Value found at the end of the provided path. An empty path simply returns the input
 * @throws JSONException
 *          Thrown in case extracting values from the {@link JSONObject} fails for any reason
 * @throws IllegalArgumentException
 *          Thrown in case a provided parameter does not comply with the restrictions
 * @throws NoSuchElementException
 *          Thrown in case an element referenced inside the path does not exist at the expected location inside the {@link JSONObject}
 * @throws ParseException
 *          Thrown in case parsing out an {@link ZonedDateTime} from the retrieved field value fails for any format related reason 
 */
public ZonedDateTime getZonedDateTimeFieldValue(final JSONObject jsonObject, final String[] fieldPath,
        final String formatString)
        throws JSONException, IllegalArgumentException, NoSuchElementException, ParseException {

    Object value = getFieldValue(jsonObject, fieldPath);
    if (value instanceof ZonedDateTime)
        return (ZonedDateTime) value;
    else if (value instanceof String)
        return (StringUtils.isNotBlank(formatString)
                ? ZonedDateTime.parse((String) value, DateTimeFormatter.ofPattern(formatString))
                : ZonedDateTime.parse((String) value));

    throw new ParseException("Types of " + (value != null ? value.getClass().getName() : "null")
            + " cannot be parsed into a valid zoned date & time representation", 0);
}

From source file:org.jvnet.hudson.plugins.thinbackup.utils.Utils.java

/**
 * @param directory root directory of all backups
 * @return a list of backups in the given directory (both FULL and DIFF), displayed as the respective backup date,
 *         from both directories and ZIP files, ordered descending by the date encoded in the backups' name.
 *//*from w w w  .  j  av  a 2 s .c om*/
public static List<String> getBackupsAsDates(final File directory) {
    final List<String> backupDates = new ArrayList<String>();

    final List<BackupSet> backupSets = getValidBackupSets(directory);
    for (final BackupSet backupSet : backupSets) {
        final String fullName = backupSet.getFullBackupName();
        try {
            final Date tmp = getDateFromBackupDirectoryName(fullName);
            if (tmp != null) {
                backupDates.add(DISPLAY_DATE_FORMAT.format(tmp));
            } else {
                throw new ParseException("", 0);
            }
        } catch (final ParseException e) {
            LOGGER.warning(String.format(
                    "Cannot parse directory name '%s' , therefore it will not show up in the list of available backups.",
                    fullName));
        }

        for (final String diffName : backupSet.getDiffBackupsNames()) {
            try {
                final Date tmp = getDateFromBackupDirectoryName(diffName);
                if (tmp != null) {
                    backupDates.add(DISPLAY_DATE_FORMAT.format(tmp));
                } else {
                    throw new ParseException("", 0);
                }
            } catch (final ParseException e) {
                LOGGER.warning(String.format(
                        "Cannot parse directory name '%s' , therefore it will not show up in the list of available backups.",
                        diffName));
            }
        }
    }

    Collections.sort(backupDates);
    Collections.reverse(backupDates);

    return backupDates;
}

From source file:com.ettrema.zsync.Upload.java

/**
 * A helper method that reads from an InputStream and copies to an OutputStream until the LF character is read (The LF is not
 * copied to the OutputStream). An exception is thrown if maxsearch bytes are read without encountering LF. This is used by {@link #parse} 
 * to copy the relocate values into a BufferingOutputStream. 
 * /*from  ww w  . ja v  a 2 s  .  c o  m*/
 * @param in The InputStream to read from
 * @param maxsearch The maximum number of bytes to search for a newline
 * @param out The OutputStream to copy into
 * @return The number of bytes read from in
 * @throws IOException
 * @throws ParseException If a newline is not found within maxsearch reads
 */
private static int copyLine(InputStream in, int maxsearch, OutputStream out)
        throws IOException, ParseException {

    if (maxsearch <= 0) {
        throw new RuntimeException("copyLine: Invalid maxsearch " + maxsearch);
    }

    byte nextByte, bytesRead = 0;
    byte NEWLINE = Character.toString(LF).getBytes(CHARSET)[0];

    while ((nextByte = (byte) in.read()) > -1) {

        if (++bytesRead > maxsearch) {
            throw new ParseException("Could not find delimiter within " + maxsearch + " bytes.", 0);
        }
        if (nextByte == NEWLINE) {
            break;
        }
        out.write(nextByte);
    }

    return bytesRead;
}

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

public static String getAttribute(Element root, String attrName, boolean isRequired) throws ParseException {

    String sValue = root.getAttribute(attrName);

    if (!StringUtils.isBlank(sValue)) {
        return sValue;
    } else {/*from w w  w. jav  a 2 s.  co  m*/

        if (isRequired) {
            final String msg = "Tag <" + root.getNodeName() + "> is lacking required attribute " + attrName;
            log.error("getAttribute(): " + msg);
            throw new ParseException(msg, -1);
        }

        return null;
    }
}

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

public Date parse(final String source) throws ParseException {
    final Date date = parse(source, new ParsePosition(0));
    if (date == null) {
        // Add a note re supported date range
        if (locale.equals(JAPANESE_IMPERIAL)) {
            throw new ParseException(
                    "(The " + locale + " locale does not support dates before 1868 AD)\n"
                            + "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(),
                    0);//w  w  w. ja  va2  s .  co m
        }
        throw new ParseException(
                "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0);
    }
    return date;
}