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:com.jkoolcloud.tnt4j.streams.parsers.ActivityRegExParser.java

@Override
protected ActivityInfo parsePreparedItem(ActivityContext cData) throws ParseException {
    if (cData == null || cData.getData() == null) {
        return null;
    }//  w ww  .j a v a  2  s . c o  m

    ActivityInfo ai = new ActivityInfo();
    ActivityField field = null;
    cData.setActivity(ai);
    Matcher matcher = (Matcher) cData.getData();
    // apply fields for parser
    try {
        if (!matchMap.isEmpty()) {
            logger().log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                    "ActivityRegExParser.applying.regex"), matchMap.size());
            ArrayList<String> matches = new ArrayList<>();
            matches.add(""); // dummy entry to index array with match
                             // locations
            while (matcher.find()) {
                String matchStr = matcher.group().trim();
                matches.add(matchStr);
                logger().log(OpLevel.TRACE, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "ActivityRegExParser.match"), matches.size(), matchStr);
            }
            logger().log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                    "ActivityRegExParser.found.matches"), matches.size());
            cData.put(MATCHES_KEY, matches);
            Object value;
            for (Map.Entry<ActivityField, List<ActivityFieldLocator>> fieldMapEntry : matchMap.entrySet()) {
                field = fieldMapEntry.getKey();
                cData.setField(field);
                List<ActivityFieldLocator> locations = fieldMapEntry.getValue();

                value = Utils.simplifyValue(parseLocatorValues(locations, cData));

                if (value != null) {
                    logger().log(OpLevel.TRACE, StreamsResources.getString(
                            StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityRegExParser.setting.field"), field);
                }

                applyFieldValue(field, value, cData);
            }
            cData.remove(MATCHES_KEY);
        }
    } catch (Exception e) {
        ParseException pe = new ParseException(StreamsResources.getStringFormatted(
                StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityRegExParser.failed.parsing.regex", field), 0);
        pe.initCause(e);
        throw pe;
    }
    try {
        Object value;
        for (Map.Entry<ActivityField, List<ActivityFieldLocator>> fieldMapEntry : groupMap.entrySet()) {
            field = fieldMapEntry.getKey();
            cData.setField(field);
            List<ActivityFieldLocator> locations = fieldMapEntry.getValue();

            value = Utils.simplifyValue(parseLocatorValues(locations, cData));

            if (value != null) {
                logger().log(OpLevel.TRACE, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "ActivityRegExParser.setting.group.field"), field);
            }

            applyFieldValue(field, value, cData);
        }
    } catch (Exception e) {
        ParseException pe = new ParseException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "ActivityRegExParser.failed.parsing.regex.group", field),
                0);
        pe.initCause(e);
        throw pe;
    }

    return ai;
}

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

/**
 * Returns a date parsed from a date/dateTime string formatted accorings to
 * ISO 8601 rules.//from   ww w .j  av  a2s .c o m
 *
 * @param date the formatted date/dateTime string.
 * @return the parsed date.
 * @throws ParseException if the date/dateTime string could not be parsed.
 */
public static Date parseISODate(String date) throws ParseException {
    String pattern;
    StringBuffer buffer = new StringBuffer(date);

    switch (buffer.length()) {
    case 4:
        // Year: yyyy (eg 1997)
        pattern = "yyyy";
        break;
    case 7:
        // Year and month: yyyy-MM (eg 1997-07)
        pattern = "yyyy-MM";
        break;
    case 10:
        // Complete date: yyyy-MM-dd (eg 1997-07-16)
        pattern = "yyyy-MM-dd";
        break;
    default:
        // Complete date plus hours and minutes: yyyy-MM-ddTHH:mmTZD (eg 1997-07-16T19:20+01:00)
        // Complete date plus hours, minutes and seconds: yyyy-MM-ddTHH:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
        // Complete date plus hours, minutes, seconds and a decimal fraction of a second: yyyy-MM-ddTHH:mm:ss.STZD (eg 1997-07-16T19:20:30.45+01:00)
        pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

        if (buffer.length() == 16) {
            // add seconds
            buffer.append(":00");
        }
        if (buffer.length() > 16 && buffer.charAt(16) != ':') {
            // insert seconds
            buffer.insert(16, ":00");
        }
        if (buffer.length() == 19) {
            // add milliseconds
            buffer.append(".000");
        }
        if (buffer.length() > 19 && buffer.charAt(19) != '.') {
            // insert milliseconds
            buffer.insert(19, ".000");
        }
        if (buffer.length() == 23) {
            // append timzeone
            buffer.append("+0000");
        }
        if (buffer.length() == 24 && buffer.charAt(23) == 'Z') {
            // replace 'Z' with '+0000'
            buffer.replace(23, 24, "+0000");
        }
        if (buffer.length() == 29 && buffer.charAt(26) == ':') {
            // delete '.' from 'HH:mm'
            buffer.deleteCharAt(26);
        }
    }

    // always set time zone on formatter
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    final String dateFromBuffer = buffer.toString();
    if (dateFromBuffer.length() > 10) {
        format.setTimeZone(TimeZone.getTimeZone("GMT" + dateFromBuffer.substring(23)));
    }
    if (!format.format(format.parse(dateFromBuffer)).equals(dateFromBuffer)) {
        throw new ParseException("Not a valid ISO date", 0);
    }
    format.setTimeZone(TimeZone.getTimeZone("UTC"));

    return format.parse(buffer.toString());
}

From source file:org.opensextant.util.GeodeticUtility.java

/**
 * The most simplistic parsing and validation of "lat lon" or "lat, lon"
 * any amount of whitespace is allowed, provided the lat lon order is there.
 * @param lat_lon string form of a simple lat/lon, e.g.,  "Y X";  No symbols
 * @return LatLon object/*from www. ja va2 s .co  m*/
 * @throws ParseException if string is unparsable
 */
public static LatLon parseLatLon(String lat_lon) throws ParseException {
    if (StringUtils.isBlank(lat_lon)) {
        return null;
    }
    String delim = lat_lon.contains(",") ? "," : " ";

    List<String> LL = TextUtils.string2list(lat_lon, delim);
    LatLon geo = null;
    try {
        geo = new GeoBase(null, lat_lon);
        geo.setLatitude(Double.parseDouble(LL.get(0)));
        geo.setLongitude(Double.parseDouble(LL.get(1)));

    } catch (Exception parseerr) {
        throw new ParseException("Unable to Parse text as XY:" + parseerr.getMessage(), 0);
    }

    if (!validateCoordinate(geo.getLatitude(), geo.getLongitude())) {
        throw new ParseException("Invalid Coordinate values", 0);
    }
    return geo;
}

From source file:org.samcrow.ridgesurvey.data.UploadService.java

/**
 * Uploads an observation//from   w ww . j  av  a  2 s .co m
 *
 * @param observation the observation to upload
 */
private void upload(@NonNull URL url, @NonNull Observation observation)
        throws IOException, ParseException, UploadException {
    Objects.requireNonNull(observation);
    final Map<String, String> formData = formatObservation(observation);
    Log.v(TAG, "Formatted observation: " + formData);

    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {
        // Disable response compression, which might be causing problems
        connection.setRequestProperty("Accept-Encoding", "identity");
        // POST
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setChunkedStreamingMode(0);
        final PrintStream out = new PrintStream(connection.getOutputStream());
        writeFormEncodedData(formData, out);
        out.flush();

        final String response = IOUtils.toString(connection.getInputStream());
        Log.v(TAG, response);

        // Check status
        final int status = connection.getResponseCode();
        if (status == 200) {
            // Check for valid JSON
            final JSONObject json = new JSONObject(response);

            final String result = json.optString("result", "");
            if (!result.equals("success")) {
                final String message = json.optString("message", null);
                if (message != null) {
                    throw new UploadException(message);
                } else {
                    throw new UploadException("Unknown server error");
                }
            }
        } else if (status == 301 || status == 302) {
            // Handle redirect and add cookies
            final String location = connection.getHeaderField("Location");
            if (location != null) {
                final URL redirectUrl = new URL(location);
                Log.i(TAG, "Following redirect to " + redirectUrl);
                upload(redirectUrl, observation);
            } else {
                throw new UploadException("Got a 301 or 302 response with no Location header");
            }
        } else {
            throw new UploadException("Unexpected HTTP status " + status);
        }

    } catch (JSONException e) {
        final ParseException e1 = new ParseException("Failed to parse response JSON", 0);
        e1.initCause(e);
        throw e1;
    } finally {
        connection.disconnect();
    }
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.TNTParseableInputStream.java

/**
 * Makes activity information {@link ActivityInfo} object from raw activity data item.
 * <p>//from w  ww.  j  a v  a2 s .c o  m
 * Default implementation simply calls {@link #applyParsers(Object)} to process raw activity data item.
 *
 * @param data
 *            raw activity data item.
 * @return activity information object
 * @throws Exception
 *             if exception occurs while parsing raw activity data item
 */
protected ActivityInfo makeActivityInfo(T data) throws Exception {
    ActivityInfo ai = null;
    if (data != null) {
        try {
            ai = applyParsers(data);
        } catch (ParseException exc) {
            int position = getActivityPosition();
            ParseException pe = new ParseException(
                    StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                            "TNTInputStream.failed.to.process", position),
                    position);
            pe.initCause(exc);
            throw pe;
        }
    }
    return ai;
}

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

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

    String sValue = root.getAttribute(attrName);

    if (!StringUtils.isBlank(sValue)) {
        try {/*from  www. jav a  2s.com*/
            return Integer.parseInt(sValue);
        } catch (NumberFormatException ex) {
            final String msg = "Invalid attribute value (not a number) for tag <" + root.getNodeName() + ">"
                    + " , attribute " + attrName + " , value '" + sValue + "'";
            log.error("getIntAttribute(): " + msg);
            throw new ParseException(msg, -1);
        }
    } else {

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

        return 0;
    }
}

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

private static int getChar(final char[] s, int index, int multiplier) throws ParseException {
    final char c = s[index];
    if (c >= '0' && c <= '9') {
        return Character.digit(c, 10) * multiplier;
    }/*from   www .j  a  va2  s.  c o m*/
    throw new ParseException("Illegal character", index);
}

From source file:FormatTest.java

public Object stringToValue(String text) throws ParseException {
    StringTokenizer tokenizer = new StringTokenizer(text, ".");
    byte[] a = new byte[4];
    for (int i = 0; i < 4; i++) {
        int b = 0;
        if (!tokenizer.hasMoreTokens())
            throw new ParseException("Too few bytes", 0);
        try {//ww  w.  j a v  a2s.  co m
            b = Integer.parseInt(tokenizer.nextToken());
        } catch (NumberFormatException e) {
            throw new ParseException("Not an integer", 0);
        }
        if (b < 0 || b >= 256)
            throw new ParseException("Byte out of range", 0);
        a[i] = (byte) b;
    }
    if (tokenizer.hasMoreTokens())
        throw new ParseException("Too many bytes", 0);
    return a;
}

From source file:ai.susi.json.JsonDataset.java

public Date parseDate(JSONObject json) throws ParseException {
    if (this.dateFieldName == null || this.dateFieldName.length() == 0 || this.dateFieldFormat == null)
        throw new ParseException("no date field defined", 0);
    Object d = json.get(this.dateFieldName);
    if (d == null)
        throw new ParseException("no date field in json, expected field '" + this.dateFieldName + "'", 0);
    if (d instanceof Date)
        return (Date) d;
    if (!(d instanceof String))
        throw new ParseException(
                "date field in json must contain a String or Date, not " + d.getClass().getName(), 0);
    return this.dateFieldFormat.parse((String) d);
}

From source file:org.unitedinternet.cosmo.calendar.query.ComponentFilter.java

/**
 * Validates this filter's state  /*from w  ww.j a  va  2s.  c  o  m*/
 * @param childCount number of element's children
 * @throws ParseException in case of invalid state
 */
private void validateNotDefinedState(int childCount) throws ParseException {
    if (childCount > 1 && isNotDefinedFilter != null) {
        throw new ParseException("CALDAV:is-not-defined cannnot be present with other child elements", -1);
    }
}