Example usage for org.apache.poi.ss.usermodel Row cellIterator

List of usage examples for org.apache.poi.ss.usermodel Row cellIterator

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Row cellIterator.

Prototype

Iterator<Cell> cellIterator();

Source Link

Usage

From source file:com.consensus.qa.framework.ExcelOperations.java

@SuppressWarnings("unused")
public AccountDetails GetAccountDetails(FileNames fileName, SheetName worksheetName) throws IOException {
    String filePath = FilePath(fileName);
    fileInput = new FileInputStream(new File(filePath));
    workBook = new XSSFWorkbook(fileInput);
    XSSFSheet workSheet = GetSheetFromWorkBook(workBook, worksheetName.toString());
    AccountDetails accountDetails = new AccountDetails();

    try {/* ww w  .ja  v  a  2s .  c o  m*/
        int mtnIndex = -1;
        int passwordIndex = -1;
        int ssnIndex = -1;
        int statusCol = -1;
        Row row = workSheet.getRow(0);
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            if (String.valueOf(cell.getStringCellValue()).contains("MTN")) {
                mtnIndex = cell.getColumnIndex();
            } else if (String.valueOf(cell.getStringCellValue()).contains("Password")) {
                passwordIndex = cell.getColumnIndex();
            } else if (String.valueOf(cell.getStringCellValue()).contains("SSN")) {
                ssnIndex = cell.getColumnIndex();
            } else if (String.valueOf(cell.getStringCellValue()).contains(Status.STATUS.toString())) {
                statusCol = cell.getColumnIndex();
            }
            if (mtnIndex != -1 && passwordIndex != -1 && ssnIndex != -1 && statusCol != -1) {
                break;
            }
        }
        if (statusCol == -1) {
            statusCol = (workSheet.getRow(0).getPhysicalNumberOfCells());
            Cell cell = workSheet.getRow(0).createCell(statusCol);
            cell.setCellValue(Status.STATUS.toString());
        }
        for (int i = 1; i < workSheet.getPhysicalNumberOfRows(); i++) {
            Cell cell = null;
            if (workSheet.getRow(i).getCell(statusCol) == null
                    || (workSheet.getRow(i).getCell(statusCol).getCellType() == Cell.CELL_TYPE_BLANK)) {
                cell = workSheet.getRow(i).createCell(statusCol);
                cell.setCellValue(Status.UNUSED.toString());
            }
            cell = workSheet.getRow(i).getCell(statusCol);
            if (cell.getStringCellValue().toString().equals(Status.UNUSED.toString())) {
                accountDetails.MTN = String
                        .valueOf(workSheet.getRow(i).getCell(mtnIndex).getNumericCellValue());
                accountDetails.Password = workSheet.getRow(i).getCell(passwordIndex).getStringCellValue();
                accountDetails.SSN = String
                        .valueOf(workSheet.getRow(i).getCell(ssnIndex).getNumericCellValue());

                cell.setCellValue(Status.INUSE.toString());
                break;
            }
        }
    }

    catch (Exception ex) {
        ex.printStackTrace();
    }

    finally {
        WriteAndCloseFile(filePath, fileInput, workBook);
    }

    if (accountDetails == null)
        Log.error("FAILED To get account details; one among MTN/Password/SSN is blank");
    return accountDetails;
}

From source file:com.consensus.qa.framework.ExcelOperations.java

@SuppressWarnings("unused")
public NPANXX GetNumberPortData(FileNames fileName, SheetName workSheetName) throws IOException {
    String filePath = FilePath(fileName);
    fileInput = new FileInputStream(new File(filePath));
    workBook = new XSSFWorkbook(fileInput);
    XSSFSheet workSheet = GetSheetFromWorkBook(workBook, workSheetName.toString());
    NPANXX npaNXX = new NPANXX();

    try {//from   w w w .  j  a v a2s.  c o  m
        int mtnIndex = -1;
        int passwordIndex = -1;
        int ssnIndex = -1;
        int statusCol = -1;
        Row row = workSheet.getRow(0);
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            if (String.valueOf(cell.getStringCellValue()).contains("NGP")) {
                mtnIndex = cell.getColumnIndex();
            } else if (String.valueOf(cell.getStringCellValue()).contains("Location")) {
                passwordIndex = cell.getColumnIndex();
            } else if (String.valueOf(cell.getStringCellValue()).contains("NPANXX")) {
                ssnIndex = cell.getColumnIndex();
            } else if (String.valueOf(cell.getStringCellValue()).contains(Status.STATUS.toString())) {
                statusCol = cell.getColumnIndex();
            }
            if (mtnIndex != -1 && passwordIndex != -1 && ssnIndex != -1 && statusCol != -1) {
                break;
            }
        }
        if (statusCol == -1) {
            statusCol = (workSheet.getRow(0).getPhysicalNumberOfCells());
            Cell cell = workSheet.getRow(0).createCell(statusCol);
            cell.setCellValue(Status.STATUS.toString());
        }
        for (int i = 1; i < workSheet.getPhysicalNumberOfRows(); i++) {
            Cell cell = null;
            if (workSheet.getRow(i).getCell(statusCol) == null
                    || (workSheet.getRow(i).getCell(statusCol).getCellType() == Cell.CELL_TYPE_BLANK)) {
                cell = workSheet.getRow(i).createCell(statusCol);
                cell.setCellValue(Status.UNUSED.toString());
            }
            cell = workSheet.getRow(i).getCell(statusCol);
            if (cell.getStringCellValue().toString().equals(Status.UNUSED.toString())) {
                npaNXX.NGP = String.valueOf(workSheet.getRow(i).getCell(mtnIndex).getNumericCellValue());
                npaNXX.Location = workSheet.getRow(i).getCell(passwordIndex).getStringCellValue();
                npaNXX.NPANXX = String.valueOf(workSheet.getRow(i).getCell(ssnIndex).getNumericCellValue());

                cell.setCellValue(Status.INUSE.toString());
                break;
            }
        }
    }

    catch (Exception ex) {
        ex.printStackTrace();
    }

    finally {
        WriteAndCloseFile(filePath, fileInput, workBook);
    }

    if (npaNXX == null)
        Log.error("FAILED To get account details; one among MTN/Password/SSN is blank");
    return npaNXX;
}

From source file:com.creditcloud.carinsurance.CarInsuranceFeeServiceBean.java

/**
 * ??//from   www  .  j  a  v  a 2s. c o m
 *
 * @param feeFileExcel
 */
public void bacthUpdateCarInsuranceFeeSatatus(File feeFileExcel) {
    try {
        FileInputStream file = new FileInputStream(feeFileExcel);
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        String insuranceNum = "";
        int currentPeriod = 0;
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    currentPeriod = (int) cell.getNumericCellValue();
                    System.out.print((int) cell.getNumericCellValue() + "\t");
                    break;
                case Cell.CELL_TYPE_STRING:
                    insuranceNum = cell.getStringCellValue().trim();
                    System.out.print(cell.getStringCellValue() + "\t");
                    break;
                }
            }
            CarInsuranceFee fee = carInsuranceFeeDAO.findByInSuranceNumAndCurrentPeriod(insuranceNum,
                    currentPeriod);
            //?
            if (fee != null) {
                updateCarInsuranceFeeSatatus(fee.getId(), CarInsuranceStatus.CLEARED);
            }
            System.out.println("");
        }
        file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.cseur.utils.ExcelReader.java

public ArrayList<ArrayList<String>> readToMap() throws IOException {

    FileInputStream file = new FileInputStream(xlsFile);
    //Get the workbook instance for XLS file 
    HSSFWorkbook workbook = new HSSFWorkbook(file);

    //Get first sheet from the workbook
    HSSFSheet sheet = workbook.getSheetAt(0);

    //get pol pod via1 via2 via3 via4 index in column and saved to array
    ArrayList<Integer> portIndexs = new ArrayList(Arrays.asList(null, null, null, null, null, null, null));
    boolean isTableHeader = true;
    //Iterate through each rows one by one
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        //read file, find the columnindex for required order, and then insert the value to valueArray.
        Row row = rowIterator.next();
        //            //escape empty lines
        Iterator<Cell> cellIterator = row.cellIterator();
        if (isTableHeader) {
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                //set absolute columnIndex in the order of POL, POD, VIA1.2.l.3.4
                switch (cell.getStringCellValue().trim().toUpperCase()) {
                case "POL":
                    portIndexs.set(0, cell.getColumnIndex());
                    break;
                case "POD":
                    portIndexs.set(1, cell.getColumnIndex());
                    break;
                case "VIA1":
                    portIndexs.set(2, cell.getColumnIndex());
                    break;
                case "VIA2":
                    portIndexs.set(3, cell.getColumnIndex());
                    break;
                case "VIA3":
                    portIndexs.set(4, cell.getColumnIndex());
                    break;
                case "VIA4":
                    portIndexs.set(5, cell.getColumnIndex());
                    break;
                //                    case "VIA5":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA6":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA7":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA8":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA9":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                //                    case "VIA0":
                //                            portIndexs.add(cell.getColumnIndex());
                //                        break;
                }//from   ww  w .  ja  va 2s  .c  om
                //                    portIndexs.trimToSize();
            }
        }
        if (!isTableHeader) {
            ArrayList<String> valueArrayList = new ArrayList<>();
            for (int i = 0; portIndexs.get(i) != null; i++) {
                if (row.getCell(portIndexs.get(i)) != null
                        && !row.getCell(portIndexs.get(i)).getStringCellValue().isEmpty()) {
                    valueArrayList
                            .add(row.getCell(portIndexs.get(i)).getStringCellValue().trim().toUpperCase());
                }
            }
            System.out.println(valueArrayList.size());
            valueArrayList_X.add(valueArrayList);
            //reference added to arraylist. clear the valueArrayList remove the values in valueArrayList_X Too!!
            //valueArrayList.clear();
        }
        isTableHeader = false;//add contents to vector.
    }
    file.close();
    return valueArrayList_X;
}

From source file:com.ddt.driver.EXCELDriver.java

private void readOlderVersionExcelFile(String path, String sheetName) {
    try {/* ww  w  .  j  a  va 2 s. c om*/

        HSSFWorkbook workbook;

        try (FileInputStream file = new FileInputStream(new File(path))) {

            workbook = new HSSFWorkbook(file);
            HSSFSheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {
                String line = "";
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();

                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        line += cell.getBooleanCellValue() + ";";
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        line += String.valueOf(cell.getNumericCellValue()).split("\\.")[0] + ";";
                        break;
                    case Cell.CELL_TYPE_STRING:
                        line += cell.getStringCellValue() + ";";
                        break;
                    }
                }
                linesOfDriver.add(line);
            }
        }
    } catch (FileNotFoundException e) {
        Logger.getLogger(EXCELDriver.class.getName()).log(Level.SEVERE, null, e);
    } catch (IOException e) {
        Logger.getLogger(EXCELDriver.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:com.ddt.driver.EXCELDriver.java

private void readNewerVersionExcelFile(String path, String sheetName) {
    try {/*from   w  w w  . j  av a  2s . c  o  m*/
        try (final FileInputStream file = new FileInputStream(new File(path))) {
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = getSheetName(sheetName, workbook);
            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext()) {
                String line = "";
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();

                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        line += cell.getBooleanCellValue() + ";";
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        line += String.valueOf(cell.getNumericCellValue()).split("\\.")[0] + ";";
                        break;
                    case Cell.CELL_TYPE_STRING:
                        line += cell.getStringCellValue() + ";";
                        break;
                    }
                }
                linesOfDriver.add(line);
            }
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(EXCELDriver.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(EXCELDriver.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.dexter.fms.mbean.FleetMBean.java

License:Open Source License

@SuppressWarnings("unchecked")
public void UploadZonMaintenance() {
    if (getMaintenanceExcel() != null) {
        GeneralDAO gDAO = new GeneralDAO();
        try {//from   ww  w.  ja v a 2s  .c  o m
            ByteArrayInputStream byteIn = new ByteArrayInputStream(getMaintenanceExcel().getContents());
            //Get the workbook instance for XLS file
            HSSFWorkbook workbook = new HSSFWorkbook(byteIn);
            //Get first sheet from the workbook
            HSSFSheet sheet = workbook.getSheetAt(0);

            //Get iterator to all the rows in current sheet starting from row 2
            Iterator<Row> rowIterator = sheet.iterator();
            int pos = 1;
            gDAO.startTransaction();
            boolean ret = false;
            while (rowIterator.hasNext()) {
                String timestamp = null, unit = null, comment1 = null, comment2 = null, comment3 = null,
                        value = null, updateTime = null;
                Row row = rowIterator.next();
                if (pos > 1) {
                    //Get iterator to all cells of current row
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        String val = "";
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_BLANK:
                            val = "";
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            val = "" + cell.getBooleanCellValue();
                            break;
                        case Cell.CELL_TYPE_ERROR:
                            val = "";
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            val = "" + cell.getNumericCellValue();
                            break;
                        case Cell.CELL_TYPE_STRING:
                            val = cell.getStringCellValue();
                            break;
                        default: {
                            try {
                                val = cell.getStringCellValue();
                            } catch (Exception ex) {
                            }
                            break;
                        }
                        }
                        switch (cell.getColumnIndex()) {
                        case 0:
                            timestamp = val;
                            break;
                        case 1:
                            unit = val;
                            break;
                        case 2:
                            comment1 = val;
                            break;
                        case 3:
                            comment2 = val;
                            break;
                        case 4:
                            comment3 = val;
                            break;
                        case 5:
                            value = val;
                            break;
                        case 7:
                            updateTime = val;
                            break;
                        }
                        String regNo = null;
                        Vehicle v = null;
                        Vendor vendor = null;
                        try {
                            if (unit != null && unit.contains("-")) {
                                regNo = unit.substring(0, unit.indexOf("-"));
                            } else if (unit != null)
                                regNo = unit;

                            if (regNo != null)
                                regNo = regNo.trim();
                        } catch (Exception ex) {
                            System.out.println("Reg No parsing exception on row index: " + pos);
                            ex.printStackTrace();
                        }
                        if (regNo != null) {
                            Query q = gDAO.createQuery(
                                    "Select e from Vehicle e where e.registrationNo=:regNo and e.partner.id=:partner_id");
                            q.setParameter("regNo", regNo);
                            q.setParameter("partner_id", partner_id);
                            Object vobj = gDAO.search(q, 1);
                            if (vobj != null) {
                                v = (Vehicle) vobj;
                            }
                        }
                        if (v != null) {
                            if (comment2 != null && comment2.trim().length() > 0) {
                                Query q = gDAO.createQuery(
                                        "Select e from Vendor e where e.name=:vname and e.partner.id=:partner_id");
                                q.setParameter("vname", comment2);
                                q.setParameter("partner_id", partner_id);
                                Object venobjs = gDAO.search(q, 0);
                                if (venobjs != null) {
                                    List<Vendor> venlist = (List<Vendor>) venobjs;
                                    for (Vendor e : venlist)
                                        vendor = e;
                                }
                                if (vendor == null) {
                                    vendor = new Vendor();
                                    vendor.setCreatedBy(dashBean.getUser());
                                    vendor.setCrt_dt(new Date());
                                    vendor.setName(comment2);
                                    vendor.setPartner(getPartner());
                                    gDAO.save(vendor);
                                }
                            }
                            Date start_dt = null, end_dt = null;
                            if (comment3 != null && comment3.trim().length() > 0) {

                            }

                            if (comment1 != null && comment1.trim().length() > 0
                                    && comment1.startsWith("Routine Service")) {
                                VehicleRoutineMaintenance vrm = new VehicleRoutineMaintenance();

                            } else if (comment1 != null && comment1.trim().length() > 0) {
                                VehicleAdHocMaintenance vahm = new VehicleAdHocMaintenance();
                            }
                        }
                    }
                }
                pos += 1;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        gDAO.destroy();
    }
}

From source file:com.dexter.fms.mbean.FleetMBean.java

License:Open Source License

@SuppressWarnings("unchecked")
public void BatchLoadVehicles() {
    if (getVehiclesBatchExcel() != null) {
        String naration = "Batch load vehicles: ";
        GeneralDAO gDAO = new GeneralDAO();
        try {//from   w  w  w .  j a v  a2 s.  c  om
            ByteArrayInputStream byteIn = new ByteArrayInputStream(getVehiclesBatchExcel().getContents());
            //Get the workbook instance for XLS file
            HSSFWorkbook workbook = new HSSFWorkbook(byteIn);
            //Get first sheet from the workbook
            HSSFSheet sheet = workbook.getSheetAt(0);

            //Get iterator to all the rows in current sheet starting from row 2
            Iterator<Row> rowIterator = sheet.iterator();
            int pos = 1;

            gDAO.startTransaction();
            boolean ret = false;
            while (rowIterator.hasNext()) {
                if (!isLicenseAvailable()) {
                    msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed: ",
                            "You have used up your license. Please purchase more license to add more vehicles!");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    break;
                }

                Row row = rowIterator.next();
                String fleet_nm = "", vehicleType = "", vehicleMaker = "", vehicleModel = "", modelYr = "",
                        trackerID = "", regNo = "", engineNo = "", chassisNo = "";
                String department = "", region = "";
                String purchase_date = "", purchased_amount = "", purchased_from = "", fuel_type = "",
                        tyre_size = "", tank_capacity = "";
                String calibrated_capacity = "", color = "", sim_no = "", unit_of_measurement = "",
                        card_no = "";
                if (pos > 1) {
                    //Get iterator to all cells of current row
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        String val = "";
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_BLANK:
                            val = "";
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            val = "" + cell.getBooleanCellValue();
                            break;
                        case Cell.CELL_TYPE_ERROR:
                            val = "";
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            val = "" + cell.getNumericCellValue();
                            break;
                        case Cell.CELL_TYPE_STRING:
                            val = cell.getStringCellValue();
                            break;
                        default: {
                            try {
                                val = cell.getStringCellValue();
                            } catch (Exception ex) {
                            }
                            break;
                        }
                        }
                        switch (cell.getColumnIndex()) {
                        case 0:
                            fleet_nm = val;
                            break;
                        case 1:
                            vehicleType = val;
                            break;
                        case 2:
                            vehicleMaker = val;
                            break;
                        case 3:
                            vehicleModel = val;
                            break;
                        case 4:
                            modelYr = val;
                            break;
                        case 5:
                            trackerID = val;
                            break;
                        case 6:
                            regNo = val;
                            break;
                        case 7:
                            engineNo = val;
                            break;
                        case 8:
                            chassisNo = val;
                            break;
                        case 9:
                            department = val;
                            break;
                        case 10:
                            region = val;
                            break;
                        case 11:
                            purchase_date = val;
                            break;
                        case 12:
                            purchased_amount = val;
                            break;
                        case 13:
                            purchased_from = val;
                            break;
                        case 14:
                            fuel_type = val;
                            break;
                        case 15:
                            tyre_size = val;
                            break;
                        case 16:
                            tank_capacity = val;
                            break;
                        case 17:
                            calibrated_capacity = val;
                            break;
                        case 18:
                            color = val;
                            break;
                        case 19:
                            sim_no = val;
                            break;
                        case 20:
                            unit_of_measurement = val;
                            break;
                        case 21:
                            card_no = val;
                            break;
                        }
                    }

                    boolean createModel = false;
                    VehicleType vt = null;
                    VehicleMake vm = null;
                    VehicleModel vmd = null;

                    Fleet fleet = null;
                    Department deptObj = null;
                    Region regionObj = null;

                    boolean conti = true;

                    if (regNo != null && regNo.trim().length() > 0) {
                        Vehicle v = null;
                        Query q = gDAO.createQuery(
                                "Select e from Vehicle e where e.registrationNo = :registrationNo");
                        q.setParameter("registrationNo", regNo);
                        Object vObj = gDAO.search(q, 0);
                        if (vObj != null) {
                            Vector<Vehicle> vList = (Vector<Vehicle>) vObj;
                            for (Vehicle e : vList)
                                v = e;
                        }
                        if (v != null)
                            conti = false;
                    }
                    if (conti) {
                        if (fleet_nm != null && fleet_nm.trim().length() > 0) {
                            Query q = gDAO.createQuery(
                                    "Select e from Fleet e where e.partner = :partner and e.name = :name");
                            q.setParameter("partner", getPartner());
                            q.setParameter("name", fleet_nm);
                            Object objs = gDAO.search(q, 0);
                            if (objs != null) {
                                Vector<Fleet> objsList = (Vector<Fleet>) objs;
                                for (Fleet e : objsList)
                                    fleet = e;
                            }
                            if (fleet == null && isAutoCreate()) {
                                fleet = new Fleet();
                                fleet.setCreatedBy(dashBean.getUser());
                                fleet.setCrt_dt(new Date());
                                fleet.setName(fleet_nm);
                                fleet.setPartner(getPartner());
                                fleet.setDefaultFleet(false);
                                ret = gDAO.save(fleet);
                                if (!ret)
                                    break;
                            } else if (fleet == null && !isAutoCreate()) {
                                ret = false;
                                gDAO.setMessage(
                                        "Fleet: '" + fleet_nm + "' does not exist for vehicle: " + regNo);
                                break;
                            }
                        }

                        if (department != null && department.trim().length() > 0) {
                            Query q = gDAO.createQuery(
                                    "Select e from Department e where e.partner = :partner and e.name = :name");
                            q.setParameter("partner", getPartner());
                            q.setParameter("name", department);
                            Object objs = gDAO.search(q, 0);
                            if (objs != null) {
                                Vector<Department> objsList = (Vector<Department>) objs;
                                for (Department e : objsList)
                                    deptObj = e;
                            }
                            if (deptObj == null && isAutoCreate()) {
                                deptObj = new Department();
                                deptObj.setCreatedBy(dashBean.getUser());
                                deptObj.setCrt_dt(new Date());
                                deptObj.setName(department);
                                deptObj.setPartner(getPartner());
                                ret = gDAO.save(deptObj);
                                if (!ret)
                                    break;
                            } else if (deptObj == null && !isAutoCreate()) {
                                ret = false;
                                gDAO.setMessage("Department: '" + department + "' does not exist for vehicle: "
                                        + regNo);
                                break;
                            }
                        }

                        if (region != null && region.trim().length() > 0) {
                            Query q = gDAO.createQuery(
                                    "Select e from Region e where e.partner = :partner and e.name = :name");
                            q.setParameter("partner", getPartner());
                            q.setParameter("name", region);
                            Object objs = gDAO.search(q, 0);
                            if (objs != null) {
                                Vector<Region> objsList = (Vector<Region>) objs;
                                for (Region e : objsList)
                                    regionObj = e;
                            }
                            if (regionObj == null && isAutoCreate()) {
                                regionObj = new Region();
                                regionObj.setCreatedBy(dashBean.getUser());
                                regionObj.setCrt_dt(new Date());
                                regionObj.setName(region);
                                regionObj.setPartner(getPartner());
                                ret = gDAO.save(regionObj);
                                if (!ret)
                                    break;
                            } else if (regionObj == null && !isAutoCreate()) {
                                ret = false;
                                gDAO.setMessage(
                                        "Region: '" + region + "' does not exist for vehicle: " + regNo);
                                break;
                            }
                        }

                        if (vehicleType != null && vehicleType.trim().length() > 0) {
                            // search for existing vehicle type and maker
                            Query q = gDAO.createQuery("Select e from VehicleType e where e.name = :name");
                            q.setParameter("name", vehicleType.trim());
                            Object qObj = gDAO.search(q, 0);
                            if (qObj != null) {
                                Vector<VehicleType> vtList = (Vector<VehicleType>) qObj;
                                for (VehicleType e : vtList)
                                    vt = e;
                            }
                            if (vt == null && isAutoCreate()) {
                                vt = new VehicleType();
                                vt.setCreatedBy(dashBean.getUser());
                                vt.setCrt_dt(new Date());
                                vt.setName(vehicleType.trim());
                                vt.setPartner(getPartner());
                                ret = gDAO.save(vt);
                                if (!ret)
                                    break;
                                createModel = true;
                            } else if (vt == null && !isAutoCreate()) {
                                ret = false;
                                gDAO.setMessage("Vehicle Type: '" + vehicleType
                                        + "' does not exist for vehicle: " + regNo);
                                break;
                            }
                        }

                        if (vehicleMaker != null && vehicleMaker.trim().length() > 0) {
                            Query q = gDAO.createQuery("Select e from VehicleMake e where e.name = :name");
                            q.setParameter("name", vehicleMaker.trim());
                            Object qObj = gDAO.search(q, 0);
                            if (qObj != null) {
                                Vector<VehicleMake> vmList = (Vector<VehicleMake>) qObj;
                                for (VehicleMake e : vmList)
                                    vm = e;
                            }
                            if (vm == null && isAutoCreate()) {
                                vm = new VehicleMake();
                                vm.setCreatedBy(dashBean.getUser());
                                vm.setCrt_dt(new Date());
                                vm.setName(vehicleMaker.trim());
                                vm.setPartner(getPartner());
                                ret = gDAO.save(vm);
                                if (!ret)
                                    break;
                                createModel = true;
                            } else if (vm == null && !isAutoCreate()) {
                                ret = false;
                                gDAO.setMessage("Vehicle Make: '" + vehicleMaker
                                        + "' does not exist for vehicle: " + regNo);
                                break;
                            }
                        }

                        if (vehicleModel != null && vehicleModel.trim().length() > 0) {
                            if (createModel) {
                                vmd = new VehicleModel();
                                vmd.setCreatedBy(dashBean.getUser());
                                vmd.setCrt_dt(new Date());
                                vmd.setMaker(vm);
                                vmd.setType(vt);
                                vmd.setName(vehicleModel);
                                vmd.setYear(modelYr);
                                vmd.setPartner(getPartner());
                                ret = gDAO.save(vmd);
                                if (!ret)
                                    break;
                            } else {
                                Query q = gDAO.createQuery(
                                        "Select e from VehicleModel e where e.name = :name and e.year=:year and e.maker=:maker and e.type=:type");
                                q.setParameter("name", vehicleModel.trim());
                                q.setParameter("year", modelYr);
                                q.setParameter("maker", vm);
                                q.setParameter("type", vt);
                                Object qObj = gDAO.search(q, 0);
                                if (qObj != null) {
                                    Vector<VehicleModel> vmList = (Vector<VehicleModel>) qObj;
                                    for (VehicleModel e : vmList)
                                        vmd = e;
                                }
                                if (vmd == null && isAutoCreate()) {
                                    vmd = new VehicleModel();
                                    vmd.setCreatedBy(dashBean.getUser());
                                    vmd.setCrt_dt(new Date());
                                    vmd.setMaker(vm);
                                    vmd.setType(vt);
                                    vmd.setName(vehicleModel);
                                    vmd.setYear(modelYr);
                                    vmd.setPartner(getPartner());
                                    ret = gDAO.save(vmd);
                                    if (!ret)
                                        break;
                                } else if (vmd == null && !isAutoCreate()) {
                                    ret = false;
                                    gDAO.setMessage("Vehicle Model: '" + vehicleModel
                                            + "' does not exist for vehicle: " + regNo);
                                    break;
                                }
                            }
                        }

                        Vendor ven = null;
                        if (purchased_from != null && purchased_from.trim().length() > 0) {
                            Query q = gDAO.createQuery(
                                    "Select e from Vendor e where e.name = :name and e.partner=:partner");
                            q.setParameter("name", vehicleModel.trim());
                            q.setParameter("partner", getPartner());
                            Object qObj = gDAO.search(q, 0);
                            if (qObj != null) {
                                Vector<Vendor> vmList = (Vector<Vendor>) qObj;
                                for (Vendor e : vmList)
                                    ven = e;
                            }
                            if (ven == null && isAutoCreate()) {
                                ven = new Vendor();
                                ven.setName(purchased_from);
                                ven.setPartner(getPartner());
                                ven.setCreatedBy(dashBean.getUser());
                                ven.setCrt_dt(new Date());
                                ret = gDAO.save(ven);
                                if (!ret)
                                    break;
                                else {
                                    ServiceType st = null;
                                    q = gDAO.createQuery("Select e from ServiceType e where e.name = :name");
                                    q.setParameter("name", "Vehicle Sales");
                                    qObj = gDAO.search(q, 0);
                                    if (qObj != null) {
                                        Vector<ServiceType> vmList = (Vector<ServiceType>) qObj;
                                        for (ServiceType e : vmList)
                                            st = e;
                                    }
                                    if (st != null) {
                                        VendorServices vs = new VendorServices();
                                        vs.setCreatedBy(dashBean.getUser());
                                        vs.setCrt_dt(new Date());
                                        vs.setServiceType(st);
                                        vs.setVendor(ven);
                                        ret = gDAO.save(vs);
                                        if (!ret)
                                            break;
                                    }
                                }
                            }
                        }

                        if (fleet != null && vt != null && vm != null && vmd != null) {
                            Vehicle v = new Vehicle();
                            v.setFleet(fleet);
                            v.setActive(true);
                            v.setActiveStatus(VehicleStatusEnum.ACTIVE.getStatus());
                            v.setChasisNo(chassisNo);
                            v.setCreatedBy(dashBean.getUser());
                            v.setCrt_dt(new Date());
                            v.setEngineNo(engineNo);
                            v.setModel(vmd);
                            v.setPartner(getPartner());
                            v.setRegistrationNo(regNo);
                            v.setZonControlId(trackerID);
                            /*try
                            {
                               v.setZonControlId(Integer.parseInt(trackerID));
                            } catch(Exception ex){}*/
                            try {
                                v.setPurchaseAmt(new BigDecimal(Double.parseDouble(purchased_amount)));
                            } catch (Exception ex) {
                            }
                            try {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                v.setPurchaseDate(sdf.parse(purchase_date));
                            } catch (Exception ex) {
                            }
                            v.setVendor(ven);
                            ret = gDAO.save(v);
                            if (!ret)
                                break;
                            else if (regionObj != null || deptObj != null) {
                                VehicleParameters vpm = new VehicleParameters();
                                vpm.setRegion(regionObj);
                                vpm.setDept(deptObj);
                                try {
                                    vpm.setCalibratedcapacity(Double.parseDouble(calibrated_capacity));
                                } catch (Exception ex) {
                                }
                                vpm.setCardno(card_no);
                                vpm.setColor(color);
                                vpm.setSimno(sim_no);
                                try {
                                    vpm.setTankcapacity(Double.parseDouble(tank_capacity));
                                } catch (Exception ex) {
                                }
                                vpm.setTyresize(tyre_size);
                                vpm.setUnitofmeasure(unit_of_measurement);

                                if (fuel_type != null && fuel_type.trim().length() > 0) {
                                    Query q = gDAO.createQuery("Select e from FuelType e where e.name = :name");
                                    q.setParameter("name", fuel_type);
                                    Object qObj = gDAO.search(q, 0);
                                    if (qObj != null) {
                                        Vector<FuelType> vmList = (Vector<FuelType>) qObj;
                                        for (FuelType e : vmList)
                                            vpm.setFuelType(e);
                                    }
                                }
                                vpm.setCreatedBy(dashBean.getUser());
                                vpm.setCrt_dt(new Date());
                                vpm.setVehicle(v);
                                ret = gDAO.save(vpm);
                                if (!ret)
                                    break;
                            }
                        }
                    }
                } else
                    pos += 1;
            }

            if (ret) {
                gDAO.commit();
                naration += ", Status: Success";
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success: ",
                        "All vehicles created successfully.");
                FacesContext.getCurrentInstance().addMessage(null, msg);

                setVehicleMakes(null);
                setVehicleTypes(null);
                setVmodels(null);
            } else {
                gDAO.rollback();
                naration += ", Status: Failed: " + gDAO.getMessage();
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed: ",
                        "Failed to create all vehicles: " + gDAO.getMessage());
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error: ",
                    "Severe error occured. " + ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } finally {
            gDAO.destroy();
            dashBean.saveAudit(naration, "", null);
        }
    }
}

From source file:com.dexter.fms.mbean.FleetMBean.java

License:Open Source License

@SuppressWarnings("unchecked")
public void BatchLoadVModels() {
    if (getModelsBatchExcel() != null) {
        String naration = "Batch load vehicle models: ";
        GeneralDAO gDAO = new GeneralDAO();
        try {//from  www. j  a v a2s.c  o  m
            ByteArrayInputStream byteIn = new ByteArrayInputStream(getModelsBatchExcel().getContents());
            //Get the workbook instance for XLS file
            HSSFWorkbook workbook = new HSSFWorkbook(byteIn);
            //Get first sheet from the workbook
            HSSFSheet sheet = workbook.getSheetAt(0);

            //Get iterator to all the rows in current sheet starting from row 2
            Iterator<Row> rowIterator = sheet.iterator();
            int pos = 1;

            gDAO.startTransaction();
            boolean ret = false;
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                String model_nm = "", vehicleType = "", vehicleMaker = "";
                String model_yr = "";
                if (pos > 1) {
                    //Get iterator to all cells of current row
                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();
                        String val = "";
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_BLANK:
                            val = "";
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            val = "" + cell.getBooleanCellValue();
                            break;
                        case Cell.CELL_TYPE_ERROR:
                            val = "";
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            val = "" + cell.getNumericCellValue();
                            break;
                        case Cell.CELL_TYPE_STRING:
                            val = cell.getStringCellValue();
                            break;
                        default: {
                            try {
                                val = cell.getStringCellValue();
                            } catch (Exception ex) {
                            }
                            break;
                        }
                        }
                        if (cell.getColumnIndex() == 0)
                            model_nm = val;
                        else if (cell.getColumnIndex() == 1)
                            model_yr = val;
                        else if (cell.getColumnIndex() == 2)
                            vehicleType = val;
                        else if (cell.getColumnIndex() == 3)
                            vehicleMaker = val;
                    }

                    VehicleType vt = null;
                    VehicleMake vm = null;
                    VehicleModel vmd = new VehicleModel();

                    // search for existing vehicle type and maker
                    Query q = gDAO.createQuery("Select e from VehicleType e where e.name = :name");
                    q.setParameter("name", vehicleType.trim());
                    Object qObj = gDAO.search(q, 0);
                    if (qObj != null) {
                        Vector<VehicleType> vtList = (Vector<VehicleType>) qObj;
                        for (VehicleType e : vtList)
                            vt = e;
                    }
                    if (vt == null && isAutoCreate()) {
                        vt = new VehicleType();
                        vt.setCreatedBy(dashBean.getUser());
                        vt.setPartner(dashBean.getUser().getPartner());
                        vt.setCrt_dt(new Date());
                        vt.setName(vehicleType.trim());
                        gDAO.save(vt);
                    }
                    q = gDAO.createQuery("Select e from VehicleMake e where e.name = :name");
                    q.setParameter("name", vehicleMaker.trim());
                    qObj = gDAO.search(q, 0);
                    if (qObj != null) {
                        Vector<VehicleMake> vmList = (Vector<VehicleMake>) qObj;
                        for (VehicleMake e : vmList)
                            vm = e;
                    }
                    if (vm == null && isAutoCreate()) {
                        vm = new VehicleMake();
                        vm.setCreatedBy(dashBean.getUser());
                        vm.setPartner(dashBean.getUser().getPartner());
                        vm.setCrt_dt(new Date());
                        vm.setName(vehicleMaker.trim());
                        gDAO.save(vm);
                    }

                    vmd.setType(vt);
                    vmd.setMaker(vm);
                    vmd.setCreatedBy(dashBean.getUser());
                    vmd.setPartner(dashBean.getUser().getPartner());
                    vmd.setCrt_dt(new Date());
                    vmd.setName(model_nm);
                    vmd.setYear(model_yr);
                    ret = gDAO.save(vmd);
                    if (!ret)
                        break;
                } else
                    pos += 1;
            }
            if (ret) {
                gDAO.commit();
                naration += "Status: Success";
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success: ",
                        "All models created successfully.");
                FacesContext.getCurrentInstance().addMessage(null, msg);

                setVehicleMakes(null);
                setVehicleTypes(null);
                setVmodels(null);
            } else {
                gDAO.rollback();
                naration += "Status: Failed: " + gDAO.getMessage();
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed: ",
                        "Failed to create all models. " + gDAO.getMessage());
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error: ",
                    "Severe error occured. " + ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } finally {
            gDAO.destroy();
            dashBean.saveAudit(naration, "", null);
        }
    }
}

From source file:com.dexter.fms.mbean.FleetMBean.java

License:Open Source License

public void save(int i) {
    String naration = "";
    GeneralDAO gDAO = new GeneralDAO();
    boolean ret = false;
    boolean validated = false;
    switch (i) {/*from   w  w w .j a va  2  s .  c om*/
    case 1: // vehicle type
    {
        if (getVehicleType().getName() != null && getPartner() != null) {
            naration = "Create vehicle type: " + getVehicleType().getName();
            getVehicleType().setPartner(getPartner());
            getVehicleType().setCreatedBy(dashBean.getUser());
            getVehicleType().setCrt_dt(new Date());
            gDAO.startTransaction();
            ret = gDAO.save(getVehicleType());
            if (ret) {
                setVehicleType(null);
                setVehicleTypes(null);
            }
            validated = true;
        }
        break;
    }
    case 2: // vehicle make
    {
        if (getVehicleMake().getName() != null && getPartner() != null) {
            naration = "Create vehicle make: " + getVehicleMake().getName();
            getVehicleMake().setPartner(getPartner());
            getVehicleMake().setCreatedBy(dashBean.getUser());
            getVehicleMake().setCrt_dt(new Date());
            gDAO.startTransaction();
            ret = gDAO.save(getVehicleMake());
            if (ret) {
                setVehicleMake(null);
                setVehicleMakes(null);
            }
            validated = true;
        }
        break;
    }
    case 3: // vehicle models
    {
        if (getVmodel().getName() != null && getVehicleType_id() != null && getVehicleMake_id() != null
                && getPartner() != null) {
            getVmodel().setPartner(getPartner());
            getVmodel().setCreatedBy(dashBean.getUser());
            getVmodel().setCrt_dt(new Date());

            if (getVehicleMake_id() > 0) {
                Object obj = gDAO.find(VehicleMake.class, getVehicleMake_id());
                if (obj != null) {
                    getVmodel().setMaker((VehicleMake) obj);
                }
            }
            if (getVehicleType_id() > 0) {
                Object obj = gDAO.find(VehicleType.class, getVehicleType_id());
                if (obj != null) {
                    getVmodel().setType((VehicleType) obj);
                }
            }
            naration = "Create vehicle model: Type: " + getVmodel().getType().getName() + ", Make: "
                    + getVmodel().getMaker().getName() + ", Model: " + getVmodel().getName() + "("
                    + getVmodel().getYear() + ")";
            gDAO.startTransaction();
            ret = gDAO.save(getVmodel());
            if (ret) {
                setVmodel(null);
                setVmodels(null);
            }
            validated = true;
        }
        break;
    }
    case 4: // vehicle standard routine maintenance
    {
        if (getVsrm().getDescription() != null && getVsrm().getOdometer() != null
                && getVehicleModel_id() != null) {
            getVsrm().setCreatedBy(dashBean.getUser());
            getVsrm().setCrt_dt(new Date());
            if (getVehicleModel_id() > 0) {
                Object obj = gDAO.find(VehicleModel.class, getVehicleModel_id());
                if (obj != null) {
                    getVsrm().setModel((VehicleModel) obj);
                }
            }
            naration = "Create standard routine maintenance: " + getVsrm().getModel().getName() + "("
                    + getVsrm().getOdometer().toPlainString() + ")";
            gDAO.startTransaction();
            ret = gDAO.save(getVsrm());
            if (ret) {
                setVsrm(null);
                setVsrmList(null);
            }
            validated = true;
        }

        break;
    }
    case 5: // batch load VSRM
    {
        if (getAllvmodels() != null && getAllvmodels().size() > 0) {
            int count = 0;
            Vector<VehicleModel> selModels = new Vector<VehicleModel>();
            for (VehicleModel e : getAllvmodels()) {
                if (e.isSelected()) {
                    count++;
                    selModels.add(e);
                }
            }
            if (count == 0) {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed: ", "No vehicle model selected!");
                FacesContext.getCurrentInstance().addMessage(null, msg);
            } else {
                // Now read the content from excel
                if (getModelsVSRMBatchExcel() != null) {
                    try {
                        ByteArrayInputStream byteIn = new ByteArrayInputStream(
                                getModelsVSRMBatchExcel().getContents());
                        HSSFWorkbook workbook = new HSSFWorkbook(byteIn);
                        HSSFSheet sheet = workbook.getSheetAt(0);

                        //Get iterator to all the rows in current sheet starting from row 2
                        Iterator<Row> rowIterator = sheet.iterator();
                        int pos = 1;

                        gDAO.startTransaction();
                        while (rowIterator.hasNext()) {
                            Row row = rowIterator.next();
                            String odometer = "", maintenance = "";
                            if (pos > 1) {
                                validated = true;
                                //Get iterator to all cells of current row
                                Iterator<Cell> cellIterator = row.cellIterator();
                                while (cellIterator.hasNext()) {
                                    Cell cell = cellIterator.next();
                                    String val = "";
                                    switch (cell.getCellType()) {
                                    case Cell.CELL_TYPE_BLANK:
                                        val = "";
                                        break;
                                    case Cell.CELL_TYPE_BOOLEAN:
                                        val = "" + cell.getBooleanCellValue();
                                        break;
                                    case Cell.CELL_TYPE_ERROR:
                                        val = "";
                                        break;
                                    case Cell.CELL_TYPE_NUMERIC:
                                        val = "" + cell.getNumericCellValue();
                                        break;
                                    case Cell.CELL_TYPE_STRING:
                                        val = cell.getStringCellValue();
                                        break;
                                    default: {
                                        try {
                                            val = cell.getStringCellValue();
                                        } catch (Exception ex) {
                                        }
                                        break;
                                    }
                                    }
                                    if (cell.getColumnIndex() == 0)
                                        odometer = val;
                                    else if (cell.getColumnIndex() == 1)
                                        maintenance = val;
                                }

                                for (VehicleModel e : selModels) {
                                    VehicleStandardRM vsrm = new VehicleStandardRM();
                                    vsrm.setCreatedBy(dashBean.getUser());
                                    vsrm.setCrt_dt(new Date());
                                    vsrm.setDescription(maintenance);
                                    vsrm.setModel(e);
                                    vsrm.setOdometer(new BigDecimal(Long.parseLong(odometer)));
                                    ret = gDAO.save(vsrm);
                                }
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error: ",
                                "Severe error occured. " + ex.getMessage());
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                    }
                }
            }
        } else {
            msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed: ", "No vehicle model available!");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
        break;
    }
    }
    if (validated) {
        if (ret) {
            gDAO.commit();
            naration += ", Status: Success";
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success: ", "Entity created successfully.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            gDAO.rollback();
            naration += ", Status: Failed: " + gDAO.getMessage();
            msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed: ",
                    "Failed to create entity. " + gDAO.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    } else {
        msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed: ",
                "All fields with the '*' sign are required!");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    gDAO.destroy();
    dashBean.saveAudit(naration, "", null);
}