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.quinsoft.opencuas.RevenueDomain.java

@Override
public Object convertExternalValue(Task task, AttributeInstance attributeInstance, AttributeDef attributeDef,
        String contextName, Object externalValue) {
    // If external value is an AttributeInstance then get *its* internal value.
    if (externalValue instanceof AttributeInstance)
        externalValue = ((AttributeInstance) externalValue).getValue();

    // KJS - Added 01/28/11 the following two returns.
    if (externalValue == null)
        return null;

    if (externalValue instanceof Number)
        return ((Number) externalValue).doubleValue();

    if (externalValue instanceof CharSequence) {
        String str = externalValue.toString();

        // VML uses "" as a synonym for null.
        if (StringUtils.isBlank(str))
            return null;

        ParsePosition ps = new ParsePosition(0);
        Double d;//w w w . j a  v  a2s  . c  o m
        synchronized (parser) {
            d = parser.parse(str, ps).doubleValue();
        }

        int idx = Math.max(ps.getErrorIndex(), ps.getIndex());
        if (idx != str.length()) {
            throw new InvalidAttributeValueException(attributeDef, str,
                    "Error parsing '" + str + "' at position " + (idx + 1));
        }

        return d;
    }

    throw new InvalidAttributeValueException(attributeDef, externalValue, "Can't convert '%s' to Double",
            externalValue.getClass().getName());
}

From source file:org.springframework.binding.convert.converters.FormattedStringToNumber.java

@SuppressWarnings("unchecked")
protected Object toObject(String string, Class<?> targetClass) throws Exception {
    ParsePosition parsePosition = new ParsePosition(0);
    NumberFormat format = numberFormatFactory.getNumberFormat();
    Number number = format.parse(string, parsePosition);
    if (number == null) {
        // no object could be parsed
        throw new InvalidFormatException(string, getPattern(format));
    }//w  w w.  j  av  a 2  s .  c o  m
    if (!lenient) {
        if (string.length() != parsePosition.getIndex()) {
            // indicates a part of the string that was not parsed; e.g. ".5" in 1234.5 when parsing an Integer
            throw new InvalidFormatException(string, getPattern(format));
        }
    }
    return convertToNumberClass(number, (Class<? extends Number>) targetClass);
}

From source file:org.apache.maven.plugin.jira.JiraHelper.java

/**
 * Try to get a JIRA pid from the issue management URL.
 *
 * @param log     Used to tell the user what happened
 * @param issueManagementUrl The URL to the issue management system
 * @param client  The client used to connect to JIRA
 * @return The JIRA id for the project, or null if it can't be found
 *//*from  www .  ja va 2  s. c om*/
public static String getPidFromJira(Log log, String issueManagementUrl, HttpClient client) {
    String jiraId = null;
    GetMethod gm = new GetMethod(issueManagementUrl);

    String projectPage;
    try {
        client.executeMethod(gm);
        log.debug("Successfully reached JIRA.");
        projectPage = gm.getResponseBodyAsString();
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.error("Unable to reach the JIRA project page:", e);
        } else {
            log.error("Unable to reach the JIRA project page. Cause is: " + e.getLocalizedMessage());
        }
        return null;
    }

    int pidIndex = projectPage.indexOf(PID);

    if (pidIndex == -1) {
        log.error("Unable to extract a JIRA pid from the page at the url " + issueManagementUrl);
    } else {
        NumberFormat nf = NumberFormat.getInstance();
        Number pidNumber = nf.parse(projectPage, new ParsePosition(pidIndex + PID.length()));
        jiraId = Integer.toString(pidNumber.intValue());
        log.debug("Found the pid " + jiraId + " at " + issueManagementUrl);
    }
    return jiraId;
}

From source file:org.opendatakit.briefcase.util.WebUtils.java

private static final Date parseDateSubset(String value, String[] parsePatterns, Locale l, TimeZone tz) {
    // borrowed from apache.commons.lang.DateUtils...
    Date d = null;//from   w ww  .  java 2  s  . c  o 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:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to a short primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)vv//from  ww  w  .j  a v  a  2  s  . com
 *@return the converted Short value.
 */
public static Short formatShort(String value, Locale locale) {
    Short 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() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) {
                result = new Short(num.shortValue());
            }
        }
    }

    return result;
}

From source file:com.autonomy.aci.client.util.DateTimeUtils.java

/**
 * Parses a string representing a date, using the supplied pattern and locale.
 * <p>//from w  ww. ja v a 2  s. co m
 * A parse is only deemed successful if it parses the whole of the input string. If the parse pattern didn't match, a
 * ParseException is thrown.
 * @param string The date to parse, not null
 * @param format The date format pattern to use, see {@link java.text.SimpleDateFormat}, not null
 * @param locale The locale whose date format symbols should be used
 * @return The parsed date
 * @throws IllegalArgumentException If the date <tt>string</tt> or <tt>format</tt> are null
 * @throws ParseException           If the date pattern was unsuitable
 */
public Date parseDate(final String string, final String format, final Locale locale) throws ParseException {
    LOGGER.trace("parseDate() called...");

    Validate.notEmpty(string, "Date string must not be null");
    Validate.notEmpty(format, "Date string format must not be null");

    final SimpleDateFormat parser = new SimpleDateFormat(format, locale);
    final ParsePosition pos = new ParsePosition(0);

    final Date date = parser.parse(string, pos);
    if (date != null && pos.getIndex() == string.length()) {
        return date;
    }

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

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

License:asdf

public void testInsert() throws Exception {
    Date currentDate = new Date();
    GroupAccess groupAccess = new GroupAccess(1, "fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.");
    groupAccess.setLastTokenRequest(currentDate);
    groupAccess.setLastUpdateFromServer(currentDate);
    groupAccess.setSynchronize(true);/*  w  w w  . j  av  a  2s .  c o m*/
    groupAccess.setInterrupted(false);

    assertEquals(IGroupAuthAccessDbController.INSERTION_CODE.CORRECT,
            mGroupAuthAccessDbController.insert(groupAccess));

    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor cursor = db.query(GroupAccess.TABLE_NAME, GroupAccess.COLUMN.ALL_COLUMNS,
            GroupAccess.COLUMN.GROUP_ID + " = ? ", new String[] { String.valueOf(1) }, null, null, null);
    int count = cursor.getCount();
    if (count == 0)
        cursor.close();

    assertTrue(cursor.moveToFirst());

    int groupId = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.GROUP_ID));
    boolean synchronize = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.SYNCHRONIZE)) == 1;
    boolean interrupted = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.INTERRUPTED)) == 1;
    Date lastTokenRequestDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_TOKEN_REQUEST)),
            new ParsePosition(0));
    Date lastUpdateDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER)),
            new ParsePosition(0));
    String token = cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.TOKEN));

    cursor.close();

    assertEquals(1, groupId);
    assertEquals(true, synchronize);
    assertEquals(false, interrupted);
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastTokenRequestDate));
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastUpdateDate));
    assertEquals("fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.", token);

}

From source file:graph.module.DateParseModule.java

@SuppressWarnings("deprecation")
private DAGNode parseDate(SimpleDateFormat sdf, String dateStr) {
    try {//from w  w  w .  j  a v a  2 s  .  c om
        ParsePosition position = new ParsePosition(0);
        Date date = sdf.parse(dateStr, position);
        if (position.getIndex() != dateStr.length()) {
            // Throw an exception or whatever else you want to do
            return null;
        }
        String pattern = sdf.toPattern();

        StringBuilder buffer = new StringBuilder();
        boolean addFurther = false;
        int brackets = 0;
        if (addFurther || pattern.contains("d")) {
            addFurther = true;
            buffer.append("(" + CommonConcepts.DAYFN.getID() + " '" + date.getDate() + " ");
            brackets++;
        }
        if (addFurther || pattern.contains("M")) {
            addFurther = true;
            buffer.append("(" + CommonConcepts.MONTHFN.getID() + " " + MONTH_FORMATTER.format(date) + " ");
            brackets++;
        }
        if (pattern.contains("y")) {
            buffer.append("(" + CommonConcepts.YEARFN.getID() + " '" + (date.getYear() + 1900));
            brackets++;
        } else if (addFurther)
            buffer.append(CommonConcepts.THE_YEAR.getID());
        for (int i = 0; i < brackets; i++)
            buffer.append(")");
        return (DAGNode) dag_.findOrCreateNode(buffer.toString(), null);
    } catch (Exception e) {
    }
    return null;
}

From source file:org.polymap.kaps.ui.MyNumberValidator.java

public Object transform2Model(Object fieldValue) throws Exception {
    if (fieldValue == null) {
        return null;
    } else if (fieldValue instanceof String) {
        if (((String) fieldValue).isEmpty()) {
            return null;
        }/*from   ww  w  .  j  a  v  a  2  s.com*/
        ParsePosition pp = new ParsePosition(0);
        Number result = nf.parse((String) fieldValue, pp);

        if (pp.getErrorIndex() > -1 || pp.getIndex() < ((String) fieldValue).length()) {
            throw new ParseException("field value: " + fieldValue + " for targetClass " + targetClass.getName(),
                    pp.getErrorIndex());
        }

        log.debug("value: " + fieldValue + " -> " + result.doubleValue());

        // XXX check max digits

        if (Float.class.isAssignableFrom(targetClass)) {
            return Float.valueOf(result.floatValue());
        } else if (Double.class.isAssignableFrom(targetClass)) {
            return Double.valueOf(result.doubleValue());
        } else if (Integer.class.isAssignableFrom(targetClass)) {
            return Integer.valueOf(result.intValue());
        } else if (Long.class.isAssignableFrom(targetClass)) {
            return Long.valueOf(result.longValue());
        } else {
            throw new RuntimeException("Unsupported target type: " + targetClass);
        }
    } else {
        throw new RuntimeException("Unhandled field value type: " + fieldValue);
    }
}

From source file:com.owncloud.android.services.AdvancedFileAlterationListener.java

public void onFileCreate(final File file, int delay) {
    if (file != null) {
        uploadMap.put(file.getAbsolutePath(), null);

        String mimetypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath());
        Long lastModificationTime = file.lastModified();
        final Locale currentLocale = context.getResources().getConfiguration().locale;

        if ("image/jpeg".equalsIgnoreCase(mimetypeString) || "image/tiff".equalsIgnoreCase(mimetypeString)) {
            try {
                ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
                String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
                if (!TextUtils.isEmpty(exifDate)) {
                    ParsePosition pos = new ParsePosition(0);
                    SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale);
                    sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
                    Date dateTime = sFormatter.parse(exifDate, pos);
                    lastModificationTime = dateTime.getTime();
                }//ww w  .  j  a va  2 s.c om

            } catch (IOException e) {
                Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage());
            }
        }

        final Long finalLastModificationTime = lastModificationTime;

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                PersistableBundleCompat bundle = new PersistableBundleCompat();
                bundle.putString(AutoUploadJob.LOCAL_PATH, file.getAbsolutePath());
                bundle.putString(AutoUploadJob.REMOTE_PATH,
                        FileStorageUtils.getInstantUploadFilePath(currentLocale, syncedFolder.getRemotePath(),
                                file.getName(), finalLastModificationTime, syncedFolder.getSubfolderByDate()));
                bundle.putString(AutoUploadJob.ACCOUNT, syncedFolder.getAccount());
                bundle.putInt(AutoUploadJob.UPLOAD_BEHAVIOUR, syncedFolder.getUploadAction());

                new JobRequest.Builder(AutoUploadJob.TAG).setExecutionWindow(30_000L, 80_000L)
                        .setRequiresCharging(syncedFolder.getChargingOnly())
                        .setRequiredNetworkType(syncedFolder.getWifiOnly() ? JobRequest.NetworkType.UNMETERED
                                : JobRequest.NetworkType.ANY)
                        .setExtras(bundle).setPersisted(false).setRequirementsEnforced(true)
                        .setUpdateCurrent(false).build().schedule();

                uploadMap.remove(file.getAbsolutePath());
            }
        };

        uploadMap.put(file.getAbsolutePath(), runnable);
        handler.postDelayed(runnable, delay);
    }
}