List of usage examples for java.text ParsePosition ParsePosition
public ParsePosition(int index)
From source file:com.comu.android.StreamRenderer.java
/** * Renders the post's timestamp./* ww w . j a v a 2 s.c om*/ * * @param post */ private void renderTimeStamp(JSONObject post) { String dateStr = post.optString("created_time"); SimpleDateFormat formatter = getDateFormat(); ParsePosition pos = new ParsePosition(0); long then = formatter.parse(dateStr, pos).getTime(); long now = new Date().getTime(); long seconds = (now - then) / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = hours / 24; String friendly = null; long num = 0; if (days > 0) { num = days; friendly = days + " day"; } else if (hours > 0) { num = hours; friendly = hours + " hour"; } else if (minutes > 0) { num = minutes; friendly = minutes + " minute"; } else { num = seconds; friendly = seconds + " second"; } if (num > 1) { friendly += "s"; } String[] chunks = new String[] { "<div class=\"timestamp\">", friendly, " ago", "</div>" }; append(chunks); }
From source file:org.ms123.common.form.BaseFormServiceImpl.java
protected Map cleanData(Map data, List<Map> shapes, boolean convert) { Map newMap = new HashMap(); System.out.println("FormService.cleanData.start(" + convert + "):" + data); for (Map shape : shapes) { String name = getName(shape); Class type = ConstraintsUtils.getType(shape); Object value = data.get(name); System.out.println("\tname:" + name + "/" + type + "=" + value); if (name == null || "".equals(name.trim())) continue; if (value != null && convert) { if (type == Double.class || type == Integer.class) { if (value instanceof String && "".equals(value)) { value = null;//w ww . ja v a 2 s. com } } if (type == Date.class) { try { if (value instanceof String) { value = new SimpleDateFormat( (((String) value).indexOf("T") > 0) ? "yyyy-MM-dd'T'HH:mm" : "yyyy-MM-dd") .parse((String) value, new ParsePosition(0)); } else { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(((Long) value)); value = cal.getTime(); } } catch (Exception e) { System.out.println("DateException:" + name + "=" + value + ":" + e.getMessage()); value = null; } } } if (value != null && !convert) {//@@@MS Hack Iso-Date -> long if (type == Date.class) { try { if (value instanceof String) { Date d = new SimpleDateFormat( (((String) value).indexOf("T") > 0) ? "yyyy-MM-dd'T'HH:mm" : "yyyy-MM-dd") .parse((String) value, new ParsePosition(0)); value = d.getTime(); } } catch (Exception e) { System.out.println("DateException,iso:" + name + "=" + value + ":" + e.getMessage()); value = null; } } } newMap.put(name, value); } System.out.println("FormService.cleanData.end:" + newMap); return newMap; }
From source file:easyJ.common.validate.GenericTypeValidator.java
/** * Checks if the value can safely be converted to a double primitive. * //from w w w . ja v a2s .co 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 Double value. */ public static Double formatDouble(String value, Locale locale) { Double result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getInstance(locale); } else { formatter = NumberFormat.getInstance(Locale.getDefault()); } 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() >= (Double.MAX_VALUE * -1) && num.doubleValue() <= Double.MAX_VALUE) { result = new Double(num.doubleValue()); } } } return result; }
From source file:org.sqlite.date.FastDateParser.java
public Date parse(final String source) throws ParseException { final Date date = parse(source, new ParsePosition(0)); if (date == null) { // Add a note re supported date range if (locale.equals(JAPANESE_IMPERIAL)) { throw new ParseException( "(The " + locale + " locale does not support dates before 1868 AD)\n" + "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0);//from w w w . j a v a 2 s.c om } throw new ParseException( "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0); } return date; }
From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.csv.CSVFileReader.java
public int readFile(BufferedReader csvReader, DataTable dataTable, PrintWriter finalOut) throws IOException { List<DataVariable> variableList = new ArrayList<>(); CSVParser parser = new CSVParser(csvReader, inFormat.withHeader()); Map<String, Integer> headers = parser.getHeaderMap(); int i = 0;// w w w . j a v a2 s . c o m for (String varName : headers.keySet()) { if (varName == null || varName.isEmpty()) { // TODO: // Add a sensible variable name validation algorithm. // -- L.A. 4.0 alpha 1 throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.invalidHeader")); } DataVariable dv = new DataVariable(); dv.setName(varName); dv.setLabel(varName); dv.setInvalidRanges(new ArrayList<>()); dv.setSummaryStatistics(new ArrayList<>()); dv.setUnf("UNF:6:NOTCALCULATED"); dv.setCategories(new ArrayList<>()); variableList.add(dv); dv.setTypeCharacter(); dv.setIntervalDiscrete(); dv.setFileOrder(i); dv.setDataTable(dataTable); i++; } dataTable.setVarQuantity((long) variableList.size()); dataTable.setDataVariables(variableList); boolean[] isNumericVariable = new boolean[headers.size()]; boolean[] isIntegerVariable = new boolean[headers.size()]; boolean[] isTimeVariable = new boolean[headers.size()]; boolean[] isDateVariable = new boolean[headers.size()]; for (i = 0; i < headers.size(); i++) { // OK, let's assume that every variable is numeric; // but we'll go through the file and examine every value; the // moment we find a value that's not a legit numeric one, we'll // assume that it is in fact a String. isNumericVariable[i] = true; isIntegerVariable[i] = true; isDateVariable[i] = true; isTimeVariable[i] = true; } // First, "learning" pass. // (we'll save the incoming stream in another temp file:) SimpleDateFormat[] selectedDateTimeFormat = new SimpleDateFormat[headers.size()]; SimpleDateFormat[] selectedDateFormat = new SimpleDateFormat[headers.size()]; File firstPassTempFile = File.createTempFile("firstpass-", ".csv"); try (CSVPrinter csvFilePrinter = new CSVPrinter( // TODO allow other parsers of tabular data to use this parser by changin inFormat new FileWriter(firstPassTempFile.getAbsolutePath()), inFormat)) { //Write headers csvFilePrinter.printRecord(headers.keySet()); for (CSVRecord record : parser.getRecords()) { // Checks if #records = #columns in header if (!record.isConsistent()) { List<String> args = Arrays.asList(new String[] { "" + (parser.getCurrentLineNumber() - 1), "" + headers.size(), "" + record.size() }); throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.recordMismatch", args)); } for (i = 0; i < headers.size(); i++) { String varString = record.get(i); isIntegerVariable[i] = isIntegerVariable[i] && varString != null && (varString.isEmpty() || varString.equals("null") || (firstNumCharSet.contains(varString.charAt(0)) && StringUtils.isNumeric(varString.substring(1)))); if (isNumericVariable[i]) { // If variable might be "numeric" test to see if this value is a parsable number: if (varString != null && !varString.isEmpty()) { boolean isNumeric = false; boolean isInteger = false; if (varString.equalsIgnoreCase("NaN") || varString.equalsIgnoreCase("NA") || varString.equalsIgnoreCase("Inf") || varString.equalsIgnoreCase("+Inf") || varString.equalsIgnoreCase("-Inf") || varString.equalsIgnoreCase("null")) { continue; } else { try { Double testDoubleValue = new Double(varString); continue; } catch (NumberFormatException ex) { // the token failed to parse as a double // so the column is a string variable. } } isNumericVariable[i] = false; } } // If this is not a numeric column, see if it is a date collumn // by parsing the cell as a date or date-time value: if (!isNumericVariable[i]) { Date dateResult = null; if (isTimeVariable[i]) { if (varString != null && !varString.isEmpty()) { boolean isTime = false; if (selectedDateTimeFormat[i] != null) { ParsePosition pos = new ParsePosition(0); dateResult = selectedDateTimeFormat[i].parse(varString, pos); if (dateResult != null && pos.getIndex() == varString.length()) { // OK, successfully parsed a value! isTime = true; } } else { for (SimpleDateFormat format : TIME_FORMATS) { ParsePosition pos = new ParsePosition(0); dateResult = format.parse(varString, pos); if (dateResult != null && pos.getIndex() == varString.length()) { // OK, successfully parsed a value! isTime = true; selectedDateTimeFormat[i] = format; break; } } } if (!isTime) { isTimeVariable[i] = false; // if the token didn't parse as a time value, // we will still try to parse it as a date, below. // unless this column is NOT a date. } else { // And if it is a time value, we are going to assume it's // NOT a date. isDateVariable[i] = false; } } } if (isDateVariable[i]) { if (varString != null && !varString.isEmpty()) { boolean isDate = false; // TODO: // Strictly speaking, we should be doing the same thing // here as with the time formats above; select the // first one that works, then insist that all the // other values in this column match it... but we // only have one, as of now, so it should be ok. // -- L.A. 4.0 beta for (SimpleDateFormat format : DATE_FORMATS) { // Strict parsing - it will throw an // exception if it doesn't parse! format.setLenient(false); try { format.parse(varString); isDate = true; selectedDateFormat[i] = format; break; } catch (ParseException ex) { //Do nothing } } isDateVariable[i] = isDate; } } } } csvFilePrinter.printRecord(record); } } dataTable.setCaseQuantity(parser.getRecordNumber()); parser.close(); csvReader.close(); // Re-type the variables that we've determined are numerics: for (i = 0; i < headers.size(); i++) { if (isNumericVariable[i]) { dataTable.getDataVariables().get(i).setTypeNumeric(); if (isIntegerVariable[i]) { dataTable.getDataVariables().get(i).setIntervalDiscrete(); } else { dataTable.getDataVariables().get(i).setIntervalContinuous(); } } else if (isDateVariable[i] && selectedDateFormat[i] != null) { // Dates are still Strings, i.e., they are "character" and "discrete"; // But we add special format values for them: dataTable.getDataVariables().get(i).setFormat(DATE_FORMATS[0].toPattern()); dataTable.getDataVariables().get(i).setFormatCategory("date"); } else if (isTimeVariable[i] && selectedDateTimeFormat[i] != null) { // Same for time values: dataTable.getDataVariables().get(i).setFormat(selectedDateTimeFormat[i].toPattern()); dataTable.getDataVariables().get(i).setFormatCategory("time"); } } // Second, final pass. try (BufferedReader secondPassReader = new BufferedReader(new FileReader(firstPassTempFile))) { parser = new CSVParser(secondPassReader, inFormat.withHeader()); String[] caseRow = new String[headers.size()]; for (CSVRecord record : parser) { if (!record.isConsistent()) { List<String> args = Arrays.asList(new String[] { "" + (parser.getCurrentLineNumber() - 1), "" + headers.size(), "" + record.size() }); throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.recordMismatch", args)); } for (i = 0; i < headers.size(); i++) { String varString = record.get(i); if (isNumericVariable[i]) { if (varString == null || varString.isEmpty() || varString.equalsIgnoreCase("NA")) { // Missing value - represented as an empty string in // the final tab file caseRow[i] = ""; } else if (varString.equalsIgnoreCase("NaN")) { // "Not a Number" special value: caseRow[i] = "NaN"; } else if (varString.equalsIgnoreCase("Inf") || varString.equalsIgnoreCase("+Inf")) { // Positive infinity: caseRow[i] = "Inf"; } else if (varString.equalsIgnoreCase("-Inf")) { // Negative infinity: caseRow[i] = "-Inf"; } else if (varString.equalsIgnoreCase("null")) { // By request from Gus - "NULL" is recognized as a // numeric zero: caseRow[i] = isIntegerVariable[i] ? "0" : "0.0"; } else { /* No re-formatting is done on any other numeric values. * We'll save them as they were, for archival purposes. * The alternative solution - formatting in sci. notation * is commented-out below. */ caseRow[i] = varString; /* if (isIntegerVariable[i]) { try { Integer testIntegerValue = new Integer(varString); caseRow[i] = testIntegerValue.toString(); } catch (NumberFormatException ex) { throw new IOException("Failed to parse a value recognized as an integer in the first pass! (?)"); } } else { try { Double testDoubleValue = new Double(varString); if (testDoubleValue.equals(0.0)) { caseRow[i] = "0.0"; } else { // One possible implementation: // // Round our fractional values to 15 digits // (minimum number of digits of precision guaranteed by // type Double) and format the resulting representations // in a IEEE 754-like "scientific notation" - for ex., // 753.24 will be encoded as 7.5324e2 BigDecimal testBigDecimal = new BigDecimal(varString, doubleMathContext); caseRow[i] = String.format(FORMAT_IEEE754, testBigDecimal); // Strip meaningless zeros and extra + signs: caseRow[i] = caseRow[i].replaceFirst("00*e", "e"); caseRow[i] = caseRow[i].replaceFirst("\\.e", ".0e"); caseRow[i] = caseRow[i].replaceFirst("e\\+00", ""); caseRow[i] = caseRow[i].replaceFirst("^\\+", ""); } } catch (NumberFormatException ex) { throw new IOException("Failed to parse a value recognized as numeric in the first pass! (?)"); } } */ } } else if (isTimeVariable[i] || isDateVariable[i]) { // Time and Dates are stored NOT quoted (don't ask). if (varString != null) { // Dealing with quotes: // remove the leading and trailing quotes, if present: varString = varString.replaceFirst("^\"*", ""); varString = varString.replaceFirst("\"*$", ""); caseRow[i] = varString; } else { caseRow[i] = ""; } } else { // Treat as a String: // Strings are stored in tab files quoted; // Missing values are stored as an empty string // between two tabs (or one tab and the new line); // Empty strings stored as "" (quoted empty string). // For the purposes of this CSV ingest reader, we are going // to assume that all the empty strings in the file are // indeed empty strings, and NOT missing values: if (varString != null) { // escape the quotes, newlines, and tabs: varString = varString.replace("\"", "\\\""); varString = varString.replace("\n", "\\n"); varString = varString.replace("\t", "\\t"); // final pair of quotes: varString = "\"" + varString + "\""; caseRow[i] = varString; } else { caseRow[i] = "\"\""; } } } finalOut.println(StringUtils.join(caseRow, "\t")); } } long linecount = parser.getRecordNumber(); finalOut.close(); parser.close(); dbglog.fine("Tmp File: " + firstPassTempFile); // Firstpass file is deleted to prevent tmp from filling up. firstPassTempFile.delete(); if (dataTable.getCaseQuantity().intValue() != linecount) { List<String> args = Arrays .asList(new String[] { "" + dataTable.getCaseQuantity().intValue(), "" + linecount }); throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.line_mismatch", args)); } return (int) linecount; }
From source file:routines.system.BigDataParserUtils.java
public synchronized static java.util.Date parseTo_Date(String s, String pattern, boolean lenient) { if (isBlank(s)) { return null; }//from w ww.j a va 2 s . co m String s2 = s.trim(); String pattern2 = pattern; if (isBlank(pattern2)) { pattern2 = Constant.dateDefaultPattern; } java.util.Date date = null; if (pattern2.equals("yyyy-MM-dd'T'HH:mm:ss'000Z'")) { if (!s2.endsWith("000Z")) { throw new RuntimeException("Unparseable date: \"" + s2 + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } pattern2 = "yyyy-MM-dd'T'HH:mm:ss"; s2 = s2.substring(0, s.lastIndexOf("000Z")); } DateFormat format = FastDateParser.getInstance(pattern2, lenient); ParsePosition pp = new ParsePosition(0); pp.setIndex(0); format.setTimeZone(TimeZone.getTimeZone("UTC")); date = format.parse(s2, pp); if (pp.getIndex() != s2.length() || date == null) { throw new RuntimeException("Unparseable date: \"" + s2 + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } return date; }
From source file:org.alfresco.util.CachingDateFormat.java
public static Pair<Date, Integer> lenientParse(String text, int minimumResolution) throws ParseException { DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); try {// ww w . ja va2s. co m Date parsed = fmt.parseDateTime(text).toDate(); return new Pair<Date, Integer>(parsed, Calendar.MILLISECOND); } catch (IllegalArgumentException e) { } SimpleDateFormatAndResolution[] formatters = getLenientFormatters(); for (SimpleDateFormatAndResolution formatter : formatters) { if (formatter.resolution >= minimumResolution) { ParsePosition pp = new ParsePosition(0); Date parsed = formatter.simpleDateFormat.parse(text, pp); if ((pp.getIndex() < text.length()) || (parsed == null)) { continue; } return new Pair<Date, Integer>(parsed, formatter.resolution); } } throw new ParseException("Unknown date format", 0); }
From source file:org.catechis.Domartin.java
/** *Get milliseconds from a long format date like this: EEE MMM dd HH:mm:ss zzz yyyy. *///from w w w . j a v a 2 s .c om public static long getMilliseconds(String str_date) { SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); Date date = null; ParsePosition pp = new ParsePosition(0); long time = 0; try { date = sdf.parse(str_date, pp); time = date.getTime(); } catch (java.lang.NullPointerException npe) { } return time; }
From source file:org.sakaiproject.unboundid.SimpleLdapAttributeMapper.java
/** * A delegate of {@link #mapLdapAttributeOntoUserData(LDAPAttribute, LdapUserData, Collection)} * that allows for discrete handling of each logical attribute name associated with * the given {@link LDAPAttribute}//from w w w .ja v a2 s. c om * * @param attribute * @param userData * @param logicalAttrName */ protected void mapLdapAttributeOntoUserData(LDAPAttribute attribute, LdapUserData userData, String logicalAttrName) { Attribute unboundidAttribute = attribute.toAttribute(); String attrValue = unboundidAttribute.getValue(); MessageFormat format = valueMappings.get(logicalAttrName); if (format != null && attrValue != null) { format = (MessageFormat) format.clone(); log.debug("mapLdapAttributeOntoUserData(): value mapper [attrValue = {}; format={}]", attrValue, format.toString()); attrValue = (String) (format.parse(attrValue, new ParsePosition(0))[0]); } log.debug( "mapLdapAttributeOntoUserData() preparing to map: [logical attr name = {}][physical attr name = {}][value = {}]", logicalAttrName, attribute.getName(), attrValue); if (logicalAttrName.equals(AttributeMappingConstants.LOGIN_ATTR_MAPPING_KEY)) { log.debug( "mapLdapAttributeOntoUserData() mapping attribute to User.eid: [logical attr name = {}][physical attr name = {}][value = {}]", logicalAttrName, attribute.getName(), attrValue); userData.setEid(attrValue); } else if (logicalAttrName.equals(AttributeMappingConstants.FIRST_NAME_ATTR_MAPPING_KEY)) { log.debug( "mapLdapAttributeOntoUserData() mapping attribute to User.firstName: [logical attr name = {}][physical attr name = [}][value = {}]", logicalAttrName, attribute.getName(), attrValue); userData.setFirstName(attrValue); } else if (logicalAttrName.equals(AttributeMappingConstants.PREFERRED_FIRST_NAME_ATTR_MAPPING_KEY)) { log.debug( "mapLdapAttributeOntoUserData() mapping attribute to User.firstNamePreferred: logical attr name = {}][physical attr name = {}][value = {}]", logicalAttrName, attribute.getName(), attrValue); userData.setPreferredFirstName(attrValue); } else if (logicalAttrName.equals(AttributeMappingConstants.LAST_NAME_ATTR_MAPPING_KEY)) { log.debug( "mapLdapAttributeOntoUserData() mapping attribute to User.lastName: [logical attr name = {}][physical attr name = {}][value = {}]", logicalAttrName, attribute.getName(), attrValue); userData.setLastName(attrValue); } else if (logicalAttrName.equals(AttributeMappingConstants.EMAIL_ATTR_MAPPING_KEY)) { log.debug( "mapLdapAttributeOntoUserData() mapping attribute to User.email: [logical attr name = {}][physical attr name = {}][value = {}]", logicalAttrName, attribute.getName(), attrValue); userData.setEmail(attrValue); } else if (logicalAttrName.equals(AttributeMappingConstants.DISPLAY_ID_ATTR_MAPPING_KEY)) { log.debug( "mapLdapAttributeOntoUserData() mapping attribute to User display Id: logical attr name = {}][physical attr name = {}][value = {}]", logicalAttrName, attribute.getName(), attrValue); userData.setProperty(UnboundidDirectoryProvider.DISPLAY_ID_PROPERTY, attrValue); } else if (logicalAttrName.equals(AttributeMappingConstants.DISPLAY_NAME_ATTR_MAPPING_KEY)) { log.debug( "mapLdapAttributeOntoUserData() mapping attribute to User display name: [logical attr name = {}][physical attr name = {}][value = {}]", logicalAttrName, attribute.getName(), attrValue); userData.setProperty(UnboundidDirectoryProvider.DISPLAY_NAME_PROPERTY, attrValue); } else { log.debug( "mapLdapAttributeOntoUserData() mapping attribute to a User property: [logical attr name (and property name) = {}][physical attr name = {}][value = {}]", logicalAttrName, attribute.getName(), attrValue); userData.setProperty(logicalAttrName, attrValue); } }