Example usage for org.apache.commons.csv CSVRecord get

List of usage examples for org.apache.commons.csv CSVRecord get

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVRecord get.

Prototype

public String get(final String name) 

Source Link

Document

Returns a value by name.

Usage

From source file:ColdestWeather.ColdestWeather.java

public String fileWithColdestTemperature() {
    CSVRecord coldestSoFar = null;/*  www  . j  a  v  a2 s .c o m*/
    String ColdestTempFile = "";
    DirectoryResource dr = new DirectoryResource();
    //Iterate over all the files
    for (File file : dr.selectedFiles()) {
        FileResource fr = new FileResource(file);
        //call coldestHourInFile to get the file with lowest temp
        CSVRecord currentRow = coldestHourInFile(fr.getCSVParser());
        if (coldestSoFar == null) {
            coldestSoFar = currentRow;
        } else {
            double currentTemp = Double.parseDouble(currentRow.get("TemperatureF"));
            double coldestTemp = Double.parseDouble(coldestSoFar.get("TemperatureF"));
            //Check if currentTemp < coldestTemp
            if (currentTemp < coldestTemp && currentTemp > -9000) {
                //Update coldesSoFar to currentRow
                coldestSoFar = currentRow;
                ColdestTempFile = file.getAbsolutePath();
            }
        }

    }

    return ColdestTempFile;
}

From source file:biz.ganttproject.impex.csv.CsvImportTest.java

public void testBasic() throws Exception {
    String header = "A, B";
    String data = "a1, b1";
    final AtomicBoolean wasCalled = new AtomicBoolean(false);
    RecordGroup recordGroup = new RecordGroup("AB", ImmutableSet.<String>of("A", "B")) {
        @Override/*  w  ww . jav a  2  s .  co  m*/
        protected boolean doProcess(CSVRecord record) {
            if (!super.doProcess(record)) {
                return false;
            }
            wasCalled.set(true);
            assertEquals("a1", record.get("A"));
            assertEquals("b1", record.get("B"));
            return true;
        }
    };
    GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header, data)), recordGroup);
    importer.load();
    assertTrue(wasCalled.get());
}

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.QuestionSetManagerTest.java

private void set_of_duplicate_question_ids_is_built() throws PipelineException {
    // Compile a list of all duplicate thread QIDs from the TSV file
    this.duplicateQuestionIDs = new HashSet<>();
    try (CSVParser parser = CSVFormat.TDF.withHeader().parse(new FileReader(dupThreadTsvFile))) {
        for (CSVRecord record : parser.getRecords()) {
            duplicateQuestionIDs.add(record.get(CorpusBuilder.TSV_COL_HEADER_THREAD_ID));
        }/* w  ww .j  a v  a  2s.  c  o m*/
    } catch (IOException e) {
        throw new PipelineException(e);
    }
}

From source file:biz.ganttproject.impex.csv.CsvImportTest.java

public void testSkipEmptyLine() throws Exception {
    String header = "A, B";
    String data = "a1, b1";
    final AtomicBoolean wasCalled = new AtomicBoolean(false);
    RecordGroup recordGroup = new RecordGroup("AB", ImmutableSet.<String>of("A", "B")) {
        @Override/* ww  w .  j a  v  a2 s. com*/
        protected boolean doProcess(CSVRecord record) {
            if (!super.doProcess(record)) {
                return false;
            }
            wasCalled.set(true);
            assertEquals("a1", record.get("A"));
            assertEquals("b1", record.get("B"));
            return true;
        }
    };
    GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header, "", data)),
            recordGroup);
    importer.load();
    assertTrue(wasCalled.get());
}

From source file:biz.ganttproject.impex.csv.CsvImportTest.java

public void testIncompleteHeader() throws IOException {
    String header = "A, B";
    String data = "a1, b1";
    final AtomicBoolean wasCalled = new AtomicBoolean(false);
    RecordGroup recordGroup = new RecordGroup("ABC", ImmutableSet.<String>of("A", "B", "C"), // all fields
            ImmutableSet.<String>of("A", "B")) { // mandatory fields
        @Override//from w  w w .  j a va  2 s . c o m
        protected boolean doProcess(CSVRecord record) {
            if (!super.doProcess(record)) {
                return false;
            }
            wasCalled.set(true);
            assertEquals("a1", record.get("A"));
            assertEquals("b1", record.get("B"));
            return true;
        }
    };
    GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header, data)), recordGroup);
    importer.load();
    assertTrue(wasCalled.get());
}

From source file:biz.ganttproject.impex.csv.CsvImportTest.java

public void testSkipUntilFirstHeader() throws IOException {
    String notHeader = "FOO, BAR, A";
    String header = "A, B";
    String data = "a1, b1";
    final AtomicBoolean wasCalled = new AtomicBoolean(false);
    RecordGroup recordGroup = new RecordGroup("ABC", ImmutableSet.<String>of("A", "B")) {
        @Override/*from ww  w  .ja v a 2  s.  c o  m*/
        protected boolean doProcess(CSVRecord record) {
            if (!super.doProcess(record)) {
                return false;
            }
            wasCalled.set(true);
            assertEquals("a1", record.get("A"));
            assertEquals("b1", record.get("B"));
            return true;
        }
    };
    GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(notHeader, header, data)),
            recordGroup);
    importer.load();
    assertTrue(wasCalled.get());
    assertEquals(1, importer.getSkippedLineCount());
}

From source file:com.teamnx.util.CSVToDateBase.java

/**
 * @param fileName/* w  w w .j  a v a  2s.  c  om*/
 * @param type
 * @return
 */
public List readCsvFile(String fileName, int type) {
    FileReader fileReader = null;
    CSVParser csvFileParser = null;
    List list = null;
    //CSVFormatheader mapping
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(file_header);
    try {
        //?FileReader object
        fileReader = new FileReader(fileName);
        //? CSVParser object
        csvFileParser = new CSVParser(fileReader, csvFileFormat);
        //CSVrecords
        List<CSVRecord> csvRecords = csvFileParser.getRecords();
        // CSV

        switch (type) {
        case USER:
            List<User> userList = new ArrayList<User>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                //?
                User user = new User();
                user.setId(record.get("id"));
                user.setName(record.get("name"));
                user.setPassword(record.get("password"));
                user.setDepartment_id(Integer.parseInt(record.get("department_id")));
                user.setCharacter(Integer.parseInt(record.get("character")));
                user.setClass_id(record.get("class_id"));
                user.setDepartment_name(record.get("department_name"));
                userList.add(user);
            }
            list = userList;
            break;
        case DEPARTMENT:
            List<Department> departmentList = new ArrayList<Department>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                //?
                Department department = new Department();
                department.setId(Integer.parseInt(record.get("id")));
                department.setName(record.get("name"));
                departmentList.add(department);
            }
            list = departmentList;
            break;
        case COURSE:
            List<Course> courseList = new ArrayList<Course>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                //?
                Course course = new Course();
                course.setId(record.get("id"));
                course.setName(record.get("name"));
                course.setDepartment_id(Integer.parseInt(record.get("department_id")));
                course.setStart_time(Integer.parseInt(record.get("start_time")));
                course.setEnd_time(Integer.parseInt(record.get("end_time")));
                course.setPosition(record.get("position"));
                course.setSchedule(record.get("schedule"));
                course.setYear(Integer.parseInt(record.get("year")));
                course.setSemester(Integer.parseInt(record.get("semester")));
                int j = Integer.parseInt(record.get("category"));
                course.setCategory(j == 1 ? true : false);
                course.setMax_member(Integer.parseInt(record.get("max_member")));
                courseList.add(course);
            }
            list = courseList;
            break;
        case STUDENT_COURSE:
            List<StudentCourse> studentCourseList = new ArrayList<StudentCourse>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                StudentCourse studentCourse = new StudentCourse();
                studentCourse.setId(record.get("id"));
                studentCourse.setCourseId(record.get("course_id"));
                studentCourse.setStudentId(record.get("student_id"));
                studentCourseList.add(studentCourse);
            }
            list = studentCourseList;
            break;
        case TEACHER_COURSE:
            List<TeacherCourse> teacherCourseList = new ArrayList<TeacherCourse>();
            for (int i = 1; i < csvRecords.size(); i++) {
                CSVRecord record = csvRecords.get(i);
                TeacherCourse teacherCourse = new TeacherCourse();
                teacherCourse.setId(record.get("id"));
                teacherCourse.setTeacherId(record.get("teacher_id"));
                teacherCourse.setCourseId(record.get("course_id"));
                teacherCourseList.add(teacherCourse);
            }
            list = teacherCourseList;
            break;

        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fileReader.close();
            csvFileParser.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return list;
        }
    }
}

From source file:de.speexx.csv.table.CsvReader.java

@Override
public Iterator<Row> iterator() {
    return new Iterator<Row>() {
        @Override//w w w. ja va 2 s .  c  om
        public boolean hasNext() {
            return CsvReader.this.itr.hasNext();
        }

        @Override
        public Row next() {
            final CSVRecord record = CsvReader.this.itr.next();
            final List<Entry> entries = new ArrayList<>();

            CsvReader.this.descriptors.stream().forEach((desc) -> {
                final String value = record.get(desc.getName());
                final SimpleEntry<String> entry = new SimpleEntry<>(value, desc);
                entries.add(entry);
            });

            return new SimpleRow(entries);
        }
    };
}

From source file:br.edimarmanica.trinity.intrasitemapping.manual.Mapping.java

private List<Map<String, String>> readOffset(File offsetFile) {
    List<Map<String, String>> offset = new ArrayList<>(); //cada arquivo  um offset

    try (Reader in = new FileReader(offsetFile)) {
        try (CSVParser parser = new CSVParser(in, CSVFormat.EXCEL)) {
            int nrRegistro = 0;
            for (CSVRecord record : parser) {

                for (int nrRegra = 0; nrRegra < record.size(); nrRegra++) {
                    String value;
                    try {
                        value = Formatter.formatValue(Preprocessing.filter(record.get(nrRegra)));
                    } catch (InvalidValue ex) {
                        value = "";
                    }/*from  ww w.j av a  2  s.co m*/

                    if (nrRegistro == 0) {
                        Map<String, String> regra = new HashMap<>();
                        regra.put(Formatter.formatURL(record.get(0)), value);
                        offset.add(regra);
                    } else {
                        offset.get(nrRegra).put(Formatter.formatURL(record.get(0)), value);
                    }
                }
                nrRegistro++;
            }
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Mapping.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Mapping.class.getName()).log(Level.SEVERE, null, ex);
    }

    return offset;
}

From source file:ca.liquidlabs.android.speedtestvisualizer.model.SpeedTestRecord.java

/**
 * Constructs speedtest model object from parsed csv record. <br/>
 * TODO: Handle the exceptions in future, and show user friendly error
 * message to user./*  w  w w. ja  v  a  2s. c  o m*/
 * 
 * @param csvRecord
 */
public SpeedTestRecord(CSVRecord csvRecord) {
    try {
        this.date = csvRecord.get(KEY_DATE);

        // data connection type - should be one of expected values
        this.connectionType = ConnectionType.fromString(csvRecord.get(KEY_CONNTYPE));

        // Lat, Lon is in float
        this.lat = Float.parseFloat(csvRecord.get(KEY_LAT));
        this.lon = Float.parseFloat(csvRecord.get(KEY_LON));

        // download and upload values are always in kbps
        this.download = Float.parseFloat(csvRecord.get(KEY_DOWNL));
        this.upload = Float.parseFloat(csvRecord.get(KEY_UPL));

        // latency is numeric - in milliseconds
        this.latency = Integer.parseInt(csvRecord.get(KEY_LATENCY));

        this.serverName = csvRecord.get(KEY_SERVER);
        this.internalIp = csvRecord.get(KEY_IPINT);
        this.externalIp = csvRecord.get(KEY_IPEXT);
    } catch (NumberFormatException e) {
        // if for some reason unexpected value is passed, stop parsing
        throw new IllegalArgumentException("Unable to parse record: " + csvRecord.toString());
    } catch (ArrayIndexOutOfBoundsException e) {
        // this might happen for some leftover lines when copy and pasting
        // data.
        throw new IllegalArgumentException("Invalid record : " + csvRecord.toString());
    }
}