Android Open Source - storm-gen Csv Utils






From Project

Back to project page storm-gen.

License

The source code is released under:

Apache License

If you think the Android project storm-gen listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*******************************************************************************
 * Copyright 2012 Google, Inc.//  ww w .  j  a v  a 2  s. c  o m
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package com.turbomanage.storm.csv;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * CSV utility methods. Does not implement the full CSV spec.
 * Values containing quotes or commas are enclosed in quotes
 * and quotes are escaped as double quotes.
 *
 * @author David M. Chandler
 */
public class CsvUtils {

  public static final char DELIMITER = ',';
  public static final char QUOTE = '"';
  public static final char CR = '\r';
  public static final char LF = '\n';
  public static final char[] CSV_SEARCH_CHARS = new char[] { DELIMITER,
      QUOTE, CR, LF };
  public static final String QUOTE_STR = String.valueOf(QUOTE);

  /**
   * Returns a {@link String} for a CSV column enclosed in double
   * quotes, if required.
   *
   * see <a
   * href="http://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a>
   * and <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.
   *
   * @param str the input String, may be null
   * @return the input String enclosed in double quotes if required, or null
   */
  public static String escapeCsv(String str) {
    if (str == null)
      return "";
    if (containsNone(str, CSV_SEARCH_CHARS))
      return str;
    StringWriter out = new StringWriter();
    out.write(QUOTE);
    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);
      if (c == QUOTE)
        out.write(QUOTE);
      out.write(c);
    }
    out.write(QUOTE);
    return out.toString();
  }

  /**
   * Removes enclosing quotes and unescapes double quotes
   *
   * @param str An escaped CSV value
   * @return the original value
   */
  public static String unescapeCsv(String str) {
    if (str == null)
      return null;
    if (!(str.charAt(0) == QUOTE && str.charAt(str.length() - 1) == QUOTE))
      return str;
    String quoteless = str.substring(1, str.length() - 1);
    return quoteless.replace(QUOTE_STR + QUOTE_STR, QUOTE_STR);
  }

  private static boolean containsNone(String str, char[] csvSearchChars) {
    if (str == null)
      return true;
    for (int i = 0; i < str.length(); i++)
      for (int j = 0; j < csvSearchChars.length; j++)
        if (str.charAt(i) == csvSearchChars[j])
          return false;
    return true;
  }

  /**
   * Returns values from a CSV String.
   *
   * @param csvRow
   * @return
   */
  public static List<String> getValues(String csvRow) {
    List<String> values = new ArrayList<String>();
    StringReader in = new StringReader(csvRow);
    String value;
    try {
      value = nextValue(in);
      while (true) {
        values.add(value);
        value = nextValue(in);
      }
    } catch (IOException e) {
      // TODO handle case of final null value better?
      if (csvRow.lastIndexOf(',') == csvRow.length() - 1)
        values.add(null);
      return values;
    }
  }

  /**
   * Obtains the next value from a {@link StringReader}.
   *
   * @param in
   * @return An escaped value
   * @throws IOException
   */
  public static String nextValue(StringReader in) throws IOException {
    StringWriter w = new StringWriter();
    boolean inQuotedValue = false;
    boolean openQuote = false;
    int c = in.read();
    if (c == QUOTE)
      inQuotedValue = true;
    else if (c == DELIMITER) {
      return null;
    } else if (c >= 0) {
      w.write(c);
    } else {
      throw new IOException("End of line reached");
    }
    c = in.read();
    while (c >= 0) {
      if (c == QUOTE) {
        if (inQuotedValue) {
          if (openQuote) {
            openQuote = false;
            w.write(QUOTE);
          } else {
            openQuote = true;
          }
        } else
          // invalid
          return w.toString();
      } else if (c == DELIMITER) {
        if (openQuote)
          return w.toString();
        else if (inQuotedValue)
          w.write(c);
        else
          // invalid
          return w.toString();
      } else
        w.write(c);
      c = in.read();
    }
    return w.toString();
  }

  /**
   * Parses a CSV row containing name=value pairs.
   *
   * @param csvPairs
   * @return Map<name,value>
   */
  public static Map<String,String> getAsMap(String csvPairs) {
    Map<String,String> map = new HashMap<String,String>();
    String[] pairs = csvPairs.split(",");
    for (String pair : pairs) {
      String[] split = pair.split("=");
      map.put(split[0], split[1]);
    }
    return map;
  }

  /**
   * Returns a String containing a comma-separated list
   * of name=value pairs from a map.
   *
   * @param map
   * @return String csv
   */
  public static String mapToCsv(Map<String,String> map) {
    StringBuilder sb = new StringBuilder();
    for (String key : map.keySet()) {
      sb.append(",");
      String val = map.get(key);
      sb.append(key + "=" + val);
    }
    return sb.toString().substring(1);
  }

}




Java Source Code List

com.turbomanage.storm.DatabaseHelper.java
com.turbomanage.storm.ModelBase.java
com.turbomanage.storm.SQLiteDao.java
com.turbomanage.storm.TableHelper.java
com.turbomanage.storm.api.Converter.java
com.turbomanage.storm.api.DatabaseFactory.java
com.turbomanage.storm.api.Database.java
com.turbomanage.storm.api.Entity.java
com.turbomanage.storm.api.Id.java
com.turbomanage.storm.api.Syncable.java
com.turbomanage.storm.api.package-info.java
com.turbomanage.storm.apt.BaseDaoModel.java
com.turbomanage.storm.apt.ClassModel.java
com.turbomanage.storm.apt.ClassProcessor.java
com.turbomanage.storm.apt.ClassTemplate.java
com.turbomanage.storm.apt.MainProcessor.java
com.turbomanage.storm.apt.ProcessorLogger.java
com.turbomanage.storm.apt.SqlUtil.java
com.turbomanage.storm.apt.StormAnnotationException.java
com.turbomanage.storm.apt.StormEnvironment.java
com.turbomanage.storm.apt.converter.ConverterModel.java
com.turbomanage.storm.apt.converter.ConverterProcessor.java
com.turbomanage.storm.apt.converter.ConverterTypeAnnotationValueVisitor.java
com.turbomanage.storm.apt.converter.ConverterTypeAnnotationValuesVisitor.java
com.turbomanage.storm.apt.converter.package-info.java
com.turbomanage.storm.apt.database.DatabaseFactoryTemplate.java
com.turbomanage.storm.apt.database.DatabaseModel.java
com.turbomanage.storm.apt.database.DatabaseProcessor.java
com.turbomanage.storm.apt.database.package-info.java
com.turbomanage.storm.apt.entity.EntityDaoTemplate.java
com.turbomanage.storm.apt.entity.EntityModel.java
com.turbomanage.storm.apt.entity.EntityProcessor.java
com.turbomanage.storm.apt.entity.FieldModel.java
com.turbomanage.storm.apt.entity.TableHelperTemplate.java
com.turbomanage.storm.apt.entity.package-info.java
com.turbomanage.storm.csv.CsvTableReader.java
com.turbomanage.storm.csv.CsvTableWriter.java
com.turbomanage.storm.csv.CsvUtils.java
com.turbomanage.storm.csv.package-info.java
com.turbomanage.storm.exception.TooManyResultsException.java
com.turbomanage.storm.exception.TypeNotSupportedException.java
com.turbomanage.storm.exception.package-info.java
com.turbomanage.storm.query.Query.java
com.turbomanage.storm.query.package-info.java
com.turbomanage.storm.sample.activity.ContactActivity.java
com.turbomanage.storm.sample.activity.NewContactActivity.java
com.turbomanage.storm.sample.adapter.ContactAdapter.java
com.turbomanage.storm.sample.database.SampleDatabaseHelper.java
com.turbomanage.storm.sample.loader.AbstractAsyncTaskLoader.java
com.turbomanage.storm.sample.loader.ContactLoader.java
com.turbomanage.storm.sample.model.Contact.java
com.turbomanage.storm.types.BlobConverter.java
com.turbomanage.storm.types.BooleanConverter.java
com.turbomanage.storm.types.ByteConverter.java
com.turbomanage.storm.types.CharConverter.java
com.turbomanage.storm.types.DateConverter.java
com.turbomanage.storm.types.DoubleConverter.java
com.turbomanage.storm.types.EnumConverter.java
com.turbomanage.storm.types.FloatConverter.java
com.turbomanage.storm.types.IntegerConverter.java
com.turbomanage.storm.types.LongConverter.java
com.turbomanage.storm.types.PrimitiveConverter.java
com.turbomanage.storm.types.ShortConverter.java
com.turbomanage.storm.types.StringConverter.java
com.turbomanage.storm.types.TypeConverter.java
com.turbomanage.storm.types.package-info.java
com.turbomanage.storm.package-info.java