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:com.advdb.footballclub.FootBallClub.java

private void createOpponent(Session session) {

    Transaction transaction = null;//from   www. j  av  a 2  s.  com
    try {
        System.out.println("start createOpponent.");
        transaction = session.beginTransaction();
        Reader in = new FileReader("/Users/apichart/Documents/DW_opponent/DimOpponent-Table 1.csv");
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
        for (CSVRecord record : records) {
            String longName = record.get(2);
            String shortName = record.get(3);
            DimOpponent d = new DimOpponent(longName, shortName);
            session.save(d);
        }
        in.close();
        session.flush();
        session.clear();
        transaction.commit();

        System.out.println("finish createOpponent.");
    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FootBallClub.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FootBallClub.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.advdb.footballclub.FootBallClub.java

private void createPlayer(Session session) {

    Transaction transaction = null;//  w w w.jav a2  s .c  o m
    try {
        System.out.println("start createPlayer.");
        transaction = session.beginTransaction();
        Reader in = new FileReader("/Users/apichart/Documents/DW_opponent/DimPlayer-Table 1.csv");
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
        for (CSVRecord record : records) {
            String name = record.get(2);
            String nationality = record.get(3);
            String value = record.get(4);
            String height = record.get(6);
            String weight = record.get(7);
            DimPlayer d = new DimPlayer(name, nationality, Double.valueOf(value), Double.valueOf(height),
                    Double.valueOf(weight));
            session.save(d);
        }
        in.close();
        session.flush();
        session.clear();
        transaction.commit();

        System.out.println("finish createPlayer.");
    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FootBallClub.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FootBallClub.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.sapuraglobal.hrms.servlet.UploadEmp.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w  w . j  a va 2  s  .c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String action = request.getParameter("action");
    System.out.println("action: " + action);
    if (action == null || action.isEmpty()) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //PriceDAO priceDAO = new PriceDAO();

        try {
            List<FileItem> fields = upload.parseRequest(request);
            //out.println("Number of fields: " + fields.size() + "<br/><br/>");
            Iterator<FileItem> it = fields.iterator();
            while (it.hasNext()) {
                FileItem fileItem = it.next();
                //store in webserver.
                String fileName = fileItem.getName();
                if (fileName != null) {
                    File file = new File(fileName);
                    fileItem.write(file);
                    System.out.println("File successfully saved as " + file.getAbsolutePath());

                    //process file
                    Reader in = new FileReader(file.getAbsolutePath());
                    Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
                    for (CSVRecord record : records) {
                        String name = record.get("<name>");
                        String login = record.get("<login>");
                        String title = record.get("<title>");
                        String email = record.get("<email>");
                        String role = record.get("<role>");
                        String dept = record.get("<department>");
                        String joinDate = record.get("<joinDate>");
                        String probDate = record.get("<probDate>");
                        String annLeaveEnt = record.get("<leave_entitlement>");
                        String annBal = record.get("<leave_bal>");
                        String annMax = record.get("<leave_max>");
                        String annCF = record.get("<leave_cf>");
                        String med = record.get("<med_taken>");
                        String oil = record.get("<oil_taken>");
                        String unpaid = record.get("<unpaid_taken>");
                        String child = record.get("<child_bal>");

                        TitleDTO titleDto = titleBean.getTitleByName(title);
                        RoleDTO roleDto = accessBean.getRole(role);
                        DeptDTO deptDto = deptBean.getDepartment(dept);
                        //create the user first
                        UserDTO user = new UserDTO();
                        user.setName(name);
                        user.setLogin(login);
                        user.setTitle(titleDto);
                        user.setEmail(email);
                        user.setDateJoin(Utility.format(joinDate, "dd/MM/yyyy"));
                        user.setProbationDue(Utility.format(probDate, "dd/MM/yyyy"));
                        //store in user table.
                        userBean.createUser(user);
                        //assign role
                        userBean.assignRole(user, roleDto);
                        //assign dept
                        deptBean.assignEmployee(user, deptDto);

                        //leave ent
                        LeaveTypeDTO lvtypeDTO = leaveBean.getLeaveType("Annual");
                        LeaveEntDTO annualentDTO = new LeaveEntDTO();
                        annualentDTO.setCurrent(Double.parseDouble(annLeaveEnt));
                        annualentDTO.setBalance(Double.parseDouble(annBal));
                        annualentDTO.setMax(Double.parseDouble(annMax));
                        annualentDTO.setCarriedOver(Double.parseDouble(annCF));
                        annualentDTO.setLeaveType(lvtypeDTO);
                        //assign annual leave
                        annualentDTO.setUser(user);
                        leaveBean.addLeaveEnt(annualentDTO);
                        //medical ent
                        LeaveTypeDTO medTypeDTO = leaveBean.getLeaveType("Medical Leave");
                        LeaveEntDTO medentDTO = new LeaveEntDTO();
                        medentDTO.setBalance(medTypeDTO.getDays() - Double.parseDouble(med));
                        medentDTO.setCurrent(medTypeDTO.getDays());
                        medentDTO.setUser(user);
                        medentDTO.setLeaveType(medTypeDTO);
                        leaveBean.addLeaveEnt(medentDTO);
                        //oil ent
                        LeaveTypeDTO oilTypeDTO = leaveBean.getLeaveType("Off-in-Lieu");
                        LeaveEntDTO oilentDTO = new LeaveEntDTO();
                        oilentDTO.setBalance(oilTypeDTO.getDays() - Double.parseDouble(oil));
                        oilentDTO.setCurrent(0);
                        oilentDTO.setUser(user);
                        oilentDTO.setLeaveType(oilTypeDTO);
                        leaveBean.addLeaveEnt(oilentDTO);
                        //unpaid
                        LeaveTypeDTO unpaidTypeDTO = leaveBean.getLeaveType("Unpaid");
                        LeaveEntDTO unpaidentDTO = new LeaveEntDTO();
                        unpaidentDTO.setBalance(unpaidTypeDTO.getDays() - Double.parseDouble(unpaid));
                        unpaidentDTO.setCurrent(0);
                        unpaidentDTO.setUser(user);
                        unpaidentDTO.setLeaveType(unpaidTypeDTO);
                        leaveBean.addLeaveEnt(unpaidentDTO);
                        //child
                        LeaveTypeDTO childTypeDTO = leaveBean.getLeaveType("Child Care");
                        double cur = childTypeDTO.getDays();
                        LeaveEntDTO childentDTO = new LeaveEntDTO();
                        childentDTO.setBalance(cur - Double.parseDouble(child));
                        childentDTO.setCurrent(cur);
                        childentDTO.setUser(user);
                        childentDTO.setLeaveType(childTypeDTO);
                        leaveBean.addLeaveEnt(childentDTO);

                    }
                    /*
                    if (stockPrices.size() > 0) {
                       priceDAO.OpenConnection();
                       priceDAO.updateStockPrice(stockPrices);
                    }
                                */

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //priceDAO.CloseConnection();
            RequestDispatcher dispatcher = request.getRequestDispatcher("/employee");
            //request.setAttribute(Constants.TITLE, "Home");
            dispatcher.forward(request, response);
        }
    } else {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/uploadEmp.jsp");
        //request.setAttribute(Constants.TITLE, "Home");
        dispatcher.forward(request, response);

    }
}

From source file:jp.co.cyberagent.parquet.msgpack.CSVAsJSONIterator.java

@Override
public String next() {
    CSVRecord record = inner.next();
    StringWriter json = new StringWriter();
    try {//from   ww  w . j a  v  a2 s  . co m
        JsonGenerator gen = jsonFactory.createJsonGenerator(json);
        gen.writeStartObject();
        for (CSVHeaderMap.Entry entry : headerMap.entries()) {
            String name = entry.getName();
            String value = record.get(entry.getIndex());

            gen.writeFieldName(name);
            entry.getWriter().write(gen, value);
        }
        gen.writeEndObject();
        gen.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return json.toString();
}

From source file:com.kumarvv.setl.utils.CsvParser.java

/**
 * parse csv record/*from   ww  w  .j a  va  2s.  c  om*/
 * @param data
 * @param record
 */
protected void processRecord(final List<Map<String, Object>> data, final CSVRecord record) {
    if (data == null || record == null) {
        return;
    }

    final Map<String, Object> row = new HashMap<>();
    for (int i = 0; i < csv.getColumns().size(); i++) {
        if (i >= record.size()) {
            break;
        }
        row.put(csv.getColumns().get(i), record.get(i));
    }
    data.add(row);
}

From source file:com.objy.se.utils.TargetList.java

private Instance getTargetObjectForKyes(CSVRecord record, SingleKey... keys) {
    //    Object[] values = new Property[keys.length];
    List<Object> values = new ArrayList<>();
    for (SingleKey key : keys) {
        //values[i] = record.get(key.rawFileAttrName);
        String value = record.get(key.rawFileAttrName);
        //Variable var = targetClass.getCorrectValue(value, key.logicalType);
        values.add(targetClass.getCorrectValue(value, key.logicalType));
    }/*from   w w  w  .  j a v  a2s . c o m*/
    return getTargetObject(values);
}

From source file:br.edimarmanica.trinity.check.CheckAttributeNotFound.java

private void readOffSets() {
    /**//from   www  . j a v  a 2s.com
     * Lendos os Run02.NR_SHARED_PAGES primeiros elementos de cada offset
     */
    File dir = new File(Paths.PATH_TRINITY + site.getPath() + "/offset");

    for (int nrOffset = 0; nrOffset < dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".csv");
        }
    }).length; nrOffset++) {
        List<Map<String, String>> offset = new ArrayList<>(); //cada arquivo  um offset

        try (Reader in = new FileReader(dir.getAbsoluteFile() + "/result_" + nrOffset + ".csv")) {
            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 = formatValue(Preprocessing.filter(record.get(nrRegra)));
                        } catch (InvalidValue ex) {
                            value = "";
                        }

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

From source file:functions.LoadCSVdata.java

public void LoadData() {
    // ArrayList<Resident> residents = new ArrayList<>();
    try {/* ww w. jav  a2 s . com*/
        // READ FEE TABLE
        file = new File(PATH + FEE_FILE);
        System.out.println(file.toPath());
        parser = CSVParser.parse(file, Charset.forName("UTF-8"), CSVFormat.DEFAULT);
        Fee new_fee;
        Resident new_res;
        for (CSVRecord c : parser) {

            // skip first record
            if (c.getRecordNumber() == 1)
                continue;

            System.out.println(c.get(datatype.GlobalVariable.TYPE) + ", "
                    + c.get(datatype.GlobalVariable.AMOUNT) + ", " + c.get(datatype.GlobalVariable.PAID_BY)
                    + ", " + c.get(datatype.GlobalVariable.PAYER));
            String tmp = c.get(datatype.GlobalVariable.PAYER);
            //String payers;

            String[] payers = tmp.split(";");

            System.out.println(payers.length);
            new_fee = new Fee();
            new_fee.name = c.get(datatype.GlobalVariable.TYPE);
            new_fee.amount = Double.valueOf(c.get(datatype.GlobalVariable.AMOUNT));
            new_fee.number_of_payer = payers.length;

            System.out.println("new fee: " + new_fee.name);

            //datatype.GlobalVariable.FEES

            int res_index;
            // add payer

            for (int i = 0; i < payers.length; i++) {
                res_index = -1;
                for (Resident r : datatype.GlobalVariable.RESIDENTS) {
                    if (r.name.equals(payers[i])) {
                        res_index = datatype.GlobalVariable.RESIDENTS.indexOf(r);
                        break;
                    }
                }

                System.out.println(res_index);

                // new resident found
                if (res_index == -1) {
                    new_res = new Resident();

                    // System.out.println(payers[i]);
                    new_res.name = payers[i];
                    datatype.GlobalVariable.RESIDENTS.add(new_res);
                    res_index = datatype.GlobalVariable.RESIDENTS.indexOf(new_res);
                }

                // insert payer's fee
                //                    if(datatype.GlobalVariable.RESIDENTS.get(res_index).extra_fee.size()>=1)
                //                        System.out.println(datatype.GlobalVariable.RESIDENTS.get(res_index).extra_fee.get(datatype.GlobalVariable.RESIDENTS.get(res_index).extra_fee.size()-1).name);
                datatype.GlobalVariable.RESIDENTS.get(res_index).extra_fee.add(new_fee);
                //                    System.out.println(datatype.GlobalVariable.RESIDENTS.get(res_index).extra_fee.get(datatype.GlobalVariable.RESIDENTS.get(res_index).extra_fee.size()-1).name);
            }

            // add paid by

            res_index = -1;
            for (Resident r : datatype.GlobalVariable.RESIDENTS) {
                if (r.name.equals(c.get(datatype.GlobalVariable.PAID_BY))) {
                    res_index = datatype.GlobalVariable.RESIDENTS.indexOf(r);
                    break;
                }
            }

            // new resident found
            if (res_index == -1) {
                new_res = new Resident();

                new_res.name = c.get(datatype.GlobalVariable.PAID_BY);
                datatype.GlobalVariable.RESIDENTS.add(new_res);
                res_index = datatype.GlobalVariable.RESIDENTS.indexOf(new_res);
            }

            // insert paid
            datatype.GlobalVariable.RESIDENTS.get(res_index).paid.add(new_fee);

        }

        file = new File(PATH + RESIDENTS_FILE);
        // READ RESIDENT TABLE
        parser = CSVParser.parse(file, Charset.forName("UTF-8"), CSVFormat.DEFAULT);
        for (CSVRecord c : parser) {

            // skip first record
            if (c.getRecordNumber() == 1)
                continue;

            System.out
                    .println(c.get(datatype.GlobalVariable.NAME) + ", " + c.get(datatype.GlobalVariable.RENT));
            int res_index = -1;
            for (Resident r : datatype.GlobalVariable.RESIDENTS) {
                if (r.name.equals(c.get(datatype.GlobalVariable.NAME))) {
                    res_index = datatype.GlobalVariable.RESIDENTS.indexOf(r);
                    break;
                }
            }
            datatype.GlobalVariable.RESIDENTS.get(res_index).basic_rent = Integer
                    .parseInt(c.get(datatype.GlobalVariable.RENT));

        }

        //            for(int i=0;i<datatype.GlobalVariable.RESIDENTS.size();i++){
        //                System.out.println(datatype.GlobalVariable.RESIDENTS.get(i).name);
        //                for(Fee f:datatype.GlobalVariable.RESIDENTS.get(i).extra_fee){
        //                    System.out.println(f.name);
        //                }
        //            }

    } catch (Exception e) {
        System.out.println(e);
    }

    //return residents;
}

From source file:net.iaeste.iws.core.services.ExchangeCSVService.java

private void process(final Map<String, OfferCSVUploadResponse.ProcessingResult> processingResult,
        final Map<String, CSVProcessingErrors> errors, final Authentication authentication,
        final CSVRecord record) {
    final Map<String, String> conversionErrors = new HashMap<>(0);
    String refNo = "";

    try {/*from w  w  w.  j a v  a 2s  .  c o  m*/
        refNo = record.get(OfferFields.REF_NO.getField());
        final Offer csvOffer = extractOfferFromCSV(authentication, conversionErrors, record);

        final CSVProcessingErrors validationErrors = new CSVProcessingErrors(conversionErrors);
        if (validationErrors.isEmpty()) {
            processingResult.put(refNo, processOffer(authentication, refNo, csvOffer));
        } else {
            LOG.warn(formatLogMessage(authentication,
                    "CSV Offer with RefNo " + refNo + " has some Problems: " + conversionErrors));
            processingResult.put(refNo, OfferCSVUploadResponse.ProcessingResult.ERROR);
            errors.put(refNo, validationErrors);
        }
    } catch (IllegalArgumentException | IWSException e) {
        LOG.debug(e.getMessage(), e);
        LOG.warn(formatLogMessage(authentication,
                "CSV Offer with RefNo " + refNo + " has a Problem: " + e.getMessage()));
        processingResult.put(refNo, OfferCSVUploadResponse.ProcessingResult.ERROR);
        if (errors.containsKey(refNo)) {
            errors.get(refNo).put("general", e.getMessage());
        } else {
            final CSVProcessingErrors generalError = new CSVProcessingErrors();
            generalError.put("general", e.getMessage());
            if (!conversionErrors.isEmpty()) {
                generalError.putAll(conversionErrors);
            }
            errors.put(refNo, generalError);
        }
    }
}

From source file:com.wx3.galacdecks.Bootstrap.java

private void importSystems(GameDatastore datastore, String path) throws IOException {
    Reader reader = new FileReader(path);
    CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
    int count = 0;
    for (CSVRecord record : parser) {
        String id = record.get("id");
        String name = record.get("name");
        String description = record.get("description");
        String pvp = record.get("pvp");
        boolean usePlayerDecks = true;
        if (record.get("usePlayerDecks").toLowerCase().equals("n")) {
            usePlayerDecks = false;//www.j  a  v a  2 s  .  c  om
        }

        String ruleField = record.get("rootRules");
        String[] ruleIds = ruleField.split(",");
        GameSystem system = new GameSystem();
        system.id = id;
        system.name = name;
        system.description = description;
        system.usePlayerDecks = usePlayerDecks;
        system.rootRules = new ArrayList<>(Arrays.asList(ruleIds));
        if (pvp.toUpperCase().equals("Y")) {
            system.pvp = true;
        } else {
            system.pvp = false;
        }
        datastore.createSystem(system);

        ++count;
    }
    logger.info("Imported " + count + " systems");
    parser.close();
}