Example usage for java.text ParsePosition getIndex

List of usage examples for java.text ParsePosition getIndex

Introduction

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

Prototype

public int getIndex() 

Source Link

Document

Retrieve the current parse position.

Usage

From source file:net.sf.jabref.model.entry.BibEntry.java

/**
 * Returns the contents of the given field, its alias or null if both are
 * not set./*from w ww.  j a  v  a 2  s. c o m*/
 * <p>
 * The following aliases are considered (old bibtex <-> new biblatex) based
 * on the BibLatex documentation, chapter 2.2.5:
 * address      <-> location
 * annote           <-> annotation
 * archiveprefix    <-> eprinttype
 * journal      <-> journaltitle
 * key              <-> sortkey
 * pdf          <-> file
 * primaryclass     <-> eprintclass
 * school           <-> institution
 * These work bidirectional.
 * <p>
 * Special attention is paid to dates: (see the BibLatex documentation,
 * chapter 2.3.8)
 * The fields 'year' and 'month' are used if the 'date'
 * field is empty. Conversely, getFieldOrAlias("year") also tries to
 * extract the year from the 'date' field (analogously for 'month').
 */
public Optional<String> getFieldOrAlias(String name) {
    Optional<String> fieldValue = getFieldOptional(toLowerCase(name));

    if (fieldValue.isPresent() && !fieldValue.get().isEmpty()) {
        return fieldValue;
    }

    // No value of this field found, so look at the alias
    String aliasForField = EntryConverter.FIELD_ALIASES.get(name);

    if (aliasForField != null) {
        return getFieldOptional(aliasForField);
    }

    // Finally, handle dates
    if (FieldName.DATE.equals(name)) {
        Optional<String> year = getFieldOptional(FieldName.YEAR);
        if (year.isPresent()) {
            MonthUtil.Month month = MonthUtil.getMonth(getFieldOptional(FieldName.MONTH).orElse(""));
            if (month.isValid()) {
                return Optional.of(year.get() + '-' + month.twoDigitNumber);
            } else {
                return year;
            }
        }
    }
    if (FieldName.YEAR.equals(name) || FieldName.MONTH.equals(name)) {
        Optional<String> date = getFieldOptional(FieldName.DATE);
        if (!date.isPresent()) {
            return Optional.empty();
        }

        // Create date format matching dates with year and month
        DateFormat df = new DateFormat() {

            static final String FORMAT1 = "yyyy-MM-dd";
            static final String FORMAT2 = "yyyy-MM";
            final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1);
            final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2);

            @Override
            public StringBuffer format(Date dDate, StringBuffer toAppendTo, FieldPosition fieldPosition) {
                throw new UnsupportedOperationException();
            }

            @Override
            public Date parse(String source, ParsePosition pos) {
                if ((source.length() - pos.getIndex()) == FORMAT1.length()) {
                    return sdf1.parse(source, pos);
                }
                return sdf2.parse(source, pos);
            }
        };

        try {
            Date parsedDate = df.parse(date.get());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parsedDate);
            if (FieldName.YEAR.equals(name)) {
                return Optional.of(Integer.toString(calendar.get(Calendar.YEAR)));
            }
            if (FieldName.MONTH.equals(name)) {
                return Optional.of(Integer.toString(calendar.get(Calendar.MONTH) + 1)); // Shift by 1 since in this calendar Jan = 0
            }
        } catch (ParseException e) {
            // So not a date with year and month, try just to parse years
            df = new SimpleDateFormat("yyyy");

            try {
                Date parsedDate = df.parse(date.get());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(parsedDate);
                if (FieldName.YEAR.equals(name)) {
                    return Optional.of(Integer.toString(calendar.get(Calendar.YEAR)));
                }
            } catch (ParseException e2) {
                LOGGER.warn("Could not parse entry " + name, e2);
                return Optional.empty(); // Date field not in valid format
            }
        }
    }
    return Optional.empty();
}

From source file:javadz.beanutils.converters.DateTimeConverter.java

/**
 * Parse a String into a <code>Calendar</code> object
 * using the specified <code>DateFormat</code>.
 *
 * @param sourceType The type of the value being converted
 * @param targetType The type to convert the value to
 * @param value The String date value.//from w w w .j  ava  2s.c  o m
 * @param format The DateFormat to parse the String value.
 *
 * @return The converted Calendar object.
 * @throws ConversionException if the String cannot be converted.
 */
private Calendar parse(Class sourceType, Class targetType, String value, DateFormat format) {
    logFormat("Parsing", format);
    format.setLenient(false);
    ParsePosition pos = new ParsePosition(0);
    Date parsedDate = format.parse(value, pos); // ignore the result (use the Calendar)
    if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedDate == null) {
        String msg = "Error converting '" + toString(sourceType) + "' to '" + toString(targetType) + "'";
        if (format instanceof SimpleDateFormat) {
            msg += " using pattern '" + ((SimpleDateFormat) format).toPattern() + "'";
        }
        if (log().isDebugEnabled()) {
            log().debug("    " + msg);
        }
        throw new ConversionException(msg);
    }
    Calendar calendar = format.getCalendar();
    return calendar;
}

From source file:HexFormat.java

/**
 * Parse a hex number into a Number object. Hexadecimal numbers may be
 * indicated with a leading character designation of '0x'. If up to 1 byte
 * is parsed, returns a Byte. If more than 1 and up to 2 bytes are parsed,
 * return a Short. If more than 2 and up to 4 bytes are parsed, return an
 * Integer. If more than 4 and up to 8 bytes are parsed, return a Long.
 * // w  ww.  j a  v  a2  s .c  o  m
 * @param source
 *            a binary number
 * @return return an integer form of Number object if parse is successful
 * @exception ParseException
 *                thrown if source is cannot be converted to a Byte, Short,
 *                Int, or Long.
 * 
 * @since 1.0
 */
public Number parse(String source) throws ParseException {
    int startIndex = 0;
    Number result;

    ParsePosition parsePosition = new ParsePosition(startIndex);
    result = parse(source, parsePosition);

    if (result == null) {
        throw new ParseException("Unable to parse " + source + " using HexFormat", parsePosition.getIndex());
    }

    return (result);
}

From source file:HexFormat.java

/**
 * Parse a hex number into a Number object. Hexadecimal numbers may be
 * indicated with a leading character designation of '0x'. If up to 1 byte
 * is parsed, returns a Byte. If more than 1 and up to 2 bytes are parsed,
 * return a Short. If more than 2 and up to 4 bytes are parsed, return an
 * Integer. If more than 4 and up to 8 bytes are parsed, return a Long.
 * /*  w w w  .  j  a  v a 2 s.c  o m*/
 * @param text
 *            a hexadecimal number
 * @param parsePosition
 *            position to start parsing from
 * @return return an integer form of Number object if parse is successful;
 *         <CODE>null</CODE> otherwise
 * 
 * @since 1.0
 */
public Number parse(String text, ParsePosition parsePosition) {
    boolean skipWhitespace = true;
    int startIndex, nibbles;

    // remove whitespace
    StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex());
    for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) {
        if (skipWhitespace && Character.isWhitespace(c)) {
            // skip whitespace
            continue;
        }
        break;
    }

    // skip a leading hex designation of the characters '0x'
    if (text.regionMatches(iter.getIndex(), "0x", 0, 2)) {
        parsePosition.setIndex(iter.getIndex() + 2);
    } else {
        parsePosition.setIndex(iter.getIndex());
    }

    startIndex = parsePosition.getIndex();
    Number result = (Number) parseObject(text, parsePosition);

    if (result == null) {
        return (result);
    }

    nibbles = parsePosition.getIndex() - startIndex;
    if (nibbles <= 2) {
        result = new Byte(result.byteValue());
    } else if (nibbles <= 4) {
        result = new Short(result.shortValue());
    } else if (nibbles <= 8) {
        result = new Integer(result.intValue());
    } else if (nibbles <= 16) {
        result = new Long(result.longValue());
    }
    return (result);
}

From source file:org.kuali.rice.core.impl.datetime.DateTimeServiceImpl.java

protected Date parse(String dateString, String pattern) throws ParseException {
    if (!StringUtils.isBlank(dateString)) {
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        dateFormat.setLenient(false);/*  ww w .jav a  2  s  .c o  m*/
        ParsePosition parsePosition = new ParsePosition(0);
        Date testDate = dateFormat.parse(dateString, parsePosition);

        // Ensure that the entire date String can be parsed by the current format.
        if (testDate == null) {
            throw new ParseException("The date that you provided is invalid.", parsePosition.getErrorIndex());
        } else if (parsePosition.getIndex() != dateString.length()) {
            throw new ParseException("The date that you provided is invalid.", parsePosition.getIndex());
        }

        // Ensure that the date's year lies between 1000 and 9999, to help prevent database-related date errors.
        Calendar testCalendar = Calendar.getInstance();
        testCalendar.setLenient(false);
        testCalendar.setTime(testDate);
        if (testCalendar.get(Calendar.YEAR) < 1000 || testCalendar.get(Calendar.YEAR) > 9999) {
            throw new ParseException("The date that you provided is not between the years 1000 and 9999.", -1);
        }

        if (testCalendar.get(Calendar.YEAR) == 1970 && !pattern.contains("y".toLowerCase())) {
            Calendar curCalendar = Calendar.getInstance();
            curCalendar.setTime(new java.util.Date());
            testCalendar.set(Calendar.YEAR, curCalendar.get(Calendar.YEAR));
            testDate = testCalendar.getTime();
        }

        return testDate;
    }
    return null;
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private Object doConvertToNumber(Map<String, Object> context, Object value, Class toType) {
    if (value instanceof String) {
        if (toType == BigDecimal.class) {
            return new BigDecimal((String) value);
        } else if (toType == BigInteger.class) {
            return new BigInteger((String) value);
        } else if (toType.isPrimitive()) {
            Object convertedValue = super.convertValue(context, value, toType);
            String stringValue = (String) value;
            if (!isInRange((Number) convertedValue, stringValue, toType))
                throw new XWorkException("Overflow or underflow casting: \"" + stringValue + "\" into class "
                        + convertedValue.getClass().getName());

            return convertedValue;
        } else {/*from   www  .jav a  2  s  .  c  o m*/
            String stringValue = (String) value;
            if (!toType.isPrimitive() && (stringValue == null || stringValue.length() == 0)) {
                return null;
            }
            NumberFormat numFormat = NumberFormat.getInstance(getLocale(context));
            ParsePosition parsePos = new ParsePosition(0);
            if (isIntegerType(toType)) {
                numFormat.setParseIntegerOnly(true);
            }
            numFormat.setGroupingUsed(true);
            Number number = numFormat.parse(stringValue, parsePos);

            if (parsePos.getIndex() != stringValue.length()) {
                throw new XWorkException(
                        "Unparseable number: \"" + stringValue + "\" at position " + parsePos.getIndex());
            } else {
                if (!isInRange(number, stringValue, toType))
                    throw new XWorkException("Overflow or underflow casting: \"" + stringValue
                            + "\" into class " + number.getClass().getName());

                value = super.convertValue(context, number, toType);
            }
        }
    } else if (value instanceof Object[]) {
        Object[] objArray = (Object[]) value;

        if (objArray.length == 1) {
            return doConvertToNumber(context, objArray[0], toType);
        }
    }

    // pass it through DefaultTypeConverter
    return super.convertValue(context, value, toType);
}

From source file:com.application.utils.FastDateParser.java

@Override
public Date parse(final String source, final ParsePosition pos) {
    final int offset = pos.getIndex();
    final Matcher matcher = parsePattern.matcher(source.substring(offset));
    if (!matcher.lookingAt()) {
        return null;
    }/*  w w  w.j a v a2  s  .c om*/
    // timing tests indicate getting new instance is 19% faster than cloning
    final Calendar cal = Calendar.getInstance(timeZone, locale);
    cal.clear();

    for (int i = 0; i < strategies.length;) {
        final Strategy strategy = strategies[i++];
        strategy.setCalendar(this, cal, matcher.group(i));
    }
    pos.setIndex(offset + matcher.end());
    return cal.getTime();
}

From source file:py.una.pol.karaku.util.FormatProvider.java

/**
 * Formatea una fecha con el formato dado
 * //w w w  .j a  va2 s.  co m
 * @param string
 *            cadena a formatear
 * @param format
 *            formato deseado
 * @return {@link Date} con los demas parmetros a cero.
 * @throws ParseException
 *             si el formato no es adecuado.
 */
protected synchronized Date stringToDate(String string, String format) throws ParseException {

    if (string == null || EMPTY_STRING.equals(string)) {
        return null;
    }
    SimpleDateFormat sdf = this.getFormat(format);
    ParsePosition psp = new ParsePosition(0);
    if (string.length() != format.length()) {
        this.throwException(string, format);
    }
    Date toRet = sdf.parse(string, psp);
    if (psp.getIndex() != string.length()) {
        this.throwException(string, format);
    }
    return toRet;
}

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  va2 s .  com
    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:org.sqlite.date.FastDateParser.java

/**
 * This implementation updates the ParsePosition if the parse succeeeds.
 * However, unlike the method {@link java.text.SimpleDateFormat#parse(String, ParsePosition)}
 * it is not able to set the error Index - i.e. {@link ParsePosition#getErrorIndex()} -  if the parse fails.
 * <p>/*w ww  .  j  av a2s.  co m*/
 * To determine if the parse has succeeded, the caller must check if the current parse position
 * given by {@link ParsePosition#getIndex()} has been updated. If the input buffer has been fully
 * parsed, then the index will point to just after the end of the input buffer.
 *
 * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition)
 * {@inheritDoc}
 */
public Date parse(final String source, final ParsePosition pos) {
    final int offset = pos.getIndex();
    final Matcher matcher = parsePattern.matcher(source.substring(offset));
    if (!matcher.lookingAt()) {
        return null;
    }
    // timing tests indicate getting new instance is 19% faster than cloning
    final Calendar cal = Calendar.getInstance(timeZone, locale);
    cal.clear();

    for (int i = 0; i < strategies.length;) {
        final Strategy strategy = strategies[i++];
        strategy.setCalendar(this, cal, matcher.group(i));
    }
    pos.setIndex(offset + matcher.end());
    return cal.getTime();
}