Package au.com.bytecode.opencsv

Examples of au.com.bytecode.opencsv.CSVReader


  }
 
  @Override
  public boolean isActive() {
    try {
      CSVReader reader = this.createCSVReader();
      reader.close();
      return true;
    } catch (Exception e) {
      log.error("Error in checking CSV config availability", e);
      return false;
    }
View Full Code Here


 
  public PrefetchDataInfo runQuery(XMLStreamWriter xmlWriter, InternalParamCollection params,
      int queryLevel, boolean prefetchData, PrefetchDataInfo prefetchedData)
      throws DataServiceFault {
    PrefetchDataInfo retPFData = null;
    CSVReader reader = null;
    if (prefetchedData != null) {
      reader = (CSVReader) prefetchedData.getObject(DBConstants.PrefetchProperties.CSV_READER);
    }
    try {
      if (reader == null) {
            reader = this.getConfig().createCSVReader();
            if (prefetchData) {
            retPFData = new PrefetchDataInfo();
            retPFData.addObject(DBConstants.PrefetchProperties.CSV_READER, reader);
            return retPFData;
          }
      }       
        String[] record = null;
        int maxCount = this.getConfig().getMaxRowCount();
        int i = 0;
        DataEntry dataEntry;
        Map<Integer, String> columnsMap = this.getConfig().getColumnMappings();
        boolean useColumnNumbers = this.isUsingColumnNumbers();     
        while ((record = reader.readNext()) != null) {
          if (maxCount != -1 && i >= maxCount) {
            break;
          }
          dataEntry = new DataEntry();
          for (int j = 0; j < record.length; j++) {
            dataEntry.addValue(useColumnNumbers ? Integer.toString(j + 1) :
              columnsMap.get(j + 1), new ParamValue(record[j]));
          }
          this.writeResultEntry(xmlWriter, dataEntry, params, queryLevel);
          i++;
        }
       
        return null;
    } catch (Exception e) {
      throw new DataServiceFault(e, "Error in CSVQuery.runQuery.");
    } finally {
      if (reader != null && !prefetchData) {
        try {
            reader.close();
        } catch (Exception e) {
          log.error("Error in closing CSV reader", e);
        }
      }
    }
View Full Code Here

    secrets.clear();

    boolean isOiSafeCsv = false;
    boolean isSecretsScv = false;
    boolean success = false;
    CSVReader reader = null;

    try {
      reader = new CSVReader(new FileReader(file));

      // Use the first line to determine the type of csv file.  Secrets will
      // output 5 columns, with the names as used in the exportSecrets()
      // function.  OI Safe 1.1.0 is also detected.
      String headers[] = reader.readNext();
      if (null != headers) {
        isSecretsScv = isSecretsCsv(headers);
        if (!isSecretsScv)
          isOiSafeCsv = isOiSafeCsv(headers);
      }

      // Read all the rest of the lines as secrets.
      for (;;) {
        String[] row = reader.readNext();
        if (null == row)
          break;

        Secret secret = new Secret();
        if (isOiSafeCsv) {
          secret.setDescription(row[1]);
          secret.setUsername(row[3]);
          secret.setPassword(row[4]);
          secret.setEmail(EMPTY_STRING);

          // I will combine the category, website, and notes columns into
          // the notes field in secrets.
          int approxMaxLength = row[0].length() + row[2].length() +
                                row[5].length() + 32;
          StringBuilder builder = new StringBuilder(approxMaxLength);
          builder.append(row[5]).append("\n\n");
          builder.append("Category: ").append(row[0]).append('\n');
          if (null != row[2] && row[2].length() > 0)
            builder.append("Website: ").append(row[2]).append('\n');

          secret.setNote(builder.toString());
        } else {
          // If we get here, then this may be an unknown format.  For better
          // or for worse, this is a "best effort" to import that data.
          secret.setDescription(row[0]);
          secret.setUsername(row[1]);
          secret.setPassword(row[2]);
          secret.setEmail(row[3]);
          secret.setNote(row[4]);
        }

        secrets.add(secret);
      }

      // We'll only return complete success if we get here, and we detected
      // that we knew the file format.  This will give the user an indication
      // do look at the secrets if the format was not automatically detected.
      success = isOiSafeCsv || isSecretsScv;
    } catch (Exception ex) {
      Log.e(LOG_TAG, "importSecrets", ex);
    } finally {
      try {if (null != reader) reader.close();} catch (IOException ex) {}
    }

    return success;
  }
View Full Code Here

  public void readFromStream(InputStream stream, AbstractTvDataService dataService) throws IOException, FileFormatException {
    readFromStream(stream, dataService, true);
  }

  public void readFromStream(InputStream stream, AbstractTvDataService dataService, boolean compressed) throws IOException, FileFormatException {
    CSVReader reader;

    if (compressed) {
      InputStream gIn = IOUtilities.openSaveGZipInputStream(stream);
      reader = new CSVReader(new InputStreamReader(gIn, "ISO-8859-15"), ';');
    } else {
      reader = new CSVReader(new InputStreamReader(stream, "ISO-8859-15"), ';');
    }

    int lineCount = 1;

    /**
     * ChannelList.readFromStream is called by both MirrorUpdater and
     * TvBrowserDataService. The MirrorUpdater calls this method without
     * DataService and doesn't need the IconLoader
     */
    IconLoader iconLoader = null;
    if (dataService != null && dataService instanceof TvBrowserDataService) {
      File dataDir = ((TvBrowserDataService) dataService).getWorkingDirectory();
      iconLoader = new IconLoader(TvBrowserDataService.getInstance(), mGroup.getId(), dataDir);
    }

    String[] tokens;
    while ((tokens = reader.readNext()) != null) {
      if (tokens.length < 4) {
        throw new FileFormatException("Syntax error in mirror file line " + lineCount + ": column count is '" + tokens.length + " < 4' : " + tokens[0]);
      }

      String country = null, timezone = null, id = null, name = null, copyright = null, webpage = null, iconUrl = null, categoryStr = null, unescapedname = null;
      try {
        country = tokens[0];
        timezone = tokens[1];
        id = tokens[2];
        name = tokens[3];
        copyright = tokens[4];
        webpage = tokens[5];
        iconUrl = tokens[6];
        categoryStr = tokens[7];

        if (tokens.length > 8) {
          unescapedname = name;
          name = StringEscapeUtils.unescapeHtml(tokens[8]);
        }

      } catch (ArrayIndexOutOfBoundsException e) {
        // ignore
      }

      int categories = Channel.CATEGORY_NONE;
      if (categoryStr != null) {
        try {
          categories = Integer.parseInt(categoryStr);
        } catch (NumberFormatException e) {
          categories = Channel.CATEGORY_NONE;
        }
      }
      Channel channel = new Channel(dataService, name, id, TimeZone.getTimeZone(timezone), country, copyright,
          webpage, mGroup, null, categories, unescapedname);
      if (iconLoader != null && iconUrl != null && iconUrl.length() > 0) {
        Icon icon = iconLoader.getIcon(id, iconUrl);
        if (icon != null) {
          channel.setDefaultIcon(icon);
        }
      }
      addChannel(channel, iconUrl);
      lineCount++;
    }

    reader.close();
    if (iconLoader != null) {
      iconLoader.close();
    }
  }
View Full Code Here

          // set the auto-increment counter to the next highest unused index.  otherwise it with keep making a longer and longer gap in the indexes.
          String statement1 = "ALTER TABLE compass.program_profile_info AUTO_INCREMENT = 1";
          PreparedStatement pstmt1 = dbconn.prepareStatement(statement1);
          pstmt1.executeUpdate();
        } catch (Exception e) {e.printStackTrace();}
        CSVReader cSVReader = new CSVReader(new InputStreamReader(in), ',', '"', 1);
        String [] nextLine;
        while ((nextLine = cSVReader.readNext()) != null) {
          System.out.println("read from CSV url: " + nextLine[0] + "," + nextLine[1] + "," + "etc...");
          String statement = "insert into compass.program_profile_info " +
              "(agency_name, program_name, program_type_code, program_type, " +
              "target_pop_a_code, target_pop_a_name, units_total, units_occupied, " +
              "units_available, contact_name, contact_phone, program_address_full, feed_source, update_time_stamp) " +
              "values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
          PreparedStatement pstmt = dbconn.prepareStatement(statement);
          pstmt.setString(1, nextLine[0]);
          //System.out.println("agency name is: " + nextLine[0]);
          pstmt.setString(2, nextLine[1]);
          //System.out.println("program name is: " + nextLine[1]);
          String programTypeCode = translateProgramTypeCode(nextLine[2]);
          //System.out.println("program type code is: " + programTypeCode);
          pstmt.setString(3, programTypeCode);
          String programType = translateProgramType(nextLine[2]);
          //System.out.println("program type is: " + programType);
          pstmt.setString(4, programType);
          System.out.println("nextLine[3] is: " + nextLine[3])
          String targetPopulation = translateTargetPopulation(nextLine[3]);
          System.out.println("target population is: " + targetPopulation);
          pstmt.setString(5, targetPopulation);
          pstmt.setString(6, translateTargetPopulationCode(targetPopulation));
          // units total
          pstmt.setString(7, nextLine[5]);
          // units occupied
          pstmt.setString(8, nextLine[6]);
          // units available
          pstmt.setString(9, nextLine[7]);
          // contact/phone #/address
          String[] contactInfo = splitContactInfo(nextLine[8]);
          if (contactInfo.length == 1) {
            // contact
            pstmt.setString(10, contactInfo[0]);
            // phone
            pstmt.setString(11, null);
            // address
            pstmt.setString(12, null);
          }
          if (contactInfo.length == 2) {
            // contact
            pstmt.setString(10, null);
            // phone
            pstmt.setString(11, contactInfo[0]);
            // address
            pstmt.setString(12, contactInfo[1]);
          }
          if (contactInfo.length == 3) {
            // contact
            pstmt.setString(10, contactInfo[0]);
            // phone
            pstmt.setString(11, contactInfo[1]);
            // address
            pstmt.setString(12, contactInfo[2]);
          }
          else {
            // contact
            pstmt.setString(10, null);
            // phone
            pstmt.setString(11, null);
            // address
            pstmt.setString(12, null);
          }
          // data source code
          pstmt.setString(13, "1");
          pstmt.setTimestamp(14, new Timestamp(System.currentTimeMillis()));
          pstmt.executeUpdate();
        }
        System.out.println("While loop ended");
        httpconn.disconnect();
        cSVReader.close();
      } catch (Exception e) {e.printStackTrace();}
    }
    catch (SQLException e) {
      e.printStackTrace();
    }
View Full Code Here

     *
     * @throws IOException if the CSV file cannot be read
     */
    private void createCsvReader() throws IOException {
      lineNumber = 1;
      reader = new CSVReader(new FileReader(fileName));
      if (headerPresent) {
        header = reader.readNext();
        lineNumber++;
      }
    }
View Full Code Here

  }

  // readFile
  private CSVReader readResource(String source) {
    CSVReader reader = null;
    try {
      InputStream is = getClass().getResourceAsStream("/" + source);
      InputStreamReader inputStreamReader = new InputStreamReader(is);
      reader = new CSVReader(inputStreamReader, ';',
          CSVWriter.NO_QUOTE_CHARACTER);

    } catch (Exception e) {
      logger.error("readFile", e);
    }
View Full Code Here

    }
    return reader;
  }

  private CSVReader readFile(String source) {
    CSVReader reader = null;
    try {
      InputStream is = new FileInputStream(source);
      InputStreamReader inputStreamReader = new InputStreamReader(is);
      reader = new CSVReader(inputStreamReader, ';',
          CSVWriter.NO_QUOTE_CHARACTER);

    } catch (Exception e) {
      logger.error("readFile", e);
    }
View Full Code Here

    return dataBean;
  }

  public static List queryComputerBean() throws IOException {
    File csv = new File(Executions.getCurrent().getDesktop().getWebApp().getRealPath("/WEB-INF/xls/demo/data.csv"));
    CSVReader reader = new CSVReader(new FileReader(csv));
    List data = new ArrayList();
    String[] nextLine;
      while ((nextLine = reader.readNext()) != null) {
        ComputerBean computerBean = new ComputerBean();
        computerBean.setId(nextLine[0]);
        computerBean.setProduct(nextLine[1]);
        computerBean.setBrand(nextLine[2]);
        computerBean.setModel(nextLine[3]);
View Full Code Here

      log.debug("RESULT=" +result);
    }
   
    boolean ok = true;
   
    CSVReader reader = new CSVReader(new StringReader(result));
    List<String[]> lines;
    try {
      lines = reader.readAll();
    }
    catch (IOException e) {
      // Should not happen.
      String error = "Error while parsing CSV: " +e.getMessage();
      resolveUriResult.setError(error);
View Full Code Here

TOP

Related Classes of au.com.bytecode.opencsv.CSVReader

Copyright © 2018 www.massapicom. 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.