Example usage for org.apache.poi.ss.usermodel Cell getStringCellValue

List of usage examples for org.apache.poi.ss.usermodel Cell getStringCellValue

Introduction

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

Prototype

String getStringCellValue();

Source Link

Document

Get the value of the cell as a string

For numeric cells we throw an exception.

Usage

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 {//  w  ww . jav a  2 s  .  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.  ja v a  2s  .  c  o m*/
    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);
}

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

@SuppressWarnings("unchecked")
public void BatchLoadPersonels() {
    if (getPartner() != null && getPersonelsBatchExcel() != null) {
        String naration = "Batch load staffs: ";
        GeneralDAO gDAO = new GeneralDAO();
        try {/*from www.  j a  va2s.c om*/
            ByteArrayInputStream byteIn = new ByteArrayInputStream(getPersonelsBatchExcel().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 staffID = "", firstname = "", lastname = "", department = "", region = "", address = "",
                        phone = "", email = "", isAUser = "";
                String username = "", password = "", cpassword = "", role = "";
                String isADriver = "", driver_grade = "", driver_license_no = "",
                        driver_license_expiry_date = "", guarantor = "";
                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:
                            staffID = val;
                            break;
                        case 1:
                            firstname = val;
                            break;
                        case 2:
                            lastname = val;
                            break;
                        case 3:
                            department = val;
                            break;
                        case 4:
                            region = val;
                            break;
                        case 5:
                            address = val;
                            break;
                        case 6:
                            phone = val;
                            break;
                        case 7:
                            email = val;
                            break;
                        case 8:
                            isAUser = val;
                            break;
                        case 9:
                            username = val;
                            break;
                        case 10:
                            password = val;
                            break;
                        case 11:
                            cpassword = val;
                            break;
                        case 12:
                            role = val;
                            break;
                        case 13:
                            isADriver = val;
                            break;
                        case 14:
                            driver_grade = val;
                            break;
                        case 15:
                            driver_license_no = val;
                            break;
                        case 16:
                            driver_license_expiry_date = val;
                            break;
                        case 17:
                            guarantor = val;
                            break;
                        }
                    }

                    PartnerPersonel pp = new PartnerPersonel();
                    pp.setPartner(getPartner());
                    pp.setCreatedBy(dashBean.getUser());
                    pp.setCrt_dt(new Date());
                    pp.setStaff_id(staffID);
                    pp.setFirstname(firstname);
                    pp.setLastname(lastname);
                    pp.setAddress(address);
                    pp.setPhone(phone);
                    pp.setEmail(email);

                    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)
                                pp.setDepartment(e);
                        }
                        if (pp.getDepartment() == null && isAutoCreate()) {
                            Department d = new Department();
                            d.setCreatedBy(dashBean.getUser());
                            d.setCrt_dt(new Date());
                            d.setName(department);
                            d.setPartner(getPartner());
                            ret = gDAO.save(d);
                            if (ret)
                                pp.setDepartment(d);
                            else
                                break;
                        } else if (pp.getDepartment() == null && !isAutoCreate()) {
                            ret = false;
                            gDAO.setMessage(
                                    "Department: '" + department + "' does not exist for user: " + username);
                            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)
                                pp.setRegion(e);
                        }
                        if (pp.getRegion() == null && isAutoCreate()) {
                            Region r = new Region();
                            r.setCreatedBy(dashBean.getUser());
                            r.setCrt_dt(new Date());
                            r.setName(region);
                            r.setPartner(getPartner());
                            ret = gDAO.save(r);
                            if (ret)
                                pp.setRegion(r);
                            else
                                break;
                        } else if (pp.getRegion() == null && !isAutoCreate()) {
                            ret = false;
                            gDAO.setMessage("Region: '" + region + "' does not exist for user: " + username);
                            break;
                        }
                    }

                    MRole r = null;
                    if (isAUser != null && isAUser.trim().equalsIgnoreCase("true")) {
                        Query q = gDAO.createQuery(
                                "Select e from MRole e where e.partner = :partner and e.name = :name");
                        q.setParameter("partner", getPartner());
                        q.setParameter("name", role);
                        Object objs = gDAO.search(q, 0);
                        if (objs != null) {
                            Vector<MRole> objsList = (Vector<MRole>) objs;
                            for (MRole e : objsList)
                                r = e;
                        }

                        if (r == null) {
                            ret = false;
                            gDAO.setMessage("Role: '" + role + "' must exist for user: " + username);
                            break;
                        }
                    }

                    ret = gDAO.save(pp);
                    if (!ret)
                        break;
                    else {
                        if (isAUser != null && isAUser.trim().equalsIgnoreCase("true")) {
                            if (username != null && username.trim().length() > 0 && password != null
                                    && password.trim().length() > 0 && role != null
                                    && role.trim().length() > 0) {
                                if (password.equals(cpassword)) {
                                    PartnerUser pu = new PartnerUser();
                                    pu.setActive(true);
                                    pu.setAdmin(false);
                                    pu.setCreatedBy(dashBean.getUser());
                                    pu.setCrt_dt(new Date());
                                    pu.setPartner(getPartner());
                                    pu.setPartner_code(getPartner().getCode());
                                    pu.setPassword(Hasher.getHashValue(password));
                                    pu.setPersonel(pp);
                                    pu.setUsername(username);
                                    ret = gDAO.save(pu);
                                    if (ret) {
                                        if (r != null) {
                                            PartnerUserRole pur = new PartnerUserRole();
                                            pur.setCreatedBy(dashBean.getUser());
                                            pur.setCrt_dt(new Date());
                                            pur.setDefaultRole(false);
                                            pur.setRole(r);
                                            pur.setUser(pu);
                                            ret = gDAO.save(pur);
                                            if (!ret)
                                                break;
                                        } else {
                                            ret = false;
                                            gDAO.setMessage("Role: '" + role + "' does not exist for user: "
                                                    + username);
                                            break;
                                        }

                                        pp.setHasUser(true);
                                        ret = gDAO.update(pp);
                                        if (!ret)
                                            break;
                                    } else
                                        break;
                                } else {
                                    ret = false;
                                    gDAO.setMessage("Passwords are not the same for user: " + username);
                                    break;
                                }
                            } else {
                                ret = false;
                                gDAO.setMessage("All fields are required to create a user account for user: "
                                        + username);
                                break;
                            }
                        }

                        if (isADriver != null && isADriver.trim().equalsIgnoreCase("true")) {
                            PartnerDriver driver = new PartnerDriver();
                            driver.setActive(true);
                            driver.setCreatedBy(dashBean.getUser());
                            driver.setCrt_dt(new Date());
                            driver.setPartner(getPartner());
                            driver.setPersonel(pp);

                            driver.setDrvLicenseNo(driver_license_no);
                            driver.setGuarantor(guarantor);

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

                            ret = gDAO.save(driver);
                            if (!ret)
                                break;
                            else {
                                pp.setHasDriver(true);
                                ret = gDAO.update(pp);
                                if (!ret)
                                    break;
                            }
                            if (driver_license_expiry_date != null) {
                                Date expiryDt = null;
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                try {
                                    expiryDt = sdf.parse(driver_license_expiry_date);
                                } catch (Exception ex) {
                                }

                                if (expiryDt != null) {
                                    DriverLicense dl = new DriverLicense();
                                    dl.setDrvLicenseNo(driver_license_no);
                                    dl.setCreatedBy(dashBean.getUser());
                                    dl.setCrt_dt(new Date());
                                    dl.setLic_end_dt(expiryDt);

                                    boolean active = false, expired = false;
                                    if (expiryDt.after(new Date())) {
                                        active = true;
                                    } else {
                                        expired = true;
                                    }
                                    dl.setActive(active);
                                    dl.setExpired(expired);
                                    dl.setDriver(driver);
                                    ret = gDAO.save(dl);
                                    if (!ret)
                                        break;
                                }
                            }
                        }
                    }
                } else
                    pos += 1;
            }
            if (ret) {
                gDAO.commit();
                naration += " Status: Success";
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success: ",
                        "All personel created successfully.");
                FacesContext.getCurrentInstance().addMessage(null, msg);

                setPersonels(null);
                setPersonelsWithoutUsers(null);
            } else {
                gDAO.rollback();
                naration += " Status: Failed: " + gDAO.getMessage();
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed: ",
                        "Failed to create all personel. " + 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.fuelcard.mbean.UserMBean.java

@SuppressWarnings("unchecked")
public void buckLoadVehicles() {
    AuditTrail audit = new AuditTrail();
    audit.setPartner(getActiveUser().getPartner());

    audit.setAuditTime(new java.util.Date());
    audit.setActionPerformed("Batch loading vehicles...");
    audit.setEntity("CAR");
    audit.setUsername(getActiveUser().getUsername());

    Vector<Car> loadedCars = new Vector<Car>();

    try {//from   www . ja v a 2 s  .com
        //Get the workbook instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(getVehiclesFile().getInputstream());
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            //Get current sheet from the workbook
            HSSFSheet sheet = workbook.getSheetAt(i);
            //Get iterator to all the rows in current sheet starting from row 2
            Iterator<Row> rowIterator = sheet.iterator();
            int pos = 1;

            // reading the contents 
            // column 1 - zonControlId, 2 - regNumber, 3 - fuelType, 4 - username, 5 - cardPan, 6 - region, 7 - dept, 8 - make, 9 - type, 10 - model, 11 - year, 12 - kmpl, 13 - vehicleCapacity, 14 - calibratedCapacity
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                String zonControlId = "", regNumber = "", fuelType = "", username = "";
                String cardPan = "", region = "", dept = "", make = "", type = "";
                String model = "", year = "", kmpl = "", vehicleCapacity = "", calibratedCapacity = "";
                if (pos > 1) // skip the first row, should be headers
                {
                    //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:
                            zonControlId = val;
                            break;
                        case 1:
                            regNumber = val;
                            break;
                        case 2:
                            fuelType = val;
                            break;
                        case 3:
                            username = val;
                            break;
                        case 4:
                            cardPan = val;
                            break;
                        case 5:
                            region = val;
                            break;
                        case 6:
                            dept = val;
                            break;
                        case 7:
                            make = val;
                            break;
                        case 8:
                            type = val;
                            break;
                        case 9:
                            model = val;
                            break;
                        case 10:
                            year = val;
                            break;
                        case 11:
                            kmpl = val;
                            break;
                        case 12:
                            vehicleCapacity = val;
                            break;
                        case 13:
                            calibratedCapacity = val;
                            break;
                        }
                    }
                    try {
                        Car e = new Car();
                        e.setCalibratedCapacity(
                                (calibratedCapacity != null) ? Double.parseDouble(calibratedCapacity) : 0);
                        e.setCardPan(cardPan);
                        e.setFuelType(fuelType);
                        e.setPartner(getActiveUser().getPartner());
                        e.setRegNumber(regNumber);
                        try {
                            e.setVehicleCapacity(
                                    (vehicleCapacity != null) ? Double.parseDouble(vehicleCapacity) : 0);
                        } catch (Exception ex) {
                        }
                        try {
                            e.setZonControlId((zonControlId != null) ? Integer.parseInt(zonControlId) : 0);
                        } catch (Exception ex) {
                        }

                        if (username != null) {
                            User u = new UserDAO().getUserByUsername(username,
                                    getActiveUser().getPartner().getCode());
                            if (u != null) {
                                e.setAssigned(true);
                                e.setAssignedUser(u);
                            }
                        }

                        if (region != null) {
                            RegionDAO regDAO = new RegionDAO();
                            Region reg = regDAO.getRegionByName(region);
                            if (reg == null) {
                                reg = new Region();
                                reg.setName(region);
                                reg.setPartner(getActiveUser().getPartner());
                                regDAO.save(reg);
                            }
                            e.setRegion(reg);
                        }

                        if (dept != null) {
                            DepartmentDAO dDAO = new DepartmentDAO();
                            Department d = dDAO.getDepartmentByName(dept);
                            if (d == null) {
                                d = new Department();
                                d.setName(dept);
                                d.setPartner(getActiveUser().getPartner());
                                dDAO.save(d);
                            }
                            e.setDepartment(d);
                        }

                        if (make != null && type != null && model != null) {
                            VehicleMake m = null;
                            VehicleType t = null;
                            VehicleModel md = null;
                            GeneralDAO gDAO = new GeneralDAO();
                            Hashtable<String, Object> params = new Hashtable<String, Object>();
                            params.put("name", make);
                            params.put("partner", getActiveUser().getPartner());
                            Object retObj = gDAO.search("VehicleMake", params);
                            if (retObj != null) {
                                Vector<VehicleMake> retList = (Vector<VehicleMake>) retObj;
                                for (VehicleMake ret : retList)
                                    m = ret;
                            }
                            if (m == null) {
                                m = new VehicleMake();
                                m.setName(make);
                                m.setPartner(getActiveUser().getPartner());
                                new PlainDAO().save(m);
                            }

                            params = new Hashtable<String, Object>();
                            params.put("name", type);
                            params.put("partner", getActiveUser().getPartner());
                            retObj = gDAO.search("VehicleType", params);
                            if (retObj != null) {
                                Vector<VehicleType> retList = (Vector<VehicleType>) retObj;
                                for (VehicleType ret : retList)
                                    t = ret;
                            }
                            if (t == null) {
                                t = new VehicleType();
                                t.setName(type);
                                t.setPartner(getActiveUser().getPartner());
                                new PlainDAO().save(t);
                            }

                            params = new Hashtable<String, Object>();
                            params.put("name", model);
                            params.put("make", m);
                            params.put("type", t);
                            params.put("year", year);
                            params.put("partner", getActiveUser().getPartner());
                            retObj = gDAO.search("VehicleModel", params);
                            if (retObj != null) {
                                Vector<VehicleModel> retList = (Vector<VehicleModel>) retObj;
                                for (VehicleModel ret : retList)
                                    md = ret;
                            }
                            if (md == null) {
                                md = new VehicleModel();
                                md.setName(model);
                                try {
                                    md.setKmpl((kmpl != null && kmpl.trim().length() > 0)
                                            ? Double.parseDouble(kmpl)
                                            : 0);
                                } catch (Exception ex) {
                                }
                                md.setMake(m);
                                md.setType(t);
                                md.setYear(year);
                                md.setPartner(getActiveUser().getPartner());
                                new PlainDAO().save(md);
                            }

                            e.setModel(md);
                        }

                        loadedCars.add(e);
                    } catch (Exception ig) {
                    }
                } else
                    pos += 1;
            }
        }

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

    audit.setActionPerformed(audit.getActionPerformed() + " Loaded: " + loadedCars.size());

    int success = 0, failed = 0;
    CarDAO cDAO = new CarDAO();
    for (Car e : loadedCars) {
        if (cDAO.createCar(e)) {
            success += 1;
            if (e.getCardPan() != null) {
                Card card = new Card();
                card.setCardPan(getVehicle().getCardPan());
                card.setCrt_dt(new Date());
                new PlainDAO().save(card);
            }
        } else
            failed += 1;
    }
    audit.setActionPerformed(audit.getActionPerformed() + " Success: " + success + ", Failed: " + failed);

    FacesContext curContext = FacesContextImpl.getCurrentInstance();
    curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Done",
            "Loaded: " + loadedCars.size() + ", Success: " + success + ", Failed: " + failed));

    new AuditDAO().save(audit);
    setVehicles(null);
}

From source file:com.dexter.fuelcard.mbean.UserMBean.java

public void buckLoadUsers() {
    AuditTrail audit = new AuditTrail();
    audit.setPartner(getActiveUser().getPartner());

    audit.setAuditTime(new java.util.Date());
    audit.setActionPerformed("Batch loading users...");
    audit.setEntity("USER");
    audit.setUsername(getActiveUser().getUsername());

    Vector<User> loadedUsers = new Vector<User>();

    try {//from ww  w  . j  a  v a 2 s . c o  m
        /*InputStream inputstream = getUploadItem().getInputstream();
        ByteArrayOutputStream fos = new ByteArrayOutputStream();      
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = inputstream.read(bytes)) != -1)
        {
           fos.write(bytes, 0, read);
        }
        fos.close();
                
        ByteArrayInputStream byteIn = new ByteArrayInputStream(fos.toByteArray());*/
        //Get the workbook instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(getUploadItem().getInputstream());
        RoleDAO rDAO = new RoleDAO();
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            //Get current sheet from the workbook
            HSSFSheet sheet = workbook.getSheetAt(i);
            //Get iterator to all the rows in current sheet starting from row 2
            Iterator<Row> rowIterator = sheet.iterator();
            int pos = 1;

            // reading the contents 
            // column 1 - username, 2 - password, 3 - full name, 4 - role id, 5 - email, 6 - mobile number, 7 - Vehicle Reg Number
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                String username = "", password = "", fullname = "", email = "", mobile = "", regNumber = "";
                long role_id = 0L;
                if (pos > 1) // skip the first row, should be headers
                {
                    //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:
                            username = val;
                            break;
                        case 1:
                            password = val;
                            break;
                        case 2:
                            fullname = val;
                            break;
                        case 3:
                            try {
                                role_id = Long.parseLong(val);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                            break;
                        case 4:
                            email = val;
                            break;
                        case 5:
                            mobile = val;
                            break;
                        case 6:
                            regNumber = val;
                            break;
                        }
                    }
                    try {
                        User e = new User();
                        e.setUsername(username);
                        e.setPassword(password);
                        e.setFullname(fullname);
                        e.setEmail(email);
                        e.setMobileNumber(mobile);
                        e.setActive(true);
                        e.setRegNumber(regNumber);

                        Role role = rDAO.getRoleById(role_id);
                        if (role != null) {
                            e.setRole(role);
                            loadedUsers.add(e);
                        }
                    } catch (Exception ig) {
                    }
                } else
                    pos += 1;
            }
        }

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

    audit.setActionPerformed(audit.getActionPerformed() + " Loaded: " + loadedUsers.size());

    int success = 0, failed = 0;
    UserDAO uDAO = new UserDAO();
    for (User e : loadedUsers) {
        String ret = uDAO.createUser(e);
        if (ret.indexOf("Success") >= 0) {
            success += 1;
            if (e.getRegNumber() != null) {
                CarDAO cDAO = new CarDAO();
                Car c = cDAO.getCarByRegNumber(e.getRegNumber());
                if (c != null) {
                    c.setAssigned(true);
                    c.setAssignedUser(e);

                    cDAO.updateCar(c);
                }
            }
        } else
            failed += 1;
    }
    audit.setActionPerformed(audit.getActionPerformed() + " Success: " + success + ", Failed: " + failed);

    FacesContext curContext = FacesContextImpl.getCurrentInstance();
    curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Done",
            "Loaded: " + loadedUsers.size() + ", Success: " + success + ", Failed: " + failed));

    new AuditDAO().save(audit);
    setAllusers(null);
}

From source file:com.dfpray.formatter.CardModel.java

/**
 * Imports a .xlsx file and create a CardModel form it
 * @param path Path to file/*from w w w.  ja v a 2s  .c  o  m*/
 * @throws IOException
 */
public void importFromExcel(String path) throws IOException {
    String[] cardInfo = new String[32];
    FileInputStream file = new FileInputStream(new File(path));
    @SuppressWarnings("resource")
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    XSSFSheet sheet = workbook.getSheetAt(0);
    Row row;
    Cell cell;
    Iterator<Cell> cellIterator;
    Iterator<Row> rowIterator;
    int i;

    //Iterate through each rows one by one
    rowIterator = sheet.iterator();

    while (rowIterator.hasNext()) {
        row = rowIterator.next();
        cellIterator = row.cellIterator();

        i = 0;
        while (cellIterator.hasNext()) {
            cell = cellIterator.next();
            switch (cell.getCellType()) {

            case Cell.CELL_TYPE_BLANK:
                cardInfo[i] = " ";
                //System.out.println("Nothing");
                break;

            case Cell.CELL_TYPE_NUMERIC:
                cardInfo[i] = (Double.toString(cell.getNumericCellValue()));
                //System.out.println(Double.toString(cell.getNumericCellValue()));
                break;

            case Cell.CELL_TYPE_STRING:
                cardInfo[i] = cell.getStringCellValue();
                //System.out.println(cell.getStringCellValue());
                break;

            }
            i++;
        }
        //Create card and add it tho this 
        cards.add(new BusinessCard(cardInfo));
    }
    file.close();
}

From source file:com.dituiba.excel.BaseExcelService.java

License:Apache License

/**
 * ??/*  w  w  w . j  a va  2 s.  c  o m*/
 * @param cell
 * @return
 */
public static boolean isEmpty(Cell cell) {
    if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            if (!ObjectHelper.isNullOrEmptyString(cell.getStringCellValue())) {
                return false;
            }
        } else {
            return false;
        }
    }
    return true;
}

From source file:com.dituiba.excel.BaseExcelService.java

License:Apache License

/**
 * ??//from  w w w.jav  a  2s .c  o m
 * @param cell
 * @return
 */
public static String getString(Cell cell) {
    return cell.getStringCellValue();
}

From source file:com.dituiba.excel.DefaultInputAdapter.java

License:Apache License

/**
 * ?//w  w  w. j  a  va 2s .com
 *
 * @param type
 * @param fieldName
 * @param cell
 * @throws IllegalAccessException
 * @throws ParseException
 */
public Object inputDateAdapter(DataBean dataBean, Class type, String fieldName, Cell cell)
        throws AdapterException {
    log.debug("in DefaultInputAdapter:inputDateAdapter fieldName:{} type:{}", fieldName, type.getSimpleName());
    InputDateConfig inputDateConfig = dataBean.getInputConfig(fieldName);
    Object o = null;
    if (Cell.CELL_TYPE_BLANK == cell.getCellType()) {
        log.debug("cell is blank ");
        return o;
    } else if (Date.class.isAssignableFrom(type)) {
        if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
            Date date = cell.getDateCellValue();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int i = calendar.get(Calendar.YEAR);
            try { //???2014026??
                o = i > 2500 ? DateUtil.formatToDate(String.format("%.0f", cell.getNumericCellValue()),
                        inputDateConfig.format()) : date;
            } catch (ParseException e) {
                throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell);
            }
        } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
            try {
                o = DateUtil.formatToDate(trim(cell.getStringCellValue()), inputDateConfig.format());
            } catch (ParseException e) {
                throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell);
            }
        } else if (Cell.CELL_TYPE_BLANK == cell.getCellType()) {
            return null;
        } else {
            throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell);
        }
    } else if (String.class.isAssignableFrom(type)) {
        if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
            Date dateCellValue = cell.getDateCellValue();
            o = DateUtil.format(dateCellValue, inputDateConfig.format());
        } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
            OutputDateConfig outputDateConfig = dataBean.getOutputConfig(fieldName);
            try {
                o = DateUtil.format(trim(cell.getStringCellValue()), outputDateConfig.format(),
                        inputDateConfig.format());
            } catch (ParseException e) {
                throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell);
            }
        } else {
            throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell);
        }
    } else {
        throw new AdapterException(fieldName, Message.DATE_TYPE_ERROR, cell);
    }
    return o;
}

From source file:com.dituiba.excel.DefaultInputAdapter.java

License:Apache License

public static Object getCellValue(Cell cell, Class type) throws AdapterException {
    if (cell == null)
        return "";
    try {/*from www.ja v  a  2  s  .  c  o m*/
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_BOOLEAN:
            return cell.getBooleanCellValue();
        case Cell.CELL_TYPE_BLANK:
            return "";
        case Cell.CELL_TYPE_NUMERIC:
            if (String.class.isAssignableFrom(type)) {
                cell.setCellType(Cell.CELL_TYPE_STRING);
                return trim(cell.getStringCellValue());
            } else if (Date.class.isAssignableFrom(type)) {
                return cell.getDateCellValue();
            }
            return cell.getNumericCellValue();
        case Cell.CELL_TYPE_STRING:
            return trim(cell.getStringCellValue());
        case Cell.CELL_TYPE_FORMULA:
            try {
                return String.valueOf(cell.getNumericCellValue());
            } catch (IllegalStateException e) {
                return trim(String.valueOf(cell.getRichStringCellValue()));
            }
        }
    } catch (Exception e) {
        throw new AdapterException(Message.INPUT_CELL_DATA_ERROR, cell);
    }
    throw new AdapterException(Message.INPUT_CELL_DATA_ERROR, cell);
}