Example usage for org.apache.commons.csv CSVParser parse

List of usage examples for org.apache.commons.csv CSVParser parse

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVParser parse.

Prototype

public static CSVParser parse(final String string, final CSVFormat format) throws IOException 

Source Link

Document

Creates a parser for the given String .

Usage

From source file:com.ctt.persistance.StorageFile.java

public static void saveTransactions(byte[] file) throws IOException {
    try {//from w ww.j av a  2  s. com

        List<String> list = new ArrayList<String>();

        CSVParser csv;
        csv = CSVParser.parse(new String(file), CSVFormat.DEFAULT);

        List<CSVRecord> it = csv.getRecords();
        Transaction obj;

        int i = 0;
        for (i = 0; i < it.size(); i++) {
            if (i != 0) {
                obj = new Transaction((CSVRecord) it.get(i));

                if (obj.validateCanonical() && obj.isRepayment()) {
                    list.add(obj.repaymentString());

                    StorageFile.saveTransaction(obj);
                }
            }
        }
        FileUtils.writeLines(new File(Main.prop.getProperty("path_repayments")), list, "\n", true);
    } catch (Exception e) {
        Main.appendLog("Error: SAVE TRANSACTIONS: " + e.getMessage());
    }
}

From source file:com.anhth12.lambda.common.text.TextUtils.java

private static String[] doParseDelimited(String delimited, CSVFormat format) {
    Iterator<CSVRecord> records;
    try {/*from w  w w .j  ava 2  s  .  c  o m*/
        records = CSVParser.parse(delimited, format).iterator();
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }

    if (records.hasNext()) {
        return Iterators.toArray(records.next().iterator(), String.class);
    } else {
        return EMPTY_STRING;
    }
}

From source file:com.bigtester.ate.tcg.controller.TrainingFileDB.java

/**
 * Parses the line.//from www . ja va 2  s . com
 *
 * @param line
 *            the line
 * @return the user input training record
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static UserInputTrainingRecord parseLine(String line) throws IOException {
    CSVParser lineParser = CSVParser.parse(line, TrainingFileDB.getCSVFormat());
    List<CSVRecord> csvRecords = lineParser.getRecords();
    UserInputTrainingRecord retVal = null; // NOPMD
    for (CSVRecord record : csvRecords) {
        if (null != record) {
            String temp = record.get(0);
            String temp2 = record.get(1);
            if (null == temp)
                temp = "";
            if (null == temp2)
                temp2 = "";
            retVal = new UserInputTrainingRecord(temp, // NOPMD
                    temp2);
        }
    }
    if (null == retVal)
        throw new IOException();
    return retVal;
}

From source file:edu.emory.cci.aiw.i2b2etl.ksb.ValueSetSupport.java

void parseId(String id) throws ParseException {
    try (CSVParser csvParser = CSVParser.parse(id, CSV_FORMAT)) {
        List<CSVRecord> records = csvParser.getRecords();
        if (records.size() != 1) {
            return;
        }//from   w  ww.  ja va  2s . c o  m
        CSVRecord record = records.get(0);
        if (record.size() != 2) {
            return;
        }
        this.declaringPropId = record.get(0);
        this.propertyName = record.get(1);
    } catch (IOException invalid) {
        throw new ParseException("Invalid value set id " + id, 0);
    }
}

From source file:com.ibm.watson.catalyst.jumpqa.template.TemplateReader.java

@Override
public List<ITemplate> read(final String aString) {
    List<ITemplate> result = new ArrayList<ITemplate>();

    CSVParser parser;//from   ww  w  .ja  v a 2s  .  c o  m
    try {
        parser = CSVParser.parse(aString, format);
    } catch (IOException e) {
        throw new RuntimeException("IOError parsing CSV.", e);
    }
    final TemplateFactory tf = new TemplateFactory();
    parser.forEach((record) -> result.add(tf.readRecord(record)));

    logger.info("Read " + result.size() + " templates");
    return result;
}

From source file:com.cloudera.oryx.common.text.TextUtils.java

private static String[] doParseDelimited(String delimited, CSVFormat format) {
    try (CSVParser parser = CSVParser.parse(delimited, format)) {
        Iterator<CSVRecord> records = parser.iterator();
        return records.hasNext()
                ? StreamSupport.stream(records.next().spliterator(), false).toArray(String[]::new)
                : EMPTY_STRING;/*from  ww  w  .  j  a v  a 2s.  c  om*/
    } catch (IOException e) {
        throw new IllegalStateException(e); // Can't happen
    }
}

From source file:io.github.seiferma.jameica.hibiscus.dkb.creditcard.synchronize.csvparser.DKBCsvParser.java

public int getBalanceInCents() throws IOException {
    CSVParser parser = CSVParser.parse(metaDataCsv, csvFormat);
    List<CSVRecord> records = parser.getRecords();
    Optional<String> foundSaldo = records.stream().filter(r -> "Saldo:".equals(r.get(0))).map(r -> r.get(1))
            .findFirst();/*  ww  w . j a  v  a  2  s .com*/
    if (!foundSaldo.isPresent()) {
        throw new IOException("Could not find balance record.");
    }
    Pattern saldoPattern = Pattern.compile("(-?[0-9]+)([.]([0-9]{1,2}))? EUR");
    Matcher saldoMatcher = saldoPattern.matcher(foundSaldo.get());
    if (!saldoMatcher.matches()) {
        throw new IOException("Could not parse saldo.");
    }

    String euroString = saldoMatcher.group(1);
    String centString = saldoMatcher.group(3) == null ? "0" : saldoMatcher.group(3);

    return getCentsFromString(euroString, centString);
}

From source file:io.github.seiferma.jameica.hibiscus.dkb.creditcard.synchronize.csvparser.DKBCsvParser.java

public Date getBalanceDate() throws IOException {
    CSVParser parser = CSVParser.parse(metaDataCsv, csvFormat);
    Optional<String> foundDate = parser.getRecords().stream().filter(r -> "Datum:".equals(r.get(0)))
            .map(r -> r.get(1)).findFirst();
    if (!foundDate.isPresent()) {
        throw new IOException("Could not find balance date.");
    }/*from   w  ww .  j  a  v a 2 s. c o m*/
    try {
        return DateUtils.parseDate(foundDate.get());
    } catch (ParseException e) {
        throw new IOException("Could not parse balance date.", e);
    }
}

From source file:com.adobe.acs.commons.exporters.impl.users.UserExportServletTest.java

@Test
public void testWithNoParameterProvidedInRequest() throws Exception {
    servlet.doGet(context.request(), context.response());
    assertEquals(context.response().getStatus(), 200);
    String output = context.response().getOutputAsString();

    CSVParser parser = CSVParser.parse(output, CSVFormat.DEFAULT.withHeader());
    assertAllUsersPresent(parser.getRecords(), "alice", "bob", "charly", "admin", "anonymous");
}

From source file:com.nuevebit.miroculus.mrna.cli.DatabasePopulator.java

private void parseCSV(String csv) throws IOException {
    CSVParser csvParser = CSVParser.parse(csv, CSVFormat.EXCEL);

    Iterator<CSVRecord> records = csvParser.iterator();
    // ignore headers
    records.next();/*from  ww  w .  j a  v  a2s .c  o m*/

    // read line by line
    while (records.hasNext()) {
        CSVRecord record = records.next();

        // normalize the name (remove *)
        String miRNAName = MiRNA.normalizeName(record.get(0));
        MiRNA miRNA = miRNARepository.findByName(miRNAName);

        if (miRNA == null) { // primera vez que se agrega
            miRNA = miRNARepository.save(new MiRNA(miRNAName));
        }

        String diseaseName = record.get(1).toLowerCase().trim();
        Disease disease = diseaseRepository.findByName(diseaseName);

        if (disease == null) {
            disease = diseaseRepository.save(new Disease(diseaseName));
            disease.setMortalityRate(0d);
        }

        String authorName = record.get(4).trim();
        Author author = authorRepository.findByName(authorName);

        if (author == null) {
            author = authorRepository.save(new Author(authorName));
        }

        String publicationTitle = record.get(6).trim();
        String publicationJournal = record.get(5).trim();

        Publication pub = publicationRepository.findByNameAndJournal(publicationTitle, publicationJournal);

        if (pub == null) {
            pub = new Publication(publicationTitle, publicationJournal);
            pub.setAuthor(author);
            String year = record.get(7);
            pub.setYear(Integer.valueOf(year));
            pub.setDescription(record.get(9).trim());

            pub = publicationRepository.save(pub);

        }

        String methodName = record.get(8).trim();
        DiscoveryMethod method = discoveryMethodRepository.findByName(methodName);

        if (method == null) {
            method = discoveryMethodRepository.save(new DiscoveryMethod(methodName));
        }

        CorrelationDiscovery correlation = new CorrelationDiscovery(miRNA, disease,
                Integer.valueOf(record.get(2)));

        correlation.setPublication(pub);
        correlation.setMethod(method);

        // save the found correlation
        correlationDiscoveryRepository.save(correlation);
    }
}