Example usage for java.text ParsePosition ParsePosition

List of usage examples for java.text ParsePosition ParsePosition

Introduction

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

Prototype

public ParsePosition(int index) 

Source Link

Document

Create a new ParsePosition with the given initial index.

Usage

From source file:com.anrisoftware.globalpom.format.latlong.LatitudeFormat.java

/**
 * Parses the latitude part to a latitude/longitude coordinate.
 * //  w  w  w  . jav  a  2  s. co m
 * @return the parsed {@link LatLong}.
 * 
 * @throws ParseException
 *             if the string can not be parsed.
 */
public LatLong parse(String source) throws ParseException {
    ParsePosition pos = new ParsePosition(0);
    LatLong result = parse(source, pos);
    if (pos.getIndex() == 0) {
        throw log.errorParseLatitude(source, pos);
    }
    return result;
}

From source file:com.alibaba.otter.node.etl.common.db.utils.SqlTimestampConverter.java

private Date parseDate(String str, String[] parsePatterns, Locale locale) throws ParseException {
    if ((str == null) || (parsePatterns == null)) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }// w  ww .j a  va  2  s.co m

    SimpleDateFormat parser = null;
    ParsePosition pos = new ParsePosition(0);

    for (int i = 0; i < parsePatterns.length; i++) {
        if (i == 0) {
            parser = new SimpleDateFormat(parsePatterns[0], locale);
        } else {
            parser.applyPattern(parsePatterns[i]);
        }
        pos.setIndex(0);
        Date date = parser.parse(str, pos);
        if ((date != null) && (pos.getIndex() == str.length())) {
            return date;
        }
    }

    throw new ParseException("Unable to parse the date: " + str, -1);
}

From source file:com.nridge.core.base.field.FieldValue.java

/**
 * Returns the default value property of the field as a <i>Date</i>
 * object instance.  The date is derived from the value using the
 * format mask of <code>Field.FORMAT_DATETIME_DEFAULT</code>.
 *
 * @return A {@link Date} reflecting the default value.
 *//*from   www . ja v a 2s  . c o m*/
public Date getDefaultValueAsDate() {
    if (StringUtils.isNotEmpty(mDefaultValue)) {
        ParsePosition parsePosition = new ParsePosition(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Field.FORMAT_DATETIME_DEFAULT);
        return simpleDateFormat.parse(mDefaultValue, parsePosition);
    } else
        return new Date();
}

From source file:org.eclipse.wb.internal.css.semantics.LengthValue.java

/**
 * Checks if current value requires unit. We need unit only if value is number.
 *///from w  ww  .  j  av a  2 s  . c om
public boolean requiresUnit() {
    if (hasValue()) {
        ParsePosition parsePosition = new ParsePosition(0);
        VALUE_DECIMAL_FORMAT.parse(m_value, parsePosition);
        return parsePosition.getIndex() == m_value.length();
    }
    return false;
}

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to an int primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)// www.ja  va 2 s  .  c o  m
 *@return the converted Integer value.
 */
public static Integer formatInt(String value, Locale locale) {
    Integer result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Integer.MIN_VALUE && num.doubleValue() <= Integer.MAX_VALUE) {
                result = new Integer(num.intValue());
            }
        }
    }

    return result;
}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.ClientLogDbController.java

@Override
public List<LogInfo> getElementByUuid(String _uuid, eActionType _actionType, eModelType _modelType,
        String _time) {/*  ww  w  . j  a  v  a  2 s  .c o m*/
    Cursor cursor = mContentResolver.query(Uri.withAppendedPath(InstalistProvider.BASE_CONTENT_URI, "log"),
            LogInfo.COLUMN.ALL_COLUMNS,
            LogInfo.COLUMN.ITEM_UUID + " LIKE ? AND " + LogInfo.COLUMN.ACTION + " = ? AND "
                    + LogInfo.COLUMN.MODEL + " = ? AND " + LogInfo.COLUMN.ACTION_DATE + " >= ? ",
            new String[] { _uuid, String.valueOf(_actionType.ordinal()), String.valueOf(_modelType.ordinal()),
                    _time },
            null);
    if (cursor == null) {
        return new ArrayList<>();
    }

    if (cursor.getCount() == 0) {
        cursor.close();
        return new ArrayList<>();
    }

    List<LogInfo> list = new ArrayList<>(cursor.getCount());
    cursor.moveToFirst();
    try {
        do {
            int id = cursor.getInt(cursor.getColumnIndex(LogInfo.COLUMN.ID));
            String uuid = cursor.getString(cursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID));
            int action = cursor.getInt(cursor.getColumnIndex(LogInfo.COLUMN.ACTION));
            eActionType actionType = eActionType.getTypeById(action);
            int model = cursor.getInt(cursor.getColumnIndex(LogInfo.COLUMN.MODEL));
            eModelType modelType = eModelType.getTypeId(model);
            String date = cursor.getString(cursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));

            list.add(new LogInfo(id, uuid, actionType, modelType,
                    ISO8601Utils.parse(date, new ParsePosition(0))));
        } while (cursor.moveToNext());
    } catch (ParseException e) {
        e.printStackTrace();
        return new ArrayList<>();
    } finally {
        cursor.close();
    }
    return list;
}

From source file:org.eclipse.riena.ui.ridgets.validation.AbstractValidDate.java

private boolean isDate(final String value, final String pattern, final boolean strict) {
    if (value == null || pattern == null || pattern.length() <= 0) {

        return false;
    }/*from w w w .  ja va 2  s. c om*/
    if (strict && value.length() != pattern.length()) {
        return false;
    }
    final SimpleDateFormat formatter = new SimpleDateFormat(pattern);
    formatter.setLenient(false);

    final ParsePosition pos = new ParsePosition(0);
    formatter.parse(value, pos);
    if (pos.getErrorIndex() != -1) {
        return false;
    }
    if (strict) {
        if (pos.getIndex() < value.length()) {
            return false;
        }
    }
    return true;
}

From source file:org.dspace.statistics.util.ClassicDSpaceLogConverter.java

/**
 * Convert a classic log file/*from  ww  w  .  j  a  v a 2s  . co m*/
 *
 * @param in The filename to read from
 * @param out The filename to write to
 * @return The number of lines processed
 */
public int convert(String in, String out) {
    // Line counter
    int counter = 0;
    int lines = 0;

    // Figure out input, output
    BufferedReader input;
    Writer output;
    try {
        if (null == in || in.isEmpty() || "-".equals(in)) {
            input = new BufferedReader(new InputStreamReader(System.in));
            in = "standard input";
        } else
            input = new BufferedReader(new FileReader(in));

        if (null == out || out.isEmpty() || "-".equals(out)) {
            output = new BufferedWriter(new OutputStreamWriter(System.out));
            out = "standard output";
        } else
            output = new BufferedWriter(new FileWriter(out));
    } catch (IOException ie) {
        log.error("File access problem", ie);
        return 0;
    }

    // Say what we're going to do
    System.err.println(" About to convert '" + in + "' to '" + out + "'");

    // Setup the regular expressions for the log file
    LogAnalyser.setRegex(in);

    // Open the file and read it line by line
    try {
        String line;
        LogLine lline;
        String lout;
        String id;
        String handle;
        String ip;
        String date;
        DSpaceObject dso;
        String uid;
        String lastLine = "";

        while ((line = input.readLine()) != null) {
            // Read in the line and convert it to a LogLine
            lines++;
            if (verbose) {
                System.out.println("  - IN: " + line);
            }
            lline = LogAnalyser.getLogLine(line);

            // Get rid of any lines that aren't INFO
            if ((lline == null) || (!lline.isLevel("INFO"))) {
                if (verbose) {
                    System.out.println("   - IGNORED!");
                }
                continue;
            }

            // Get the IP address of the user
            Matcher matcher = ipaddrPattern.matcher(line);
            if (matcher.find()) {
                ip = matcher.group(1);
            } else {
                ip = "unknown";
            }

            // Get and format the date
            // We can use lline.getDate() as this strips the time element
            date = dateFormatOut
                    .format(dateFormatIn.parse(line.substring(0, line.indexOf(',')), new ParsePosition(0)));

            // Generate a UID for the log line
            // - based on the date/time
            uid = dateFormatOutUID.format(dateFormatInUID
                    .parse(line.substring(0, line.indexOf(' ', line.indexOf(' ') + 1)), new ParsePosition(0)));

            try {
                // What sort of view is it?
                // (ignore lines from org.dspace.usage.LoggerUsageEventListener which is 1.6 code)
                if ((lline.getAction().equals("view_bitstream"))
                        && (!lline.getParams().contains("invalid_bitstream_id"))
                        && (!lline.getParams().contains("withdrawn"))
                        && ((!line.contains("org.dspace.usage.LoggerUsageEventListener")) || newEvents)) {
                    id = lline.getParams().substring(13);
                } else if ((lline.getAction().equals("view_item"))
                        && ((!line.contains("org.dspace.usage.LoggerUsageEventListener")) || newEvents)) {
                    handle = lline.getParams().substring(7);
                    dso = HandleManager.resolveToObject(context, handle);
                    id = "" + dso.getID();
                } else if ((lline.getAction().equals("view_collection"))
                        && ((!line.contains("org.dspace.usage.LoggerUsageEventListener")) || newEvents)) {
                    id = lline.getParams().substring(14);
                } else if ((lline.getAction().equals("view_community"))
                        && ((!line.contains("org.dspace.usage.LoggerUsageEventListener")) || newEvents)) {
                    id = lline.getParams().substring(13);
                } else {
                    //if (verbose) System.out.println("   - IGNORED!");
                    continue;
                }

                // Construct the log line
                lout = uid + "," + lline.getAction() + "," + id + "," + date + "," + lline.getUser() + "," + ip
                        + "\n";
            } catch (Exception e) {
                if (verbose) {
                    System.out.println("  - IN: " + line);
                }
                if (verbose) {
                    System.err.println("Error with log line! " + e.getMessage());
                }
                continue;
            }

            if ((verbose) && (!"".equals(lout))) {
                System.out.println("  - IN: " + line);
                System.out.println("  - OUT: " + lout);
            }

            // Write the output line
            if ((!"".equals(lout)) && (!lout.equals(lastLine))) {
                output.write(lout);
                counter++;
                lastLine = lout;
            }
        }
    } catch (IOException e) {
        log.error("File access problem", e);
    } finally {
        // Clean up the input and output streams
        try {
            input.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        try {
            output.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        try {
            output.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Tell the user what we have done
    System.err.println("  Read " + lines + " lines and recorded " + counter + " events");
    return counter;
}

From source file:org.opendatakit.common.android.utilities.WebUtils.java

@SuppressLint("SimpleDateFormat")
private Date parseDateSubset(String value, String[] parsePatterns, Locale l, TimeZone tz) {
    // borrowed from apache.commons.lang.DateUtils...
    Date d = null;/*  w w w  . ja  v a  2  s .  co m*/
    SimpleDateFormat parser = null;
    ParsePosition pos = new ParsePosition(0);
    for (int i = 0; i < parsePatterns.length; i++) {
        if (i == 0) {
            if (l == null) {
                parser = new SimpleDateFormat(parsePatterns[0]);
            } else {
                parser = new SimpleDateFormat(parsePatterns[0], l);
            }
        } else {
            parser.applyPattern(parsePatterns[i]);
        }
        parser.setTimeZone(tz); // enforce UTC for formats without timezones
        pos.setIndex(0);
        d = parser.parse(value, pos);
        if (d != null && pos.getIndex() == value.length()) {
            return d;
        }
    }
    return d;
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to an int primitive.
 * //  w  w  w.  j a va 2  s  .c  o  m
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)
 * @return the converted Integer value.
 */
public static Integer formatInt(String value, Locale locale) {
    Integer result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Integer.MIN_VALUE && num.doubleValue() <= Integer.MAX_VALUE) {
                result = new Integer(num.intValue());
            }
        }
    }

    return result;
}