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

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

Introduction

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

Prototype

Cell getCell(int cellnum, MissingCellPolicy policy);

Source Link

Document

Returns the cell at the given (0 based) index, with the specified org.apache.poi.ss.usermodel.Row.MissingCellPolicy

Usage

From source file:com.b2international.snowowl.snomed.core.refset.automap.XlsParser.java

License:Apache License

private List<String> collectRowValues(Row row) {

    List<String> list = newArrayListWithExpectedSize(row.getLastCellNum());

    boolean hasAnyCellWithValue = false;
    for (int i = 0; i < row.getLastCellNum(); i++) {
        String cellValue = getStringValue(row.getCell(i, Row.RETURN_BLANK_AS_NULL));
        hasAnyCellWithValue = !StringUtils.isEmpty(cellValue);
        list.add(cellValue);//from   ww  w  .  j a  v a  2s . co m
    }

    return hasAnyCellWithValue ? list : Collections.<String>emptyList();
}

From source file:com.b2international.snowowl.snomed.importer.net4j.SnomedSubsetImportUtil.java

License:Apache License

private List<String> collectRowValues(final Row row) {
    List<String> list = Lists.newArrayList();
    for (int i = 0; i < row.getLastCellNum(); i++) {
        list.add(getStringValue(row.getCell(i, Row.CREATE_NULL_AS_BLANK)));
    }//from  w ww .  j  a  va  2s  .c o m

    return list;
}

From source file:com.clican.pluto.dataprocess.engine.processes.ExcelProcessor.java

License:LGPL

public void readExcel(ProcessorContext context, ExcelExecBean execBean) throws Exception {
    InputStream is = new AutoDecisionResource(execBean.getResource()).getInputStream();
    try {//  www  .j ava2  s . c  o m
        Workbook book = WorkbookFactory.create(is);
        Sheet sheet = book.getSheet(execBean.getSheetName());
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        List<String> names = new ArrayList<String>();
        Map<String, String> typeMap = execBean.getTypeMap();
        int firstRow = sheet.getFirstRowNum(), lastRow = sheet.getLastRowNum();
        for (int rowIdx = firstRow; rowIdx < lastRow; rowIdx++) {
            Row excelRow = sheet.getRow(rowIdx);

            short minColIx = excelRow.getFirstCellNum();
            short maxColIx = excelRow.getLastCellNum();

            Map<String, Object> row = new HashMap<String, Object>();

            for (int colIdx = minColIx; colIdx < maxColIx; colIdx++) {
                Cell cell = excelRow.getCell(colIdx, Row.CREATE_NULL_AS_BLANK);

                if (rowIdx == 0) {
                    names.add(cell.getStringCellValue());
                } else {
                    String type = null;
                    if (names.size() > colIdx) {
                        type = typeMap.get(names.get(colIdx));
                    }
                    if (StringUtils.isNotEmpty(type)) {
                        if (type.equals("string")) {
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            row.put(names.get(colIdx), cell.getStringCellValue().trim());
                        } else if (type.equals("double")) {
                            cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                            row.put(names.get(colIdx), cell.getNumericCellValue());
                        } else if (type.equals("int")) {
                            cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                            row.put(names.get(colIdx), (int) cell.getNumericCellValue());
                        } else if (type.equals("date")) {
                            row.put(names.get(colIdx), cell.getDateCellValue());
                        } else {
                            throw new DataProcessException("??Excel?");
                        }
                    }
                }
            }
            if (rowIdx != 0) {
                result.add(row);
            }
        }
        context.setAttribute(execBean.getResultName(), result);
    } finally {
        if (is != null) {
            is.close();
        }
    }

}

From source file:com.devnexus.ting.web.controller.admin.RegistrationController.java

License:Apache License

@RequestMapping(value = "/s/admin/{eventKey}/uploadRegistration", method = RequestMethod.POST)
public ModelAndView uploadGroupRegistration(ModelAndView model, HttpServletRequest request,
        @PathVariable(value = "eventKey") String eventKey,
        @Valid @ModelAttribute("registerForm") UploadGroupRegistrationForm uploadForm,
        BindingResult bindingResult) throws FileNotFoundException, IOException, InvalidFormatException {

    EventSignup signUp = eventSignupRepository.getByEventKey(eventKey);
    model.getModelMap().addAttribute("event", signUp.getEvent());

    if (bindingResult.hasErrors()) {

        model.getModelMap().addAttribute("registerForm", uploadForm);
        model.setViewName("/admin/upload-registration");
    } else {/*from w  ww  .  ja  v a  2 s.c om*/

        boolean hasErrors = false;

        try {

            Workbook wb = WorkbookFactory.create(uploadForm.getRegistrationFile().getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            Cell contactNameCell = sheet.getRow(0).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            Cell contactEmailCell = sheet.getRow(1).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            Cell contactPhoneCell = sheet.getRow(2).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            Cell registrationReferenceCell = sheet.getRow(3).getCell(1,
                    Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

            if (contactNameCell.getStringCellValue().isEmpty()) {
                hasErrors = true;
                bindingResult.addError(new ObjectError("registrationFile", "Contact Name Empty"));
            }

            if (contactEmailCell.getStringCellValue().isEmpty()) {
                hasErrors = true;
                bindingResult.addError(new ObjectError("registrationFile", "Contact Email Empty"));
            }

            if (contactPhoneCell.getStringCellValue().isEmpty()) {
                hasErrors = true;
                bindingResult.addError(new ObjectError("registrationFile", "Contact Phone Empty"));
            }

            if (registrationReferenceCell.getStringCellValue().isEmpty()) {
                hasErrors = true;
                bindingResult.addError(new ObjectError("registrationFile", "Registration Reference Empty"));
            }

            if (!hasErrors) {
                RegistrationDetails details = new RegistrationDetails();
                details.setContactEmailAddress(contactEmailCell.getStringCellValue());
                details.setContactName(contactNameCell.getStringCellValue());
                details.setContactPhoneNumber(contactPhoneCell.getStringCellValue());
                details.setRegistrationFormKey(registrationReferenceCell.getStringCellValue());
                details.setEvent(signUp.getEvent());
                details.setFinalCost(BigDecimal.ZERO);
                details.setInvoice("Invoiced");
                details.setPaymentState(RegistrationDetails.PaymentState.PAID);
                int attendeeRowIndex = 7;

                Row attendeeRow = sheet.getRow(attendeeRowIndex);
                while (attendeeRow != null) {
                    attendeeRow = sheet.getRow(attendeeRowIndex);
                    if (attendeeRow != null) {
                        Cell firstName = attendeeRow.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell lastName = attendeeRow.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell emailAddress = attendeeRow.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell city = attendeeRow.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell state = attendeeRow.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell country = attendeeRow.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell ticketType = attendeeRow.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell company = attendeeRow.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell jobTitle = attendeeRow.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell tshirtSize = attendeeRow.getCell(9, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell vegetarian = attendeeRow.getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell sponsorMessages = attendeeRow.getCell(11,
                                Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

                        if (firstName.getStringCellValue().isEmpty()) {
                            break;
                        }

                        if (lastName.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : lastName"));
                            hasErrors = true;
                            break;
                        }
                        if (emailAddress.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : emailAddress"));
                            hasErrors = true;
                            break;
                        }
                        if (city.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : city"));
                            hasErrors = true;
                            break;
                        }
                        if (state.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : state "));
                            hasErrors = true;
                            break;
                        }
                        if (country.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : country"));
                            hasErrors = true;
                            break;
                        }
                        if (company.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : company"));
                            hasErrors = true;
                            break;
                        }
                        if (jobTitle.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : jobTitle"));
                            hasErrors = true;
                            break;
                        }

                        if (ticketType.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information: ticket type"));
                            hasErrors = true;
                            break;
                        }

                        if (tshirtSize.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information: t shirt "));
                            hasErrors = true;
                            break;
                        }
                        if (vegetarian.getStringCellValue().isEmpty()
                                || !(vegetarian.getStringCellValue().equalsIgnoreCase("no")
                                        || vegetarian.getStringCellValue().equalsIgnoreCase("yes"))) {
                            bindingResult.addError(
                                    new ObjectError("registrationFile", " row " + (attendeeRowIndex + 1)
                                            + " missing information. Vegetarian option should be yes or no "));
                            hasErrors = true;
                            break;
                        }
                        if (sponsorMessages.getStringCellValue().isEmpty()
                                || !(sponsorMessages.getStringCellValue().equalsIgnoreCase("no")
                                        || sponsorMessages.getStringCellValue().equalsIgnoreCase("yes"))) {
                            bindingResult.addError(
                                    new ObjectError("registrationFile", " row " + (attendeeRowIndex + 1)
                                            + " missing information. Sponsor message should be yes or no "));
                            hasErrors = true;
                            break;
                        }

                        TicketOrderDetail detail = new TicketOrderDetail();

                        detail.setCity(city.getStringCellValue());
                        detail.setCompany(company.getStringCellValue());
                        detail.setCouponCode("");
                        detail.setCountry(country.getStringCellValue());
                        detail.setEmailAddress(emailAddress.getStringCellValue());
                        detail.setFirstName(firstName.getStringCellValue());
                        detail.setJobTitle(jobTitle.getStringCellValue());
                        detail.setLastName(lastName.getStringCellValue());
                        detail.setSponsorMayContact(
                                sponsorMessages.getStringCellValue().equalsIgnoreCase("no") ? "false" : "true");
                        detail.setState(state.getStringCellValue());
                        detail.setTicketGroup(
                                Long.parseLong(ticketType.getStringCellValue().split("-\\|-")[1].trim()));

                        detail.setLabel(businessService.getTicketGroup(detail.getTicketGroup()).getLabel());

                        detail.settShirtSize(tshirtSize.getStringCellValue());
                        detail.setVegetarian(
                                vegetarian.getStringCellValue().equalsIgnoreCase("no") ? "false" : "true");
                        detail.setRegistration(details);
                        details.getOrderDetails().add(detail);

                        attendeeRowIndex++;

                    }
                }

                if (uploadForm.getOverrideRegistration()) {
                    try {
                        RegistrationDetails tempRegistration = businessService
                                .getRegistrationForm(registrationReferenceCell.getStringCellValue());
                        tempRegistration.getOrderDetails().forEach((oldDetail) -> {
                            oldDetail.setRegistration(null);
                        });
                        tempRegistration.getOrderDetails().clear();
                        tempRegistration.getOrderDetails().addAll(details.getOrderDetails());

                        tempRegistration.getOrderDetails().forEach((detail) -> {
                            detail.setRegistration(tempRegistration);
                        });
                        details = tempRegistration;

                        businessService.updateRegistration(details, uploadForm.getSendEmail());
                    } catch (EmptyResultDataAccessException ignore) {
                        businessService.updateRegistration(details, uploadForm.getSendEmail());
                    }
                } else {
                    try {
                        RegistrationDetails tempRegistration = businessService
                                .getRegistrationForm(registrationReferenceCell.getStringCellValue());
                        hasErrors = true;
                        bindingResult.addError(new ObjectError("registrationFile",
                                "Registration with this key exists, please check \"Replace Registrations\"."));
                    } catch (EmptyResultDataAccessException ignore) {
                        businessService.updateRegistration(details, uploadForm.getSendEmail());
                    }
                }

            }

        } catch (Exception ex) {
            hasErrors = true;
            Logger.getAnonymousLogger().log(Level.SEVERE, ex.getMessage(), ex);

            bindingResult.addError(new ObjectError("registrationFile", ex.getMessage()));
        }
        if (hasErrors) {
            model.setViewName("/admin/upload-registration");
        } else {
            model.setViewName("/admin/index");
        }
    }

    return model;
}

From source file:com.ebay.xcelite.reader.BeanSheetReader.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//w  ww  .j  a  v a  2  s  .  c  o  m
public Collection<T> read() {
    buildHeader();
    List<T> data = Lists.newArrayList();
    try {
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            if (isBlankRow(row))
                continue;
            T object = type.newInstance();

            int i = 0;
            for (String columnName : header) {
                Cell cell = row.getCell(i, Row.RETURN_BLANK_AS_NULL);
                Col col = mapper.getColumn(columnName);
                if (col == null) {
                    if (anyColumn != null) {
                        Set<Field> fields = ReflectionUtils.getAllFields(object.getClass(),
                                withName(anyColumn.getFieldName()));
                        Field field = fields.iterator().next();
                        if (!isColumnInIgnoreList(field, columnName)) {
                            writeToAnyColumnField(field, object, cell, columnName);
                        }
                    }
                } else {
                    Set<Field> fields = ReflectionUtils.getAllFields(object.getClass(),
                            withName(col.getFieldName()));
                    Field field = fields.iterator().next();
                    writeToField(field, object, cell, col);
                }
                i++;
            }
            boolean keepObject = true;
            for (RowPostProcessor<T> rowPostProcessor : rowPostProcessors) {
                keepObject = rowPostProcessor.process(object);
                if (!keepObject)
                    break;
            }
            if (keepObject) {
                data.add(object);
            }
        }
    } catch (InstantiationException e1) {
        throw new RuntimeException(e1);
    } catch (IllegalAccessException e1) {
        throw new RuntimeException(e1);
    }
    return data;
}

From source file:com.ebay.xcelite.reader.SimpleSheetReader.java

License:Apache License

@Override
public Collection<Collection<Object>> read() {
    List<Collection<Object>> rows = Lists.newArrayList();
    Iterator<Row> rowIterator = sheet.getNativeSheet().iterator();
    boolean firstRow = true;
    short cellsNum = -1;
    while (rowIterator.hasNext()) {
        Row excelRow = rowIterator.next();
        if (firstRow) {
            cellsNum = excelRow.getLastCellNum();
            firstRow = false;//from   w  w  w .  j  av  a2 s.c o  m
            if (skipHeader)
                continue;
        }
        List<Object> row = Lists.newArrayList();

        boolean blankRow = true;
        for (int i = 0; i < cellsNum; i++) {
            Object value = readValueFromCell(excelRow.getCell(i, Row.MissingCellPolicy.RETURN_NULL_AND_BLANK));

            if (blankRow && value != null && !String.valueOf(value).isEmpty()) {
                blankRow = false;
            }
            row.add(value);
        }
        if (blankRow)
            continue;
        boolean keepRow = true;
        for (RowPostProcessor<Collection<Object>> rowPostProcessor : rowPostProcessors) {
            keepRow = rowPostProcessor.process(row);
            if (!keepRow)
                break;
        }
        if (keepRow) {
            rows.add(row);
        }
    }
    return rows;
}

From source file:com.elecnor.ecosystem.helper.LocalLicenseHelper.java

public HashMap<String, Object> validateRowDataAndFetchBean(Row row, UserDetail userDetail) {
    int rowNumber = row.getRowNum();
    ArrayList<ExcelErrorDetails> rowErrorList = new ArrayList<ExcelErrorDetails>();
    String stringToCheck = "";
    UploadFileUtility upUtil = new UploadFileUtility();
    int colNum;//from  w  w w.j  av a 2s  .  c o  m
    boolean isRowHavingErrors = false;
    LicenseDirectory licenseDirectory = new LicenseDirectory();
    Map<String, Object> rowValidationReturn = new HashMap<String, Object>();

    colNum = ConstantUtil.LOCAL_LICENSE_DATA_LOCAL_JURISDICTION;
    try {
        stringToCheck = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
        licenseDirectory.setLocalJurisdiction(stringToCheck);
    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(
                upUtil.getExcelErrorDetails(rowNumber, colNum, ConstantUtil.ERROR_STRING_VALIDATION_ERROR));
        isRowHavingErrors = true;

    }
    stringToCheck = "";
    colNum = ConstantUtil.LOCAL_LICENSE_DATA_LICENSE_NO;
    try {
        stringToCheck = String
                .valueOf((int) row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getNumericCellValue());
        licenseDirectory.setLicenseNumber(stringToCheck);

    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(
                upUtil.getExcelErrorDetails(rowNumber, colNum, ConstantUtil.ERROR_INTEGER_VALIDATION_ERROR));
        isRowHavingErrors = true;

    }

    //validate Expiry date
    stringToCheck = "";
    colNum = ConstantUtil.LOCAL_LICENSE_DATA_EXPIRY_DATE;
    try {
        stringToCheck = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
        DateFormat format = new SimpleDateFormat("dd-mm-yyyy", Locale.ENGLISH);
        Date date = format.parse(stringToCheck);
        licenseDirectory.setExpiryDate(date);
    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(
                upUtil.getExcelErrorDetails(rowNumber, colNum, ConstantUtil.ERROR_STRING_VALIDATION_ERROR));
        isRowHavingErrors = true;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    licenseDirectory.setStatus("ACTIVE");
    licenseDirectory.setType("LOCAL");
    licenseDirectory.setLicenseSubmittedBy(userDetail);
    licenseDirectory.setDomainDetail(userDetail.getDomainDetail());
    //validate Primary Person

    stringToCheck = "";
    colNum = ConstantUtil.LOCAL_LICENSE_DATA_PRIMARY_PERSON;
    try {

        stringToCheck = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
        licenseDirectory.setPrimaryPerson(stringToCheck);

    } catch (Exception e) {

        licenseDirectory.setPrimaryPerson("");

    }
    ExcelErrorDetails excelErrorDetailsBasedOnBeanValidations = upUtil
            .getExcelErrorDetailsBasedOnBeanValidations(row.getRowNum(), licenseDirectory);
    if (excelErrorDetailsBasedOnBeanValidations != null) {
        isRowHavingErrors = true;
        rowErrorList.add(excelErrorDetailsBasedOnBeanValidations);
    }

    //}
    if (isRowHavingErrors) {
        rowValidationReturn.put("errorList", rowErrorList);
        rowValidationReturn.put("licenseDirectoryBean", null);

    } else {
        rowValidationReturn.put("errorList", null);
        rowValidationReturn.put("licenseDirectoryBean", licenseDirectory);
    }
    return (HashMap<String, Object>) rowValidationReturn;

}

From source file:com.elecnor.ecosystem.helper.StateLicenseHelper.java

public HashMap<String, Object> validateRowDataAndFetchBean(Row row, UserDetail userDetail) {
    int rowNumber = row.getRowNum();
    ArrayList<String> states = new ArrayList<String>();
    String states_temp[] = { "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
            "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa",
            "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota",
            "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey",
            "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon",
            "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah",
            "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" };

    for (int i = 0; i < states_temp.length; i++) {
        states.add(states_temp[i]);//from  w  w w .  j  a v a 2  s .c o m
    }
    ArrayList<ExcelErrorDetails> rowErrorList = new ArrayList<ExcelErrorDetails>();
    String stringToCheck = "";
    UploadFileUtility upUtil = new UploadFileUtility();
    int colNum;
    boolean isRowHavingErrors = false;
    LicenseDirectory licenseDirectory = new LicenseDirectory();
    Map<String, Object> rowValidationReturn = new HashMap<String, Object>();
    colNum = ConstantUtil.STATE_LICENSE_DATA_LICENSE_NO;
    try {

        stringToCheck = String
                .valueOf((int) row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getNumericCellValue());
        licenseDirectory.setLicenseNumber(stringToCheck);

    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(
                upUtil.getExcelErrorDetails(rowNumber, colNum, ConstantUtil.ERROR_STRING_VALIDATION_ERROR));
        isRowHavingErrors = true;
        illegalStateException.printStackTrace();
    }
    //validate state
    stringToCheck = "";
    colNum = ConstantUtil.STATE_LICENSE_DATA_STATE;
    try {
        stringToCheck = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getStringCellValue();

        licenseDirectory.setState(states.indexOf(stringToCheck));
    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(
                upUtil.getExcelErrorDetails(rowNumber, colNum, ConstantUtil.ERROR_STRING_VALIDATION_ERROR));
        isRowHavingErrors = true;
        illegalStateException.printStackTrace();
    }

    //validate Expiry date
    stringToCheck = "";
    colNum = ConstantUtil.STATE_LICENSE_DATA_EXPIRY_DATE;
    try {
        stringToCheck = String
                .valueOf((row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getStringCellValue().trim()));
        DateFormat format = new SimpleDateFormat("dd-mm-yyyy", Locale.ENGLISH);
        Date date = format.parse(stringToCheck);
        licenseDirectory.setExpiryDate(date);
    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(
                upUtil.getExcelErrorDetails(rowNumber, colNum, ConstantUtil.ERROR_STRING_VALIDATION_ERROR));
        isRowHavingErrors = true;
        illegalStateException.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    licenseDirectory.setStatus("ACTIVE");
    licenseDirectory.setType("STATE");
    licenseDirectory.setLicenseSubmittedBy(userDetail);
    licenseDirectory.setDomainDetail(userDetail.getDomainDetail());
    //validate Primary Person

    stringToCheck = "";
    colNum = ConstantUtil.STATE_LICENSE_DATA_PRIMARY_PERSON;
    try {

        stringToCheck = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
        licenseDirectory.setLicenseDescription(stringToCheck);

    } catch (Exception e) {

        licenseDirectory.setLicenseDescription("");
        e.printStackTrace();
    }
    ExcelErrorDetails excelErrorDetailsBasedOnBeanValidations = upUtil
            .getExcelErrorDetailsBasedOnBeanValidations(row.getRowNum(), licenseDirectory);
    if (excelErrorDetailsBasedOnBeanValidations != null) {
        isRowHavingErrors = true;
        rowErrorList.add(excelErrorDetailsBasedOnBeanValidations);
    }

    //}
    if (isRowHavingErrors) {
        rowValidationReturn.put("errorList", rowErrorList);
        rowValidationReturn.put("licenseDirectoryBean", null);

    } else {
        rowValidationReturn.put("errorList", null);
        rowValidationReturn.put("licenseDirectoryBean", licenseDirectory);
    }
    return (HashMap<String, Object>) rowValidationReturn;

}

From source file:com.elecnor.ecosystem.serviceimpl.LicenseDirectoryServiceImpl.java

License:Open Source License

public ArrayList<ExcelErrorDetails> validateRowData(Row row) {
    int rowNumber = row.getRowNum();
    ArrayList<ExcelErrorDetails> rowErrorList = new ArrayList<ExcelErrorDetails>();
    String stringToCheck = "";
    int colNum;//from w w  w  . j a va  2 s.c om
    String fieldToCheck = "";
    boolean valueNotValid = false;

    // validation for License Number
    fieldToCheck = "STATE_LICENSE_DATA_LICENSE_NO";
    colNum = readFromHeader(null, fieldToCheck);
    try {
        stringToCheck = String
                .valueOf((long) (row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getNumericCellValue()));
    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(getExcelErrorDetails(rowNumber, colNum, "License No. should not have characters"));
        valueNotValid = true;
    }
    if (!valueNotValid) {
        if (stringToCheck.equals("0")) {

            rowErrorList.add(getExcelErrorDetails(rowNumber, colNum, "License Number cannot be null"));
        }
    }
    valueNotValid = false;

    // validation for State
    fieldToCheck = "STATE_LICENSE_DATA_STATE";
    colNum = readFromHeader(null, fieldToCheck);
    try {
        stringToCheck = String
                .valueOf((int) (row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getNumericCellValue()));
    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(getExcelErrorDetails(rowNumber, colNum, "Choose state from the given options"));
        valueNotValid = true;
    }
    valueNotValid = false;

    // validation for Expiry Date
    fieldToCheck = "STATE_LICENSE_DATA_EXPIRY_DATE";
    colNum = readFromHeader(null, fieldToCheck);
    try {
        stringToCheck = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK).getStringCellValue();
    } catch (IllegalStateException illegalStateException) {
        rowErrorList.add(getExcelErrorDetails(rowNumber, colNum,
                "Expiry date should be in proper format and with '-' or '.' as separators"));
        valueNotValid = true;
    }
    if (!valueNotValid) {
        if (stringToCheck == null) {
            rowErrorList.add(getExcelErrorDetails(rowNumber, colNum, "Expiry Date cannot be null"));
        }
        if (!stringToCheck.matches("^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}$")) {
            rowErrorList.add(getExcelErrorDetails(rowNumber, colNum, "Wrong Date Format"));
        }
    }
    valueNotValid = false;

    if (!rowErrorList.isEmpty()) {
        return rowErrorList;
    } else
        return null;
}

From source file:com.elecnor.ecosystem.serviceimpl.LicenseDirectoryServiceImpl.java

License:Open Source License

public LicenseDirectory getStateLicenseDetails(Row row, DomainDetail domainDetail, UserDetail userDetail) {

    LicenseDirectory stateLicDirectory = new LicenseDirectory();
    String inputDateInString = "";
    Date inputDate = null;/* w w  w .j  a va 2  s .c o m*/
    DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
    String checkValue;

    stateLicDirectory.setLicenseSubmittedBy(userDetail);
    stateLicDirectory.setDomainDetail(domainDetail);
    stateLicDirectory.setType("STATE");
    stateLicDirectory.setStatus("ACTIVE");

    try {
        int stateId = getStateId(row.getCell(1, Row.CREATE_NULL_AS_BLANK).getStringCellValue().trim());
        if (stateId == -1) {
            stateLicDirectory.setState(null);
        } else {
            stateLicDirectory.setState(stateId);
        }
    } catch (Exception e1) {
        stateLicDirectory.setState(null);
    }

    try {
        checkValue = String.valueOf((long) (row.getCell(0, Row.CREATE_NULL_AS_BLANK).getNumericCellValue()));
        if (checkValue.equalsIgnoreCase("0")) {
            stateLicDirectory.setLicenseNumber(null);
        } else {
            stateLicDirectory.setLicenseNumber(checkValue);
        }
    } catch (Exception e1) {
        stateLicDirectory.setLicenseNumber(null);
    }

    try {
        inputDateInString = row.getCell(2, Row.CREATE_NULL_AS_BLANK).getStringCellValue().trim();
        inputDate = dateFormat.parse(inputDateInString);
        stateLicDirectory.setExpiryDate(inputDate);
    } catch (Exception e1) {
        stateLicDirectory.setExpiryDate(null);
    }

    try {
        stateLicDirectory
                .setPrimaryPerson(row.getCell(3, Row.CREATE_NULL_AS_BLANK).getStringCellValue().trim());
    } catch (Exception e) {
        stateLicDirectory.setPrimaryPerson("");
    }

    try {
        stateLicDirectory
                .setLicenseDescription(row.getCell(4, Row.CREATE_NULL_AS_BLANK).getStringCellValue().trim());
    } catch (Exception e) {
        stateLicDirectory.setLicenseDescription("");
    }

    return stateLicDirectory;
}