Example #1
0
  /**
   * This method parses a CSV input stream and populates the database (and spreadsheet) with data.
   * The caller is responsible for managing the stream.
   *
   * @param inStream The stream to deserialized when populating the database.
   * @return populated database on sucess, null otherwise.
   */
  public Datastore openAsCSV(final InputStream inStream) {
    try {
      LOGGER.event("open csv database from stream");

      Datastore db = DatastoreFactory.newDatastore();
      db.setTitleNotifier(OpenSHAPA.getApplication());
      InputStreamReader isr = new InputStreamReader(inStream);
      BufferedReader csvFile = new BufferedReader(isr);

      // Read each line of the CSV file.
      String line = csvFile.readLine();

      // If we have a version identifier parse the file using the schema
      // that matches that identifier.
      if ("#4".equalsIgnoreCase(line)) {

        // Version 4 includes a comment for columns.
        line = parseDefinitions(csvFile, db);

        while (line != null) {
          line = parseVariable(csvFile, line, db, "#4");
        }
      } else if ("#3".equalsIgnoreCase(line)) {

        // Version 3 includes column visible status after the column type
        // Parse predicate definitions first.
        line = parseDefinitions(csvFile, db);

        while (line != null) {
          line = parseVariable(csvFile, line, db, "#3");
        }
      } else if ("#2".equalsIgnoreCase(line)) {

        // Parse predicate definitions first.
        line = parseDefinitions(csvFile, db);

        while (line != null) {
          line = parseVariable(csvFile, line, db);
        }

      } else {

        // Use the original schema to load the file - just variables,
        // and no escape characters.
        while (line != null) {
          line = parseVariable(csvFile, line, db);
        }
      }

      csvFile.close();
      isr.close();

      return db;
    } catch (IOException e) {
      LOGGER.error("Unable to read line from CSV file", e);
    } catch (UserWarningException e) {
      LOGGER.error("Unable to create new variable.", e);
    }

    // Error encountered - return null.
    return null;
  }