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.netscape.cms.publish.publishers.FileBasedPublisher.java

long getCreationTime(File file) throws ParseException {
    // parse and get the creation time from the file name
    String pattern = getGeneralCrlPrefix() + "-(\\d{8}-\\d{6})(-delta)?.(der|b64|zip)";
    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(file.getName());

    if (!m.matches())
        throw new ParseException("Invalid date format.", 0);

    String creationTimeString = m.group(1);
    java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyyMMdd-HHmmss");
    java.util.Date creationTime = format.parse(creationTimeString);
    return creationTime.getTime();
}

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/*ww  w  .ja  v a2  s .c o 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 formatter
 *          The expected format (eg. YYYY-mm-DD)
 * @param required
 *          Field is required to exist at the end of the given path 
 * @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 Date getDateTimeFieldValue(final JSONObject jsonObject, final String[] fieldPath,
        final SimpleDateFormat formatter, final boolean required)
        throws JSONException, IllegalArgumentException, NoSuchElementException, ParseException {

    if (formatter == null)
        throw new IllegalArgumentException("Null is not permitted as input to formatter parameter");

    Object value = getFieldValue(jsonObject, fieldPath);
    if (value == null && !required)
        return null;

    if (value instanceof Date)
        return (Date) value;
    else if (value instanceof String)
        return formatter.parse((String) value);

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

From source file:edu.psu.iam.cpr.core.api.helper.FindPersonHelper.java

/**
 * Parse a date string and return a Calendar object.
 * //from w  w w . j  a  va2s  .c o  m
 * @param dateString The date to parse (in MM-DD-YYYY or MM/DD/YYYY format)
 * @param lenient Should parsing be lenient
 * 
 * @return a Calendar object
 * @throws ParseException if dateString is malformed
 */
public static final Date parseDateString(final String dateString, final boolean lenient) throws ParseException {
    LOG4J_LOGGER.debug("FPH: now = parseDateString for string = " + dateString);

    if (dateString == null) {
        throw new ParseException("Date string is null", 0);
    }

    SimpleDateFormat sdf = new SimpleDateFormat(CprProperties.INSTANCE.getProperties()
            .getProperty(CprPropertyName.CPR_FORMAT_PARTIAL_DATE.toString()));
    sdf.setLenient(lenient);
    Date d = sdf.parse(dateString.replace('-', '/').trim());

    return d;
}

From source file:org.mifosplatform.infrastructure.core.serialization.JsonParserHelper.java

public Integer convertToInteger(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();//from   ww w .  j  a v  a 2  s  . c o  m
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        Integer number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            df.setParseBigDecimal(true);

            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final Number parsedNumber = df.parse(source);

            final double parsedNumberDouble = parsedNumber.doubleValue();
            final int parsedNumberInteger = parsedNumber.intValue();

            if (source.contains(Character.toString(symbols.getDecimalSeparator()))) {
                throw new ParseException(source, 0);
            }

            if (!Double.valueOf(parsedNumberDouble)
                    .equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) {
                throw new ParseException(source, 0);
            }

            number = parsedNumber.intValue();
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.integer.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid integer value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

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

/**
 * Sets the value for the dynamic fields in the specified activity entity.
 * <p>/*from   w  w  w .j  a v  a  2 s . co m*/
 * If field has stacked parser defined, then field value is parsed into separate activity using stacked parser. If
 * field can be parsed by stacked parser, can be merged or added as a child into specified (parent) activity
 * depending on stacked parser reference 'aggregation' attribute value.
 *
 * @param cData
 *            parsing context data package
 * @param field
 *            field to apply value to
 * @param value
 *            value to apply for dynamic fields
 * @throws IllegalStateException
 *             if parser has not been properly initialized
 * @throws ParseException
 *             if an error parsing the specified value
 *
 * @see #applyFieldValue(TNTInputStream, ActivityInfo, ActivityField, Object)
 */
protected void applyDynamicValue(ActivityContext cData, ActivityField field, Object value)
        throws ParseException {
    Map<String, Object> dValMap = parseDynamicValues(cData, field.getDynamicLocators());

    Object[] fValues = Utils.makeArray(value);

    List<ActivityField> tFieldsList = new ArrayList<>();
    for (int vi = 0; vi < fValues.length; vi++) {
        ActivityField tField = field.createTempField(dValMap, vi);
        tFieldsList.add(tField);
    }

    reviewTempFieldsNames(tFieldsList);

    ActivityField tField = null;
    try {
        for (int tfi = 0; tfi < tFieldsList.size(); tfi++) {
            tField = tFieldsList.get(tfi);
            Object fValue = fValues[tfi];

            applyFieldValue(cData.getStream(), cData.getActivity(), tField, Utils.simplifyValue(fValue));
        }
    } catch (Exception e) {
        ParseException pe = new ParseException(StreamsResources.getStringFormatted(
                StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityParser.parsing.failed", tField), 0);
        pe.initCause(e);
        throw pe;
    }
}

From source file:edu.ku.brc.specify.config.DateConverter.java

/**
 * @param dateStr/*from w  w w .  ja  v  a2 s . c o m*/
 * @return Calendar defined by date
 * @throws ParseException
 */
public Calendar convert(String dateStr) throws ParseException {
    if (StringUtils.isBlank(dateStr)) {
        return null;
    }

    DateFormats format = match(dateStr);
    if (format != null) {
        return format.convertToCalendar(dateStr);
    }

    throw new ParseException("unrecognized date format", 0);
}

From source file:org.apache.hadoop.mapred.Counters.java

private static String getBlock(String str, char open, char close, IntWritable index) throws ParseException {
    StringBuilder split = new StringBuilder();
    int next = StringUtils.findNext(str, open, StringUtils.ESCAPE_CHAR, index.get(), split);
    split.setLength(0); // clear the buffer
    if (next >= 0) {
        ++next; // move over '('

        next = StringUtils.findNext(str, close, StringUtils.ESCAPE_CHAR, next, split);
        if (next >= 0) {
            ++next; // move over ')'
            index.set(next);//from  w ww  . j  a v a  2s  .co m
            return split.toString(); // found a block
        } else {
            throw new ParseException("Unexpected end of block", next);
        }
    }
    return null; // found nothing
}

From source file:edu.ku.brc.specify.config.DateConverter.java

/**
 * @param dateStr/*w w w  .  java 2 s . c o m*/
 * @return the precision of dateStr
 * @throws ParseException
 */
public PartialDateEnum getDatePrecision(String dateStr) throws ParseException {
    if (StringUtils.isBlank(dateStr)) {
        return PartialDateEnum.None;
    }

    DateFormats format = match(dateStr);
    if (format != null) {
        return format.getPrecision(dateStr);
    }

    throw new ParseException("unrecognized date format", 0);
}

From source file:edu.hawaii.soest.pacioos.text.SimpleTextSource.java

/**
 *  return the sample observation date given minimal sample metadata
 *//*w  w  w . j a va  2 s .  c  o m*/
public Date getSampleDate(String line) throws ParseException {

    /*
     * Date time formats and field locations are highly dependent on instrument
     * output settings.  The -d and -f options are used to set dateFormats and dateFields,
     * or in the XML-based configuration file
     * 
     * this.dateFormats will look something like {"yyyy-MM-dd", "HH:mm:ss"} or 
     * {"yyyy-MM-dd HH:mm:ss"} or {"yyyy", "MM", "dd", "HH", "mm", "ss"}
     * 
     * this.dateFields will also look something like {1,2} or {1} or {1, 2, 3, 4, 5, 6}
     * 
     * NS01 sample:
     * # 26.1675,  4.93111,    0.695, 0.1918, 0.1163,  31.4138, 09 Dec 2012 15:46:55
     * NS03 sample:
     * #  25.4746,  5.39169,    0.401,  35.2570, 09 Dec 2012, 15:44:36
     */
    // extract the date from the data line
    SimpleDateFormat dateFormat;
    String dateFormatStr = "";
    String dateString = "";
    String[] columns = line.trim().split(this.delimiter);
    log.debug("Delimiter is: " + this.delimiter);
    log.debug(Arrays.toString(columns));
    Date sampleDate = new Date();
    // build the total date format from the individual fields listed in dateFields
    int index = 0;
    if (this.dateFields != null && this.dateFormats != null) {
        for (Integer dateField : this.dateFields) {
            try {
                dateFormatStr += this.dateFormats.get(index); //zero-based list
                dateString += columns[dateField.intValue() - 1].trim(); //zero-based list
            } catch (IndexOutOfBoundsException e) {
                String msg = "There was an error parsing the date from the sample using the date format '"
                        + dateFormatStr + "' and the date field index of " + dateField.intValue();
                if (log.isDebugEnabled()) {
                    e.printStackTrace();
                }
                throw new ParseException(msg, 0);
            }
            index++;
        }
        log.debug("Using date format string: " + dateFormatStr);
        log.debug("Using date string       : " + dateString);
        log.debug("Using time zone         : " + this.timezone);

        this.tz = TimeZone.getTimeZone(this.timezone);
        if (this.dateFormats == null || this.dateFields == null) {
            log.warn("Using the default datetime field for sample data.");
            dateFormat = this.defaultDateFormat;
        }
        // init the date formatter
        dateFormat = new SimpleDateFormat(dateFormatStr);
        dateFormat.setTimeZone(this.tz);

        // parse the date string
        sampleDate = dateFormat.parse(dateString.trim());
    } else {
        log.info("No date formats or date fields were configured. Using the current date for this sample.");
    }

    return sampleDate;
}

From source file:edu.ku.brc.specify.config.DateConverter.java

/**
 * @param dateStr/*  w  ww.  j av  a 2  s. co  m*/
 * @return a String defining a valid Calendar object according to precision of dateStr
 * @throws ParseException
 */
public String adjustForPrecision(String dateStr) throws ParseException {
    if (StringUtils.isBlank(dateStr)) {
        return dateStr;
    }

    DateFormats format = match(dateStr);
    if (format != null) {
        PartialDateEnum prec = format.getPrecision(dateStr);
        return format.adjustForPrecision(dateStr, prec);
    }

    throw new ParseException("unrecognized date format", 0);
}