Example usage for java.text ParseException initCause

List of usage examples for java.text ParseException initCause

Introduction

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

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

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

/**
 * Given an <code>InputSource</code> object that points to XML data, parse
 * the XML and return a parsed <code>Document</code> object.
 *
 * @param source The InputSource object that points to XML data.
 * @param validating Set to <code>true</code> if the parser should
 *  validate against a DTD.//from   w  w w .  jav a2s. c o m
 * @return A parsed Document object.
 * @throws ParseException Thrown if any error occurs during parsing.
 */
public static Document parseXML(InputSource source, boolean validating) throws ParseException {
    // Create a builder factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(validating);
    // Create the builder and parse the file
    try {
        return factory.newDocumentBuilder().parse(source);
    } catch (IOException e) {
        ParseException pe = new ParseException("IO exception while parsing XML", -1);
        pe.initCause(e);
        throw pe;
    } catch (ParserConfigurationException e) {
        ParseException pe = new ParseException("XML could not be parsed", -1);
        pe.initCause(e);
        throw pe;
    } catch (SAXException e) {
        ParseException pe = new ParseException("XML contains invalid XML", -1);
        pe.initCause(e);
        throw pe;
    }
}

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./*  ww w .  j  av a2s.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:com.jkoolcloud.tnt4j.streams.utils.TimestampFormatter.java

/**
 * Parses the value into a timestamp with microsecond accuracy based on the specified units.
 * <p>/* www.j  a  v  a 2  s  .  co  m*/
 * 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:org.cook_e.data.StorageParser.java

/**
 * Parses a serialized list of steps/*from   w ww  . j  a v a  2  s.c  om*/
 * @param stepsString a string representing a list of steps, in the format returned by
 *                    {@link #serializeRecipeSteps(List)}
 * @return the steps in the provided String
 * @throws java.text.ParseException if the steps could not be parsed
 */
public List<Step> parseRecipeSteps(String stepsString) throws ParseException {
    try {
        final JSONArray json = new JSONArray(stepsString);
        final List<Step> steps = new ArrayList<>(json.length());
        for (int i = 0; i < json.length(); i++) {
            final JSONObject stepJson = json.getJSONObject(i);

            final String description = stepJson.getString("description");
            final Duration duration = Duration.millis(stepJson.getLong("duration_ms"));
            final boolean simultaneous = stepJson.getBoolean("simultaneous");

            final JSONArray ingredientsJson = stepJson.getJSONArray("ingredients");
            final List<String> ingredients = new ArrayList<>(ingredientsJson.length());
            for (int j = 0; j < ingredientsJson.length(); j++) {
                ingredients.add(ingredientsJson.getString(j));
            }
            steps.add(new Step(ingredients, description, duration, simultaneous, i));
        }

        return steps;
    } catch (JSONException e) {
        final ParseException parseException = new ParseException("Invalid JSON", 0);
        parseException.initCause(e);
        throw parseException;
    }
}

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

/**
 * Gets field raw data value resolved by locator.
 *
 * @param locator/*from  w  ww. ja v a 2s. c o m*/
 *            activity field locator
 * @param cData
 *            activity data carrier object
 * @param formattingNeeded
 *            flag to set if value formatting is not needed
 * @return substring value resolved by locator, or {@code null} if value is not resolved
 */
@Override
protected Object resolveLocatorValue(ActivityFieldLocator locator, ActivityContext cData,
        AtomicBoolean formattingNeeded) throws ParseException {
    Object val = null;
    String locStr = locator.getLocator();
    try {
        IntRange range = IntRange.getRange(locStr, true);

        val = StringUtils.substring(cData.getData(), range.getFrom(), range.getTo());
    } catch (Exception exc) {
        ParseException pe = new ParseException(StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ActivityStringParser.range.exception"), 0);
        pe.initCause(exc);

        throw pe;
    }

    return val;
}

From source file:com.blackberry.logdriver.timestamp.Rfc5424TimestampParser.java

@Override
public long parseTimestatmp(String timestamp) throws ParseException {
    try {/*from ww w  .  j ava2  s.c  o  m*/
        // Parse the easy part of the string
        String firstPart = timestamp.substring(0, 19);
        Long time;
        time = dateCache.get(firstPart);
        if (time == null) {
            time = dateFormat.parse(firstPart).getTime();
            dateCache.put(firstPart, time);
        }
        int currentIndex = 19;
        char c = timestamp.charAt(currentIndex);

        // Check for fractional seconds to add. We only record up to millisecond
        // precision, so only grab up to three digits.
        if (timestamp.charAt(currentIndex) == '.') {
            // There are fractional seconds, so grab up to 3.
            // The first digit is guaranteed by the spec. After that, we need to
            // check if we still have digits.
            // The spec requires a timezone, so we can't run out of digits
            // before we run out of string.
            currentIndex++;
            c = timestamp.charAt(currentIndex);
            time += 100 * Character.getNumericValue(c);
            currentIndex++;
            c = timestamp.charAt(currentIndex);
            if (Character.isDigit(c)) {
                time += 10 * Character.getNumericValue(c);
                currentIndex++;
                c = timestamp.charAt(currentIndex);
                if (Character.isDigit(c)) {
                    time += Character.getNumericValue(c);
                    currentIndex++;
                    c = timestamp.charAt(currentIndex);
                    // Now just go through the digits until we're done.
                    while (Character.isDigit(c)) {
                        currentIndex++;
                        c = timestamp.charAt(currentIndex);
                    }
                }
            }

        }

        // Now adjust for timezone offset. either Z or +/-00:00
        boolean positiveTimeZone = true;
        if (c == 'Z') {
            // That's fine. No adjustment.
        } else {
            if (c == '+') {
                positiveTimeZone = true;
            } else if (c == '-') {
                positiveTimeZone = false;
            } else {
                throw new IllegalArgumentException("Malformed date:" + timestamp);
            }

            // Grab the next 2 for hour. Then skip the colon and grab the next
            // 2.
            currentIndex++;
            int hour = Integer.parseInt(timestamp.substring(currentIndex, currentIndex + 2));
            currentIndex += 2;
            c = timestamp.charAt(currentIndex);
            if (c != ':') {
                throw new IllegalArgumentException("Malformed date:" + timestamp);
            }
            currentIndex++;
            int minute = Integer.parseInt(timestamp.substring(currentIndex, currentIndex + 2));

            int offset = (60 * hour + minute) * 60 * 1000;
            if (positiveTimeZone) {
                time -= offset;
            } else {
                time += offset;
            }

        }

        // If we support daylight savings, then we need to keep checking if we're
        // in
        // daylight savings or not.
        if (daylightSavings) {
            time += tz.getOffset(time);
        } else {
            time += tzOffset;
        }

        return time;
    } catch (ParseException e) {
        throw e;
    } catch (Throwable t) {
        ParseException e = new ParseException("Unexpected Exception", 0);
        e.initCause(t);
        throw e;
    }
}

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

/**
 * Uploads an observation/*from ww w  . j  a  v a 2  s .  c o  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.parsers.ActivityJsonParser.java

@Override
protected ActivityContext prepareItem(TNTInputStream<?, ?> stream, Object data) throws ParseException {
    DocumentContext jsonDoc;/*from w ww. ja  v a2  s.c o m*/
    String jsonString = null;
    try {
        if (data instanceof DocumentContext) {
            jsonDoc = (DocumentContext) data;
        } else if (data instanceof InputStream) {
            jsonDoc = JsonPath.parse((InputStream) data);
        } else {
            jsonString = getNextActivityString(data);
            if (StringUtils.isEmpty(jsonString)) {
                return null;
            }
            jsonDoc = JsonPath.parse(jsonString);
        }
    } catch (Exception e) {
        ParseException pe = new ParseException(StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ActivityJsonParser.jsonDocument.parse.error"), 0);
        pe.initCause(e);

        throw pe;
    }

    if (jsonString == null) {
        jsonString = jsonDoc.jsonString();
    }

    ActivityContext cData = new ActivityContext(stream, data, jsonDoc);
    cData.setMessage(jsonString);

    return cData;
}

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;
    }/* ww w .j  a v a 2  s.co  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:com.jkoolcloud.tnt4j.streams.inputs.TNTParseableInputStream.java

/**
 * Makes activity information {@link ActivityInfo} object from raw activity data item.
 * <p>//from  w  ww .  ja  va  2s  . com
 * 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;
}