@Override
 public Report generateReport(String fileInput) throws CalculateIncomeTaxException {
   Reader in = null;
   List<InputRawData> inputRawData = new ArrayList<InputRawData>();
   try {
     in = new FileReader(fileInput);
     Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().withIgnoreEmptyLines().parse(in);
     for (CSVRecord record : records) {
       String firstName = record.get("FirstName");
       String lastName = record.get("LastName");
       String annualSalary = record.get("AnnualSalary");
       String superRate = record.get("SuperRate");
       String paymentMonth = record.get("PaymentMonth");
       inputRawData.add(
           new InputRawData(firstName, lastName, annualSalary, superRate, paymentMonth));
     }
   } catch (FileNotFoundException fileNotFound) {
     fileNotFound.printStackTrace();
   } catch (IOException ioException) {
     ioException.printStackTrace();
   } finally {
     try {
       in.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return reportFactory.create(inputRawData);
 }
Example #2
0
  /**
   * Translates the given CSV content into a List of objects.
   *
   * <p>Translation of each row into its representative object is handled by the {@link
   * RowTranslator} provided during construction. This class only handles the generic iteration
   * logic and global error handling.
   *
   * <p><strong>Warning:</strong> the given CSV content is read completely into memory while
   * parsing. This method does not therefore support very large CSV files (i.e., 50MB+).
   *
   * @param csvReader a Reader providing the CSV content. This method will close the reader when
   *     done.
   */
  public TabularParseResult<T> readObjects(final Reader csvReader) {
    final ArrayList<TabularUploadError> errors = new ArrayList<>();

    try {
      final List<CSVRecord> records = CSVFormat.EXCEL.parse(csvReader).getRecords();
      LOGGER.debug("The CSV file has {} rows.", records.size());

      if (records.isEmpty()) {
        errors.add(TabularUploadError.global(ValidationCodes.NO_VALUE, null, "no records"));
      } else {
        return readProcedures(records, errors);
      }
    } catch (final IOException ex) {
      errors.add(
          TabularUploadError.global(
              ValidationCodes.INVALID_CONTENTS, null, "Could not parse the CSV content."));
    } finally {
      try {
        csvReader.close();
      } catch (final IOException ex) {
        LOGGER.warn("Failed to close the CSV reader.", ex);
      }
    }

    return new TabularParseResult<>(Collections.<T>emptyList(), errors);
  }
  public synchronized EnrichmentResultWriter open() {
    LOG.info("Opening result writer on file: " + outFile.getAbsolutePath());

    if (outFile.exists()) {
      throw new RuntimeException("File already exists, stopping: " + outFile.getAbsolutePath());
    }

    checkIfWritable(outFile);

    final FileWriter fileWriter;
    try {
      fileWriter = new FileWriter(outFile, true);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    try {
      this.printer =
          new CSVPrinter(
              fileWriter,
              CSVFormat.EXCEL
                  .withDelimiter(';')
                  .withHeader("idRef", "isbn", "userEmail", "resultStatus", "errorMessage"));
    } catch (IOException e) {
      throw new RuntimeException("Unable to write results to CSV: " + outFile.getAbsolutePath(), e);
    }

    return this;
  }
 /**
  * Returns a <code>CSVParser</code> object to access the contents of an open file, possibly
  * without a header row and a different data delimiter than a comma.
  *
  * <p>Each line of the file should be formatted as data separated by the delimiter passed as a
  * parameter and with/without a header row to describe the column names. This is useful if the
  * data is separated by some character other than a comma.
  *
  * @param withHeader uses first row of data as a header row only if true
  * @param delimiter a single character that separates one field of data from another
  * @return a <code>CSVParser</code> that can provide access to the records in the file one at a
  *     time
  * @throws exception if this file does not represent a CSV formatted data
  * @throws exception if <code>delimiter.length() != 1</code>
  */
 public CSVParser getCSVParser(boolean withHeader, String delimiter) {
   if (delimiter == null || delimiter.length() != 1) {
     throw new ResourceException(
         "FileResource: CSV delimiter must be a single character: " + delimiter);
   }
   try {
     char delim = delimiter.charAt(0);
     Reader input = new StringReader(mySource);
     if (withHeader) {
       return new CSVParser(input, CSVFormat.EXCEL.withHeader().withDelimiter(delim));
     } else {
       return new CSVParser(input, CSVFormat.EXCEL.withDelimiter(delim));
     }
   } catch (Exception e) {
     throw new ResourceException("FileResource: cannot read " + myPath + " as a CSV file.");
   }
 }
 /**
  * Executa carregamento da matriz de adjacência por um arquivo CSV
  *
  * @param file Arquivo CSV
  * @throws IOException Problema no momento da leitura do arquivo CSV
  */
 public void loadCsv(File file) throws IOException {
   Reader in = new FileReader(file);
   Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
   for (CSVRecord record : records) {
     List<Integer> linha = new ArrayList<>();
     Iterator<String> linhaCsv = record.iterator();
     while (linhaCsv.hasNext()) {
       try {
         linha.add(Integer.parseInt(linhaCsv.next()));
       } catch (NumberFormatException e) {
         throw new RuntimeException("Não foi possivel converter arquivo!", e);
       }
     }
     mapa.add(linha);
   }
 }
  // obter as masterRules de cada site para cada atributo
  private String getMasterRule(Site site, Attribute attribute) {
    try (Reader in = new FileReader(Paths.PATH_INTRASITE + "/" + site.getPath() + "/result.csv")) {
      try (CSVParser parser = new CSVParser(in, CSVFormat.EXCEL.withHeader())) {

        for (CSVRecord record : parser) {
          if (record.get("ATTRIBUTE").equals(attribute.getAttributeID())) {
            if (record.get("RULE").equals("Attribute not found")) {
              return null;
            }
            return record.get("RULE");
          }
        }
      }
    } catch (FileNotFoundException ex) {
      Logger.getLogger(CheckDistanceExpectedMapping.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(CheckDistanceExpectedMapping.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
  }
Example #7
0
  public void processCsvFile(String csvFile) throws IOException {
    if (csvFile != null && !csvFile.isEmpty()) {
      fileName = csvFile;
    }
    File f = new File(getCsvPath());
    CSVParser parser = CSVParser.parse(f, Charset.forName("UTF-8"), CSVFormat.EXCEL.withHeader());
    for (CSVRecord record : parser) {
      String serialNumber = record.get("Serial Number");

      boolean success = false;
      if (matchOnly) {
        MobileDeviceMatch match = findMobileDevice(serialNumber);
        if (match != null) {
          success = true;
        }
      } else {
        String deviceName = record.get("iPad Name");
        String assetTag = record.get("Asset Tag");
        String building = record.get("Building");
        String room = record.get("Room");
        String department = record.get("Department");
        if (serialNumber != null
            && !serialNumber.isEmpty()
            && assetTag != null
            && !assetTag.isEmpty()
            && deviceName != null
            && !deviceName.isEmpty()) {

          success =
              updateMobileDevice(serialNumber, deviceName, assetTag, building, room, department);
        } else {
          System.out.println("bad record at line " + String.valueOf(record.getRecordNumber()));
          continue;
        }
      }
      System.out.println(serialNumber + "\t" + String.valueOf(success));
    }
  }
Example #8
0
  public LinkedList<IRule> loadFromCsv() throws IOException {
    InputStream ins = this.getClass().getClassLoader().getResourceAsStream(ruleCsvPath);
    InputStreamReader inr = new InputStreamReader(ins);
    CSVParser parser = new CSVParser(inr, CSVFormat.EXCEL.withHeader());
    Iterable<CSVRecord> records = parser.getRecords();

    LinkedList<IRule> lst = new LinkedList<IRule>();
    for (CSVRecord record : records) {
      Rule rule = new Rule();
      RuleConditionScript ruleCondition = new RuleConditionScript();
      // set conditions
      ruleCondition.setExpression(record.get(COLUMN_EXPRESSION));
      rule.setiCondition(ruleCondition);
      rule.setRuleName(record.get(COLUMN_RULE_NAME));
      rule.setRuleGroup(record.get(COLUMN_GROUP_NAME));
      // set action
      RuleActionScript action = new RuleActionScript();
      rule.setiAction(action);
      // add rule
      lst.add(rule);
    }
    return lst;
  }