Package net.gouline.riskybusiness.data

Source Code of net.gouline.riskybusiness.data.ParsableParser

package net.gouline.riskybusiness.data;

import au.com.bytecode.opencsv.CSVReader;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
* Parser for generic parsable objects.
*
* @author Mike Gouline
*/
public abstract class ParsableParser<T extends Parsable> {
  protected ParsableParser() {}

  /**
   * Parses CSV into a list of parsable objects.
   *
   * @param input    CSV reader.
   * @param tolerant Skip errors if true, throw exceptions if false.
   * @return List of parsable objects.
   * @throws IOException Error reading.
   */
  public List<T> parse(Reader input, boolean tolerant)
          throws IOException {
    CSVReader reader = new CSVReader(input);

    List<T> parsables = new ArrayList<T>();
    String[] headers = reader.readNext();

    if (headers != null) {
      String[] line;
      T parsable;

      while ((line = reader.readNext()) != null) {
        parsable = newInstance();

        for (int i = 0; i < line.length; ++i) {
          if (i >= headers.length && !tolerant)
            throw new IllegalArgumentException("Line length header mismatch");

          try {
            parsable.setField(headers[i], line[i]);
          } catch (IllegalArgumentException e) {
            if (!tolerant) throw e;
          }
        }

        parsables.add(parsable);
      }
    }

    return parsables;
  }

  /**
   * Create new instance of a parsable object type.
   *
   * @return New instance of parsable object type.
   */
  protected abstract T newInstance();
}
TOP

Related Classes of net.gouline.riskybusiness.data.ParsableParser

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.