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

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

Introduction

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

Prototype

int getColumnIndex();

Source Link

Document

Returns column index of this cell

Usage

From source file:org.opencrx.kernel.portal.wizard.ImportAccountsFromXlsController.java

License:BSD License

/**
 * Read import definition (first row in excel sheet).
 * // ww  w . ja v a 2 s  . c o m
 * @param row
 * @param nRow
 * @param maxCell
 * @param recordDefinition
 */
public int readImportDefinition(Row row, int nRow, AccountRecordDefinition recordDefinition,
        Writer importReport) throws IOException {
    int maxCell = 0;
    importReport.append("<tr class=\"gridTableHeaderFull\">");
    importReport.append("  <td>#</td>");
    try {
        Iterator<Cell> cells = row.cellIterator();
        int idxCell = 0;
        while (cells.hasNext()) {
            Cell cell = cells.next();
            idxCell = cell.getColumnIndex();
            if (idxCell > maxCell) {
                maxCell = idxCell;
            }
            try {
                if ((cell.getCellType() == Cell.CELL_TYPE_STRING) && (cell.getStringCellValue() != null)) {
                    boolean isSearchAttribute = false;
                    String cellValue = (cell.getStringCellValue().trim());
                    recordDefinition.getColumns().put(idxCell, cellValue);
                    // get idx of select attributes
                    if (this.ATTR_EXTSTRING0.compareToIgnoreCase(cellValue) == 0) {
                        recordDefinition.setIdxExtString0(idxCell);
                        isSearchAttribute = true;
                    } else if (this.ATTR_FIRSTNAME.compareToIgnoreCase(cellValue) == 0) {
                        recordDefinition.setIdxFirstName(idxCell);
                        isSearchAttribute = true;
                    } else if (this.ATTR_LASTNAME.compareToIgnoreCase(cellValue) == 0) {
                        recordDefinition.setIdxLastName(idxCell);
                        isSearchAttribute = true;
                    } else if (this.ATTR_ALIASNAME.compareToIgnoreCase(cellValue) == 0) {
                        recordDefinition.setIdxAliasName(idxCell);
                        isSearchAttribute = true;
                    } else if (this.ATTR_EMAILADDRESS.compareToIgnoreCase(cellValue) == 0) {
                        recordDefinition.setIdxEMailAddress(idxCell);
                        isSearchAttribute = true;
                    } else if (this.ATTR_COMPANY.compareToIgnoreCase(cellValue) == 0) {
                        recordDefinition.setIdxCompany(idxCell);
                        isSearchAttribute = true;
                    } else if (this.ATTR_DTYPE.compareToIgnoreCase(cellValue) == 0) {
                        recordDefinition.setIdxDtype(idxCell);
                    } else if (this.ATTR_XRI.compareToIgnoreCase(cellValue) == 0) {
                        recordDefinition.setIdxXri(idxCell);
                        isSearchAttribute = true;
                    }
                    importReport.append("<td "
                            + (isSearchAttribute ? "class='searchAttr' title='attribute used for matching'"
                                    : "")
                            + "Col-" + DECIMAL_FORMAT_4.format(idxCell) + EOL_HTML + cellValue + "</td>");
                } else {
                    String cellType = null;
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_BLANK:
                        cellType = "CELL_TYPE_BLANK";
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        cellType = "CELL_TYPE_BOOLEAN";
                        break;
                    case Cell.CELL_TYPE_ERROR:
                        cellType = "CELL_TYPE_ERROR";
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        cellType = "CELL_TYPE_FORMULA";
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        cellType = "CELL_TYPE_NUMERIC";
                        break;
                    case Cell.CELL_TYPE_STRING:
                        cellType = "CELL_TYPE_STRING";
                    }
                    importReport.append("<td class=\"err\">c" + DECIMAL_FORMAT_4.format(idxCell)
                            + " [not a string cell]<br />Type is " + cellType + "</td>");
                }
            } catch (Exception ec) {
                new ServiceException(ec).log();
                importReport.append("<td class=\"err\">c" + DECIMAL_FORMAT_4.format(idxCell)
                        + " [unknown error]<br />" + ec.getMessage() + "</td>");
            }
        }
    } catch (Exception e) {
        new ServiceException(e).log();
        importReport.append("<td class=\"err\">ERROR in Attribute Row!</td>");
    }
    importReport.append("</tr>");
    return maxCell;
}

From source file:org.opencrx.kernel.portal.wizard.ImportAccountsFromXlsController.java

License:BSD License

/**
 * Read account record./*from ww w. j  a v  a2s .  c o m*/
 * 
 * @param row
 * @param nRow
 * @param maxCell
 * @param recordDefinition
 * @param record
 * @return
 * @throws ServiceException
 */
public void readAccountRecord(Row row, int nRow, int maxCell, AccountRecord record, Writer importReport,
        List<String> errors) throws ServiceException, IOException {
    importReport.append("<tr class=\"gridTableRowFull\">");
    importReport.append("<td>" + DECIMAL_FORMAT_4.format(nRow) + "</td>");
    AccountRecordDefinition recordDefinition = record.getRecordDefinition();
    Iterator<Cell> cells = row.cellIterator();
    int idxCell = 0;
    while (cells.hasNext()) {
        Cell cell = (Cell) cells.next();
        idxCell = cell.getColumnIndex();
        try {
            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                String cellValue = cell.getStringCellValue().trim();
                record.setFieldValue(idxCell, cellValue);
                if (idxCell == recordDefinition.getIdxDtype()) {
                    if (AccountType.Group.name().compareToIgnoreCase(cellValue) == 0) {
                        record.setTypeExplicitlySet(true);
                        record.setAccountType(AccountType.Group);
                        record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.ATTR_CLASS, " ok");
                    } else if (AccountType.LegalEntity.name().compareToIgnoreCase(cellValue) == 0) {
                        record.setTypeExplicitlySet(true);
                        record.setAccountType(AccountType.LegalEntity);
                        record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.ATTR_CLASS, " ok");
                    } else if (AccountType.UnspecifiedAccount.name().compareToIgnoreCase(cellValue) == 0) {
                        record.setTypeExplicitlySet(true);
                        record.setAccountType(AccountType.UnspecifiedAccount);
                        record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.ATTR_CLASS, " ok");
                    } else if (AccountType.Contact.name().compareToIgnoreCase(cellValue) == 0) {
                        record.setTypeExplicitlySet(true);
                        record.setAccountType(AccountType.Contact);
                        record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.ATTR_CLASS, " ok");
                    }
                } else if (idxCell == recordDefinition.getIdxExtString0()) {
                    record.setExtString0(cellValue);
                } else if (idxCell == recordDefinition.getIdxFirstName()) {
                    record.setFirstName(cellValue);
                } else if (idxCell == recordDefinition.getIdxLastName()) {
                    record.setLastName(cellValue);
                } else if (idxCell == recordDefinition.getIdxAliasName()) {
                    record.setAliasName(cellValue);
                } else if (idxCell == recordDefinition.getIdxEMailAddress()) {
                    record.setEmailAddress(cellValue);
                } else if (idxCell == recordDefinition.getIdxCompany()) {
                    record.setCompany(cellValue);
                } else if (idxCell == recordDefinition.getIdxXri()) {
                    record.setXriExplicitlySet(true);
                    record.setXri(cellValue);
                }
                record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.CONTENT,
                        (cellValue != null ? (cellValue.replace("\r\n", EOL_HTML)).replace("\n", EOL_HTML)
                                : ""));
            } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                BigDecimal cellValue = new BigDecimal(cell.getNumericCellValue());
                if (idxCell == recordDefinition.getIdxExtString0()) {
                    record.setExtString0(cellValue.toString());
                    record.setFieldValue(idxCell, record.getExtString0());
                } else {
                    record.setFieldValue(idxCell, cellValue);
                }
                record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.CONTENT,
                        cellValue.toString());
            } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
                boolean cellValue = cell.getBooleanCellValue();
                record.setFieldValue(idxCell, cellValue);
                record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.CONTENT,
                        (cellValue ? "TRUE" : "FALSE"));
            } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
                record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.ATTR_CLASS, " empty");
                record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.CONTENT, "&nbsp;");
            } else {
                record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.ATTR_CLASS, " err");
                record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.CONTENT,
                        "r" + DECIMAL_FORMAT_4.format(nRow) + ":c" + DECIMAL_FORMAT_4.format(idxCell)
                                + ": cell type '" + cell.getCellType() + "' not supported<br>");
            }
        } catch (Exception e) {
            ServiceException e0 = new ServiceException(e);
            e0.log();
            errors.add(e0.getMessage());
            record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.ATTR_CLASS, " err");
            record.appendImportStatus(idxCell, AccountRecord.ImportStatusElement.CONTENT,
                    "r" + DECIMAL_FORMAT_4.format(nRow) + ":c" + DECIMAL_FORMAT_4.format(idxCell)
                            + ": Unknown ERROR. See log.<br>");
        }
    }
}

From source file:org.openelis.bean.DataViewReportBean.java

License:Open Source License

/**
 * Creates and returns a workbook that gets converted to an Excel file; each
 * row in the workbook shows fields from some part of a sample and analytes
 * and values/* w  w  w  .j  a  v a 2s. c om*/
 * 
 * @param results
 *        the list of VOs containing result info to be shown
 * @param auxiliary
 *        the list of VOs containing aux data info to be shown
 * @param noResAux
 *        the list of VOs containing info to be shown when both results and
 *        aux data are excluded
 * @param testAnaResMap
 *        the map containing result analytes and values selected by the
 *        user; if an analyte or value is not in the map, the result is not
 *        shown
 * @param auxFieldValMap
 *        the map containing aux data analytes and values selected by the
 *        user; if an analyte or value is not in the map, the aux data is
 *        not shown
 * @param moduleName
 *        the name of a security module for the logged in user; the module's
 *        clause is used to restrict the fetched data to specific records
 *        e.g. organizations
 * @param showReportableColumnsOnly
 *        if true, only reportable column analytes are shown
 * @param headers
 *        the list of labels for the column headers
 * @param data
 *        the VO containing the user's choices for the data shown e.g. the
 *        meta keys for selected columns and "include" and "exclude" flags
 * @param smMap
 *        the map that provides the data for the columns belonging to
 *        various parts of a sample e.g. domain, organization, project etc.
 * @param status
 *        the percent completion in this ReportStatus is updated every time
 *        a new row is added to the workbook
 */
private XSSFWorkbook getWorkbook(List<DataViewResultVO> results, List<DataViewResultVO> auxiliary,
        List<DataViewResultVO> noResAux, HashMap<Integer, HashSet<String>> testAnaResMap,
        HashMap<Integer, HashSet<String>> auxFieldValMap, String moduleName, boolean showReportableColumnsOnly,
        ArrayList<String> headers, DataView1VO data, HashMap<Integer, SampleManager1> smMap,
        ReportStatus status) throws Exception {
    boolean excludeOverride, excludeRes, excludeAux, samOverridden, anaOverridden, addRow;
    int i, j, resIndex, auxIndex, noResAuxIndex, rowIndex, numRes, numAux, numNoResAux, lastCol, currCol;
    Integer samId, prevSamId, resAccNum, auxAccNum, itemId, anaId, prevAnaId, anaIndex;
    String value;
    SampleManager1 sm;
    XSSFWorkbook wb;
    XSSFSheet sheet;
    DataViewResultVO res;
    ResultViewDO rowRes, colRes;
    Row currRow, prevRow;
    RowData rd;
    Cell cell;
    ArrayList<Integer> maxChars;
    ArrayList<ResultViewDO> smResults;
    HashMap<String, Integer> colAnaMap;
    HashMap<Integer, HashSet<String>> anaValMap;

    numRes = results == null ? 0 : results.size();
    numAux = auxiliary == null ? 0 : auxiliary.size();
    numNoResAux = noResAux == null ? 0 : noResAux.size();
    excludeOverride = "Y".equals(data.getExcludeResultOverride());
    excludeRes = "Y".equals(data.getExcludeResults());
    excludeAux = "Y".equals(data.getExcludeAuxData());

    resIndex = 0;
    auxIndex = 0;
    noResAuxIndex = 0;
    lastCol = 0;
    currCol = 0;
    rowIndex = 1;
    prevSamId = null;
    prevAnaId = null;
    anaIndex = null;
    samOverridden = false;
    anaOverridden = false;
    currRow = null;
    prevRow = null;
    sm = null;
    wb = new XSSFWorkbook();
    sheet = wb.createSheet();
    colAnaMap = new HashMap<String, Integer>();
    maxChars = new ArrayList<Integer>();
    rd = new RowData();

    status.setMessage(Messages.get().report_genDataView());
    status.setPercentComplete(0);
    session.setAttribute("DataViewReportStatus", status);

    /*
     * the lists of results and aux data are iterated through until there
     * are no more elements left in each of them to read from
     */
    while (resIndex < numRes || auxIndex < numAux || noResAuxIndex < numNoResAux) {
        /*
         * the user wants to stop the report
         */
        if (ReportStatus.Status.CANCEL.equals(status.getStatus())) {
            status.setMessage(Messages.get().report_stopped());
            return null;
        }

        status.setPercentComplete(
                100 * (resIndex + auxIndex + noResAuxIndex) / (numRes + numAux + numNoResAux));
        res = null;
        anaValMap = null;
        value = null;
        if (excludeRes && excludeAux) {
            res = noResAux.get(noResAuxIndex++);
        } else {
            if (resIndex < numRes && auxIndex < numAux) {
                resAccNum = results.get(resIndex).getSampleAccessionNumber();
                auxAccNum = auxiliary.get(auxIndex).getSampleAccessionNumber();
                /*
                 * if this result's accession number is less than or equal
                 * to this aux data's, add a row for this result, otherwise
                 * add a row for the aux data; this makes sure that the
                 * results for a sample are shown before the aux data;
                 * accession numbers are compared instead of sample ids
                 * because the former is the field shown in the report and
                 * not the latter
                 */
                if (resAccNum <= auxAccNum) {
                    res = results.get(resIndex++);
                    anaValMap = testAnaResMap;
                } else {
                    res = auxiliary.get(auxIndex++);
                    anaValMap = auxFieldValMap;
                }
            } else if (resIndex < numRes) {
                /*
                 * no more aux data left to show
                 */
                res = results.get(resIndex++);
                anaValMap = testAnaResMap;
            } else if (auxIndex < numAux) {
                /*
                 * no more results left to show
                 */
                res = auxiliary.get(auxIndex++);
                anaValMap = auxFieldValMap;
            }
        }

        samId = res.getSampleId();
        itemId = res.getSampleItemId();
        anaId = res.getAnalysisId();

        if (!samId.equals(prevSamId)) {
            /*
             * don't show any data for this sample if it's overridden and
             * such samples are excluded; whether the sample is overridden
             * is checked even if such samples are not excluded because
             * overridden result values are not shown in the report
             */
            sm = smMap.get(samId);
            samOverridden = false;
            if ((getSampleQAs(sm) != null)) {
                for (SampleQaEventViewDO sqa : getSampleQAs(sm)) {
                    if (Constants.dictionary().QAEVENT_OVERRIDE.equals(sqa.getTypeId())) {
                        samOverridden = true;
                        if (excludeOverride)
                            prevSamId = samId;
                        break;
                    }
                }
            }
        }

        if (samOverridden && excludeOverride) {
            prevSamId = samId;
            continue;
        }

        /*
         * don't show any data for this analysis if it's overridden and such
         * analyses are excluded; whether the analysis is overridden is
         * checked even if such analyses are not excluded because overridden
         * values are not shown in the report
         */
        if (anaId != null) {
            if (!anaId.equals(prevAnaId)) {
                anaOverridden = false;
                if ((getAnalysisQAs(sm) != null)) {
                    for (AnalysisQaEventViewDO aqa : getAnalysisQAs(sm)) {
                        if (aqa.getAnalysisId().equals(anaId)
                                && Constants.dictionary().QAEVENT_OVERRIDE.equals(aqa.getTypeId())) {
                            anaOverridden = true;
                            if (excludeOverride)
                                break;
                        }
                    }
                }
            }
            if (anaOverridden && excludeOverride) {
                prevSamId = samId;
                prevAnaId = anaId;
                continue;
            }
        }

        if (anaValMap != null) {
            /*
             * show this result or aux data only if its value was selected
             * by the user
             */
            value = getValue(anaValMap, res.getAnalyteId(), res.getValue(), res.getTypeId());
            if (value == null) {
                prevSamId = samId;
                prevAnaId = anaId;
                continue;
            }
        }

        currRow = sheet.createRow(rowIndex++);

        /*
         * fill the passed row's cells for all columns except the ones for
         * analytes and values
         */
        setBaseCells(sm, itemId, anaId, rd, data.getColumns(), moduleName != null, wb, currRow, maxChars);

        if (value != null) {
            /*
             * this row is for either a result or aux data; show the analyte
             */
            cell = currRow.createCell(currRow.getPhysicalNumberOfCells());
            setCellValue(cell, res.getAnalyteName(), null);
            setMaxChars(cell.getColumnIndex(), res.getAnalyteName(), maxChars, null);
            cell = currRow.createCell(currRow.getPhysicalNumberOfCells());
            if (anaId != null && !excludeRes) {
                /*
                 * this row is for a result; show the value only if the
                 * analysis and sample are not overridden
                 */
                if (!anaOverridden && !samOverridden)
                    setCellValue(cell, value, null);
                setMaxChars(cell.getColumnIndex(), cell.getStringCellValue(), maxChars, null);

                /*
                 * if this analyte has column analytes, show them in the
                 * header and their values in the columns; results for a
                 * sample can be null if it has no results with values but
                 * has aux data with values and aux data is not excluded
                 */
                smResults = getResults(sm);
                if (smResults != null) {
                    for (i = 0; i < smResults.size(); i++) {
                        rowRes = smResults.get(i);
                        if (!res.getId().equals(rowRes.getId()))
                            continue;
                        j = i + 1;
                        if (j < smResults.size() && "Y".equals(smResults.get(j).getIsColumn())) {
                            /*
                             * this analyte has column analytes; "lastCol"
                             * is the right-most column in the workbook; if
                             * an analyte doesn't have a column yet, that
                             * column will be added after "lastCol";
                             * "currCol" keeps track of the current column
                             */
                            if (lastCol == 0)
                                lastCol = currRow.getPhysicalNumberOfCells();

                            currCol = currRow.getPhysicalNumberOfCells();
                            while (j < smResults.size()) {
                                colRes = smResults.get(j++);
                                if ("N".equals(colRes.getIsColumn()))
                                    break;
                                if (showReportableColumnsOnly && "N".equals(colRes.getIsReportable()))
                                    continue;
                                anaIndex = colAnaMap.get(colRes.getAnalyte());

                                /*
                                 * if this column analyte's name is not
                                 * found in the map, create a new column and
                                 * start adding values in it; set the value
                                 * in this cell if the analyte is shown in
                                 * this column; if the analyte is not shown
                                 * in this column, find the column in which
                                 * it is shown and set the value
                                 */
                                if (anaIndex == null) {
                                    anaIndex = lastCol++;
                                    colAnaMap.put(colRes.getAnalyte(), anaIndex);
                                    headers.add(colRes.getAnalyte());
                                    setMaxChars(cell.getColumnIndex(), colRes.getAnalyte(), maxChars, null);
                                    cell = currRow.createCell(anaIndex);
                                } else if (anaIndex == currCol) {
                                    cell = currRow.createCell(currCol++);
                                } else {
                                    cell = currRow.createCell(anaIndex);
                                }

                                /*
                                 * set the value if the analysis and sample
                                 * are not overridden
                                 */
                                if (!anaOverridden && !samOverridden)
                                    setCellValue(cell, getValue(colRes.getValue(), colRes.getTypeId()), null);
                                setMaxChars(cell.getColumnIndex(), cell.getStringCellValue(), maxChars, null);
                            }
                        }
                    }
                }
            } else {
                /*
                 * this row is for an aux data; show the value
                 */
                setCellValue(cell, value, null);
                setMaxChars(cell.getColumnIndex(), value, maxChars, null);
            }
        }

        prevAnaId = anaId;
        prevSamId = samId;

        /*
         * an empty row can't be created and then added to the sheet, it has
         * to be obtained from the sheet; thus it has to be removed if it
         * shouldn't be shown because it has the same data as the previous
         * row in all cells; this can happen if e.g. a user selects only
         * container and sample type but all sample items in a sample have
         * the same values for these fields
         */
        if (isSameDataInRows(currRow, prevRow)) {
            sheet.removeRow(currRow);
            rowIndex--;
        } else {
            prevRow = currRow;
        }
    }

    /*
     * add the header row and set the header labels for all columns
     */
    setHeaderCells(sheet, wb, headers, maxChars);

    /*
     * make each column wide enough to show the longest string in it; the
     * width for each column is set as the maximum number of characters in
     * that column multiplied by 256; this is because the default width of
     * one character is 1/256 units in Excel
     */
    for (i = 0; i < maxChars.size(); i++)
        sheet.setColumnWidth(i, maxChars.get(i) * 256);

    return wb;
}

From source file:org.openelis.bean.DataViewReportBean.java

License:Open Source License

/**
 * Fills all cells in "row" except the ones for analytes and values; the
 * filled cells include the ones for sample, domain, organization, sample
 * item, analysis etc.//from   w  ww  .j  a  v  a2  s .  com
 * 
 * @param sm
 *        the manager for the sample whose data or whose children's data is
 *        being shown in the row
 * @param sampleItemId
 *        the id of the sample item whose data or whose children's data is
 *        being shown in the row
 * @param analysisId
 *        the id of the analysis whose data or whose children's data is
 *        being shown in the row
 * @param rd
 *        the object that contains data that stays the same between rows
 *        that belong to the same sample, sample item or analysis, but needs
 *        to be updated if one or more of them change; if one of these is
 *        different between this row and the previous row, the appropriate
 *        fields in the object are updated
 * @param columns
 *        the list of meta keys for the columns selected by the user
 * @param forWeb
 *        if true, the report is run for an external user, otherwise it's
 *        run for an internal user; this is used to show different
 *        information in the same column e.g qa event reporting text for
 *        external users as opposed to name for internal ones
 * @param wb
 *        the workbook whose rows are being filled
 * @param row
 *        the row whose cells are being filled
 * @param maxChars
 *        the list containing the maximum number of characters in each
 *        column; it's updated a when new value is set in a cell
 * @throws Exception
 */
private void setBaseCells(SampleManager1 sm, Integer sampleItemId, Integer analysisId, RowData rd,
        ArrayList<String> columns, boolean forWeb, XSSFWorkbook wb, Row row, ArrayList<Integer> maxChars)
        throws Exception {
    String column, pattern;
    Object value;
    SampleDO s;
    SampleEnvironmentalDO se;
    SampleSDWISViewDO ss;
    SampleClinicalViewDO sc;
    SampleNeonatalViewDO sn;
    SamplePTDO sp;
    SampleAnimalDO sa;
    Cell cell;
    CellStyle style;
    ArrayList<String> labels;
    HashMap<String, CellStyle> dtStyles;

    if (columns == null)
        return;

    s = getSample(sm);
    se = getSampleEnvironmental(sm);
    ss = getSampleSDWIS(sm);
    sc = getSampleClinical(sm);
    sn = getSampleNeonatal(sm);
    sp = getSamplePT(sm);
    sa = getSampleAnimal(sm);

    labels = new ArrayList<String>();

    if (!s.getId().equals(rd.sampleId)) {
        rd.clear();
        rd.sampleId = s.getId();
        /*
         * find the report-to organization
         */
        if (getOrganizations(sm) != null) {
            for (SampleOrganizationViewDO data : getOrganizations(sm)) {
                if (Constants.dictionary().ORG_REPORT_TO.equals(data.getTypeId()))
                    rd.reportToOrg = data;
                else if (Constants.dictionary().ORG_BILL_TO.equals(data.getTypeId()))
                    rd.billToOrg = data;
            }
        }

        /*
         * for external clients, internal qa events are not shown and the qa
         * event's reporting text is shown; otherwise internal qa events are
         * shown and the qa event's name is shown
         */
        rd.sampleQAs = null;
        if (getSampleQAs(sm) != null) {
            labels.clear();
            for (SampleQaEventViewDO data : getSampleQAs(sm)) {
                if (forWeb && Constants.dictionary().QAEVENT_INTERNAL.equals(data.getTypeId()))
                    continue;
                labels.add(forWeb ? data.getQaEventReportingText() : data.getQaEventName());
            }
            rd.sampleQAs = DataBaseUtil.concatWithSeparator(labels, forWeb ? " " : ", ");
        }

        /*
         * for external users show only the first permanent project; for
         * internal users, show all projects
         */
        if (getProjects(sm) != null) {
            labels.clear();
            for (SampleProjectViewDO data : getProjects(sm)) {
                if (forWeb) {
                    if ("Y".equals(data.getIsPermanent())) {
                        labels.add(data.getProjectName());
                        break;
                    }
                } else {
                    labels.add(data.getProjectName());
                }
            }
            rd.projNames = DataBaseUtil.concatWithSeparator(labels, ", ");
        }
    }

    if (sampleItemId != null && !sampleItemId.equals(rd.sampleItemId)) {
        /*
         * find the item with the passed id
         */
        for (SampleItemViewDO data : getItems(sm)) {
            if (data.getId().equals(sampleItemId)) {
                rd.sampleItem = data;
                break;
            }
        }
    } else if (sampleItemId == null) {
        rd.sampleItem = null;
    }

    if (analysisId != null && !analysisId.equals(rd.analysisId)) {
        /*
         * find the analysis with the passed id
         */
        for (AnalysisViewDO data : getAnalyses(sm)) {
            if (data.getId().equals(analysisId)) {
                rd.analysis = data;
                break;
            }
        }
        /*
         * find the names of the users who completed and/or released the
         * analysis
         */
        rd.completedBy = null;
        rd.releasedBy = null;
        if (getUsers(sm) != null) {
            labels.clear();
            for (AnalysisUserViewDO data : getUsers(sm)) {
                if (!data.getAnalysisId().equals(analysisId))
                    continue;
                if (Constants.dictionary().AN_USER_AC_COMPLETED.equals(data.getActionId()))
                    labels.add(data.getSystemUser());
                else if (Constants.dictionary().AN_USER_AC_RELEASED.equals(data.getActionId()))
                    rd.releasedBy = data.getSystemUser();
            }
            rd.completedBy = DataBaseUtil.concatWithSeparator(labels, ", ");
        }

        /*
         * find the qa events for the analysis; for external clients,
         * internal qa events are not shown and the qa event's reporting
         * text is shown; otherwise internal qa events are shown and the qa
         * event's name is shown
         */
        rd.analysisQAs = null;
        if (getAnalysisQAs(sm) != null) {
            labels.clear();
            for (AnalysisQaEventViewDO data : getAnalysisQAs(sm)) {
                if (!data.getAnalysisId().equals(analysisId)
                        || (forWeb && Constants.dictionary().QAEVENT_INTERNAL.equals(data.getTypeId())))
                    continue;

                labels.add(forWeb ? data.getQaEventReportingText() : data.getQaEventName());
            }
            rd.analysisQAs = DataBaseUtil.concatWithSeparator(labels, forWeb ? " " : ", ");
        }
    } else if (analysisId == null) {
        rd.analysis = null;
    }

    /*
     * set the label for each column
     */
    dtStyles = new HashMap<String, CellStyle>();
    for (int i = 0; i < columns.size(); i++) {
        column = columns.get(i);
        value = null;
        pattern = null;
        switch (column) {
        /*
         * sample columns
         */
        case SampleWebMeta.ACCESSION_NUMBER:
            value = s.getAccessionNumber();
            break;
        case SampleWebMeta.REVISION:
            value = s.getRevision();
            break;
        case SampleWebMeta.COLLECTION_DATE:
            if (rd.collDateTime == null) {
                /*
                 * combine the collected date and time to form the label
                 * for this column; "collDateTime" is set to empty
                 * string and not null so that it isn't tried to be
                 * created again until the sample changes; at that time
                 * it gets set to null before entering the switch-case
                 */
                rd.collDateTime = getDateTime(s.getCollectionDate(), s.getCollectionTime());
            }
            value = rd.collDateTime;
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.RECEIVED_DATE:
            value = s.getReceivedDate();
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.ENTERED_DATE:
            value = s.getEnteredDate();
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.RELEASED_DATE:
            value = s.getReleasedDate();
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.STATUS_ID:
            value = getDictionaryLabel(s.getStatusId());
            break;
        case SampleWebMeta.SAMPLE_QA_EVENT_QA_EVENT_NAME:
            value = rd.sampleQAs;
            break;
        case SampleWebMeta.PROJECT_NAME:
            value = rd.projNames;
            break;
        case SampleWebMeta.CLIENT_REFERENCE_HEADER:
            value = s.getClientReference();
            break;
        /*
         * organization/report-to columns
         */
        case SampleWebMeta.SAMPLE_ORG_ID:
        case SampleWebMeta.REPORT_TO_ORG_ID:
            value = rd.reportToOrg != null ? rd.reportToOrg.getOrganizationId() : null;
            break;
        case SampleWebMeta.ORG_NAME:
        case SampleWebMeta.REPORT_TO_ORG_NAME:
            value = rd.reportToOrg != null ? rd.reportToOrg.getOrganizationName() : null;
            break;
        case SampleWebMeta.SAMPLE_ORG_ATTENTION:
        case SampleWebMeta.REPORT_TO_ATTENTION:
            value = rd.reportToOrg != null ? rd.reportToOrg.getOrganizationAttention() : null;
            break;
        case SampleWebMeta.ADDR_MULTIPLE_UNIT:
        case SampleWebMeta.REPORT_TO_ADDR_MULTIPLE_UNIT:
            value = rd.reportToOrg != null ? rd.reportToOrg.getOrganizationMultipleUnit() : null;
            break;
        case SampleWebMeta.ADDR_STREET_ADDRESS:
        case SampleWebMeta.REPORT_TO_ADDR_STREET_ADDRESS:
            value = rd.reportToOrg != null ? rd.reportToOrg.getOrganizationStreetAddress() : null;
            break;
        case SampleWebMeta.ADDR_CITY:
        case SampleWebMeta.REPORT_TO_ADDR_CITY:
            value = rd.reportToOrg != null ? rd.reportToOrg.getOrganizationCity() : null;
            break;
        case SampleWebMeta.ADDR_STATE:
        case SampleWebMeta.REPORT_TO_ADDR_STATE:
            value = rd.reportToOrg != null ? rd.reportToOrg.getOrganizationState() : null;
            break;
        case SampleWebMeta.ADDR_ZIP_CODE:
        case SampleWebMeta.REPORT_TO_ADDR_ZIP_CODE:
            value = rd.reportToOrg != null ? rd.reportToOrg.getOrganizationZipCode() : null;
            break;
        /*
         * bill-to columns
         */
        case SampleWebMeta.BILL_TO_ORG_ID:
            value = rd.billToOrg != null ? rd.billToOrg.getOrganizationId() : null;
            break;
        case SampleWebMeta.BILL_TO_ORG_NAME:
            value = rd.billToOrg != null ? rd.billToOrg.getOrganizationName() : null;
            break;
        case SampleWebMeta.BILL_TO_ATTENTION:
            value = rd.billToOrg != null ? rd.billToOrg.getOrganizationAttention() : null;
            break;
        case SampleWebMeta.BILL_TO_ADDR_MULTIPLE_UNIT:
            value = rd.billToOrg != null ? rd.billToOrg.getOrganizationMultipleUnit() : null;
            break;
        case SampleWebMeta.BILL_TO_ADDR_STREET_ADDRESS:
            value = rd.billToOrg != null ? rd.billToOrg.getOrganizationStreetAddress() : null;
            break;
        case SampleWebMeta.BILL_TO_ADDR_CITY:
            value = rd.billToOrg != null ? rd.billToOrg.getOrganizationCity() : null;
            break;
        case SampleWebMeta.BILL_TO_ADDR_STATE:
            value = rd.billToOrg != null ? rd.billToOrg.getOrganizationState() : null;
            break;
        case SampleWebMeta.BILL_TO_ADDR_ZIP_CODE:
            value = rd.billToOrg != null ? rd.billToOrg.getOrganizationZipCode() : null;
            break;
        /*
         * sample item columns
         */
        case SampleWebMeta.ITEM_TYPE_OF_SAMPLE_ID:
            value = rd.sampleItem != null ? rd.sampleItem.getTypeOfSample() : null;
            break;
        case SampleWebMeta.ITEM_SOURCE_OF_SAMPLE_ID:
            value = rd.sampleItem != null ? rd.sampleItem.getSourceOfSample() : null;
            break;
        case SampleWebMeta.ITEM_SOURCE_OTHER:
            value = rd.sampleItem != null ? rd.sampleItem.getSourceOther() : null;
            break;
        case SampleWebMeta.ITEM_CONTAINER_ID:
            value = rd.sampleItem != null ? rd.sampleItem.getContainer() : null;
            break;
        case SampleWebMeta.ITEM_CONTAINER_REFERENCE:
            value = rd.sampleItem != null ? rd.sampleItem.getContainerReference() : null;
            break;
        case SampleWebMeta.ITEM_ITEM_SEQUENCE:
            value = rd.sampleItem != null ? rd.sampleItem.getItemSequence() : null;
            break;
        /*
         * analysis columns
         */
        case SampleWebMeta.ANALYSIS_ID:
            value = rd.analysis != null ? rd.analysis.getId() : null;
            break;
        case SampleWebMeta.ANALYSIS_TEST_NAME_HEADER:
            value = null;
            if (rd.analysis != null)
                value = forWeb ? rd.analysis.getTestReportingDescription() : rd.analysis.getTestName();
            break;
        case SampleWebMeta.ANALYSIS_METHOD_NAME_HEADER:
            value = null;
            if (rd.analysis != null)
                value = forWeb ? rd.analysis.getMethodReportingDescription() : rd.analysis.getMethodName();
            break;
        case SampleWebMeta.ANALYSIS_STATUS_ID_HEADER:
            value = getDictionaryLabel(rd.analysis != null ? rd.analysis.getStatusId() : null);
            break;
        case SampleWebMeta.ANALYSIS_REVISION:
            value = rd.analysis != null ? rd.analysis.getRevision() : null;
            break;
        case SampleWebMeta.ANALYSIS_IS_REPORTABLE_HEADER:
            value = getYesNoLabel(rd.analysis != null ? rd.analysis.getIsReportable() : null);
            break;
        case SampleWebMeta.ANALYSIS_UNIT_OF_MEASURE_ID:
            value = getDictionaryLabel(rd.analysis != null ? rd.analysis.getUnitOfMeasureId() : null);
            break;
        case SampleWebMeta.ANALYSIS_QA_EVENT_QA_EVENT_NAME:
            /*
             * for external clients, both sample and analysis qa events
             * are shown in the same column
             */
            value = forWeb ? DataBaseUtil.concatWithSeparator(rd.sampleQAs, " ", rd.analysisQAs)
                    : rd.analysisQAs;
            break;
        case SampleWebMeta.ANALYSIS_COMPLETED_DATE:
            value = rd.analysis != null ? rd.analysis.getCompletedDate() : null;
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.ANALYSIS_COMPLETED_BY:
            value = rd.completedBy;
            break;
        case SampleWebMeta.ANALYSIS_RELEASED_DATE:
            value = rd.analysis != null ? rd.analysis.getReleasedDate() : null;
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.ANALYSIS_RELEASED_BY:
            value = rd.releasedBy;
            break;
        case SampleWebMeta.ANALYSIS_STARTED_DATE:
            value = rd.analysis != null ? rd.analysis.getStartedDate() : null;
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.ANALYSIS_PRINTED_DATE:
            value = rd.analysis != null ? rd.analysis.getPrintedDate() : null;
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.ANALYSIS_SECTION_NAME:
            value = rd.analysis != null ? rd.analysis.getSectionName() : null;
            break;
        case SampleWebMeta.ANALYSIS_TYPE_ID:
            value = getDictionaryLabel(rd.analysis != null ? rd.analysis.getTypeId() : null);
            break;
        /*
         * environmental columns
         */
        case SampleWebMeta.ENV_IS_HAZARDOUS:
            value = getYesNoLabel(se != null ? se.getIsHazardous() : null);
            break;
        case SampleWebMeta.ENV_PRIORITY:
            value = se != null ? se.getPriority() : null;
            break;
        case SampleWebMeta.ENV_COLLECTOR_HEADER:
            value = se != null ? se.getCollector() : null;
            break;
        case SampleWebMeta.ENV_COLLECTOR_PHONE:
            value = se != null ? se.getCollectorPhone() : null;
            break;
        case SampleWebMeta.ENV_DESCRIPTION:
            value = se != null ? se.getDescription() : null;
            break;
        case SampleWebMeta.ENV_LOCATION:
            value = se != null ? se.getLocation() : null;
            break;
        case SampleWebMeta.LOCATION_ADDR_MULTIPLE_UNIT:
            value = se != null ? se.getLocationAddress().getMultipleUnit() : null;
            break;
        case SampleWebMeta.LOCATION_ADDR_STREET_ADDRESS:
            value = se != null ? se.getLocationAddress().getStreetAddress() : null;
            break;
        case SampleWebMeta.LOCATION_ADDR_CITY:
            value = se != null ? se.getLocationAddress().getCity() : null;
            break;
        case SampleWebMeta.LOCATION_ADDR_STATE:
            value = se != null ? se.getLocationAddress().getState() : null;
            break;
        case SampleWebMeta.LOCATION_ADDR_ZIP_CODE:
            value = se != null ? se.getLocationAddress().getZipCode() : null;
            break;
        case SampleWebMeta.LOCATION_ADDR_COUNTRY:
            value = se != null ? se.getLocationAddress().getCountry() : null;
            break;
        /*
         * sdwis columns
         */
        case SampleWebMeta.SDWIS_PWS_ID:
            value = ss != null ? ss.getPwsNumber0() : null;
            break;
        case SampleWebMeta.PWS_NAME:
            value = ss != null ? ss.getPwsName() : null;
            break;
        case SampleWebMeta.SDWIS_STATE_LAB_ID:
            value = ss != null ? ss.getStateLabId() : null;
            break;
        case SampleWebMeta.SDWIS_FACILITY_ID:
            value = ss != null ? ss.getFacilityId() : null;
            break;
        case SampleWebMeta.SDWIS_SAMPLE_TYPE_ID:
            value = getDictionaryLabel(ss != null ? ss.getSampleTypeId() : null);
            break;
        case SampleWebMeta.SDWIS_SAMPLE_CATEGORY_ID:
            value = getDictionaryLabel(ss != null ? ss.getSampleCategoryId() : null);
            break;
        case SampleWebMeta.SDWIS_SAMPLE_POINT_ID:
            value = ss != null ? ss.getSamplePointId() : null;
            break;
        case SampleWebMeta.SDWIS_LOCATION:
            value = ss != null ? ss.getLocation() : null;
            break;
        case SampleWebMeta.SDWIS_PRIORITY:
            value = ss != null ? ss.getPriority() : null;
            break;
        case SampleWebMeta.SDWIS_COLLECTOR_HEADER:
            value = ss != null ? ss.getCollector() : null;
            break;
        /*
         * clinical columns
         */
        case SampleWebMeta.CLIN_PATIENT_ID:
            value = sc != null ? sc.getPatientId() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_LAST_NAME_HEADER:
            value = sc != null ? sc.getPatient().getLastName() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_FIRST_NAME_HEADER:
            value = sc != null ? sc.getPatient().getFirstName() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_BIRTH_DATE:
            value = sc != null ? sc.getPatient().getBirthDate() : null;
            pattern = Messages.get().gen_datePattern();
            break;
        case SampleWebMeta.CLIN_PATIENT_NATIONAL_ID:
            value = sc != null ? sc.getPatient().getNationalId() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_ADDR_MULTIPLE_UNIT:
            value = sc != null ? sc.getPatient().getAddress().getMultipleUnit() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_ADDR_STREET_ADDRESS:
            value = sc != null ? sc.getPatient().getAddress().getStreetAddress() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_ADDR_CITY:
            value = sc != null ? sc.getPatient().getAddress().getCity() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_ADDR_STATE:
            value = sc != null ? sc.getPatient().getAddress().getState() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_ADDR_ZIP_CODE:
            value = sc != null ? sc.getPatient().getAddress().getZipCode() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_ADDR_HOME_PHONE:
            value = sc != null ? sc.getPatient().getAddress().getHomePhone() : null;
            break;
        case SampleWebMeta.CLIN_PATIENT_GENDER_ID:
            value = getDictionaryLabel(sc != null ? sc.getPatient().getGenderId() : null);
            break;
        case SampleWebMeta.CLIN_PATIENT_RACE_ID:
            value = getDictionaryLabel(sc != null ? sc.getPatient().getRaceId() : null);
            break;
        case SampleWebMeta.CLIN_PATIENT_ETHNICITY_ID:
            value = getDictionaryLabel(sc != null ? sc.getPatient().getEthnicityId() : null);
            break;
        case SampleWebMeta.CLIN_PROVIDER_LAST_NAME:
            if (sc != null)
                value = sc.getProvider() != null ? sc.getProvider().getLastName() : null;
            break;
        case SampleWebMeta.CLIN_PROVIDER_FIRST_NAME:
            if (sc != null)
                value = sc.getProvider() != null ? sc.getProvider().getFirstName() : null;
            break;
        case SampleWebMeta.CLIN_PROVIDER_PHONE:
            value = sc != null ? sc.getProviderPhone() : null;
            break;
        /*
         * neonatal columns
         */
        case SampleWebMeta.NEO_PATIENT_ID:
            value = sn != null ? sn.getPatientId() : null;
            break;
        case SampleWebMeta.NEO_PATIENT_LAST_NAME:
            value = sn != null ? sn.getPatient().getLastName() : null;
            break;
        case SampleWebMeta.NEO_PATIENT_FIRST_NAME:
            value = sn != null ? sn.getPatient().getFirstName() : null;
            break;
        case SampleWebMeta.NEO_PATIENT_BIRTH_DATE:
            if (rd.birthDateTime == null) {
                /*
                 * combine the birth date and time to form the label for
                 * this column; "birthDateTime" is set to empty string
                 * and not null so that it isn't tried to be created
                 * again until the sample changes; at that time it gets
                 * set to null before entering the switch-case
                 */
                rd.birthDateTime = getDateTime(sn.getPatient().getBirthDate(), sn.getPatient().getBirthTime());
            }
            value = rd.birthDateTime;
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.NEO_PATIENT_ADDR_MULTIPLE_UNIT:
            value = sn != null ? sn.getPatient().getAddress().getMultipleUnit() : null;
            break;
        case SampleWebMeta.NEO_PATIENT_ADDR_STREET_ADDRESS:
            value = sn != null ? sn.getPatient().getAddress().getStreetAddress() : null;
            break;
        case SampleWebMeta.NEO_PATIENT_ADDR_CITY:
            value = sn != null ? sn.getPatient().getAddress().getCity() : null;
            break;
        case SampleWebMeta.NEO_PATIENT_ADDR_STATE:
            value = sn != null ? sn.getPatient().getAddress().getState() : null;
            break;
        case SampleWebMeta.NEO_PATIENT_ADDR_ZIP_CODE:
            value = sn != null ? sn.getPatient().getAddress().getZipCode() : null;
            break;
        case SampleWebMeta.NEO_PATIENT_GENDER_ID:
            value = getDictionaryLabel(sn != null ? sn.getPatient().getGenderId() : null);
            break;
        case SampleWebMeta.NEO_PATIENT_RACE_ID:
            value = getDictionaryLabel(sn != null ? sn.getPatient().getRaceId() : null);
            break;
        case SampleWebMeta.NEO_PATIENT_ETHNICITY_ID:
            value = getDictionaryLabel(sn != null ? sn.getPatient().getEthnicityId() : null);
            break;
        case SampleWebMeta.NEO_IS_NICU:
            value = getYesNoLabel(sn != null ? sn.getIsNicu() : null);
            break;
        case SampleWebMeta.NEO_BIRTH_ORDER:
            value = sn != null ? sn.getBirthOrder() : null;
            break;
        case SampleWebMeta.NEO_GESTATIONAL_AGE:
            value = sn != null ? sn.getGestationalAge() : null;
            break;
        case SampleWebMeta.NEO_FEEDING_ID:
            value = getDictionaryLabel(sn != null ? sn.getFeedingId() : null);
            break;
        case SampleWebMeta.NEO_WEIGHT:
            value = sn != null ? sn.getWeight() : null;
            break;
        case SampleWebMeta.NEO_IS_TRANSFUSED:
            value = getYesNoLabel(sn != null ? sn.getIsTransfused() : null);
            break;
        case SampleWebMeta.NEO_TRANSFUSION_DATE:
            value = sn != null ? sn.getTransfusionDate() : null;
            pattern = Messages.get().gen_datePattern();
            break;
        case SampleWebMeta.NEO_IS_REPEAT:
            value = getYesNoLabel(sn != null ? sn.getIsRepeat() : null);
            break;
        case SampleWebMeta.NEO_COLLECTION_AGE:
            value = sn != null ? sn.getCollectionAge() : null;
            break;
        case SampleWebMeta.NEO_IS_COLLECTION_VALID:
            value = getYesNoLabel(sn != null ? sn.getIsCollectionValid() : null);
            break;
        case SampleWebMeta.NEO_FORM_NUMBER:
            value = sn != null ? sn.getFormNumber() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_ID:
            value = sn != null ? sn.getNextOfKinId() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_LAST_NAME:
            value = sn != null ? sn.getNextOfKin().getLastName() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_MIDDLE_NAME:
            value = sn != null ? sn.getNextOfKin().getMiddleName() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_FIRST_NAME:
            value = sn != null ? sn.getNextOfKin().getFirstName() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_RELATION_ID:
            value = getDictionaryLabel(sn != null ? sn.getNextOfKinRelationId() : null);
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_BIRTH_DATE:
            value = sn != null ? sn.getNextOfKin().getBirthDate() : null;
            pattern = Messages.get().gen_datePattern();
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_NATIONAL_ID:
            value = sn != null ? sn.getNextOfKin().getNationalId() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_ADDR_MULTIPLE_UNIT:
            value = sn != null ? sn.getNextOfKin().getAddress().getMultipleUnit() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_ADDR_STREET_ADDRESS:
            value = sn != null ? sn.getNextOfKin().getAddress().getStreetAddress() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_ADDR_CITY:
            value = sn != null ? sn.getNextOfKin().getAddress().getCity() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_ADDR_STATE:
            value = sn != null ? sn.getNextOfKin().getAddress().getState() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_ADDR_ZIP_CODE:
            value = sn != null ? sn.getNextOfKin().getAddress().getZipCode() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_ADDR_HOME_PHONE:
            value = sn != null ? sn.getNextOfKin().getAddress().getHomePhone() : null;
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_GENDER_ID:
            value = getDictionaryLabel(sn != null ? sn.getNextOfKin().getGenderId() : null);
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_RACE_ID:
            value = getDictionaryLabel(sn != null ? sn.getNextOfKin().getRaceId() : null);
            break;
        case SampleWebMeta.NEO_NEXT_OF_KIN_ETHNICITY_ID:
            value = getDictionaryLabel(sn != null ? sn.getNextOfKin().getEthnicityId() : null);
            break;
        case SampleWebMeta.NEO_PROVIDER_LAST_NAME:
            if (sn != null)
                value = sn.getProvider() != null ? sn.getProvider().getLastName() : null;
            break;
        case SampleWebMeta.NEO_PROVIDER_FIRST_NAME:
            if (sn != null)
                value = sn.getProvider() != null ? sn.getProvider().getFirstName() : null;
            break;
        /*
         * pt columns
         */
        case SampleWebMeta.PT_PT_PROVIDER_ID:
            value = getDictionaryLabel(sp != null ? sp.getPTProviderId() : null);
            break;
        case SampleWebMeta.PT_SERIES:
            value = sp != null ? sp.getSeries() : null;
            break;
        case SampleWebMeta.PT_DUE_DATE:
            value = sp != null ? sp.getDueDate() : null;
            pattern = Messages.get().gen_dateTimePattern();
            break;
        case SampleWebMeta.RECEIVED_BY_ID:
            value = s.getReceivedById() != null ? userCache.getSystemUser(s.getReceivedById()).getLoginName()
                    : null;
            /*
             * animal fields
             */
        case SampleWebMeta.ANI_ANIMAL_COMMON_NAME_ID:
            value = getDictionaryLabel(sa != null ? sa.getAnimalCommonNameId() : null);
            break;
        case SampleWebMeta.ANI_ANIMAL_SCIENTIFIC_NAME_ID:
            value = getDictionaryLabel(sa != null ? sa.getAnimalScientificNameId() : null);
            break;
        case SampleWebMeta.ANI_LOCATION:
            value = sa != null ? sa.getLocation() : null;
            break;
        case SampleWebMeta.ANI_LOCATION_ADDR_MULTIPLE_UNIT:
            value = sa != null ? sa.getLocationAddress().getMultipleUnit() : null;
            break;
        case SampleWebMeta.ANI_LOCATION_ADDR_STREET_ADDRESS:
            value = sa != null ? sa.getLocationAddress().getStreetAddress() : null;
            break;
        case SampleWebMeta.ANI_LOCATION_ADDR_CITY:
            value = sa != null ? sa.getLocationAddress().getCity() : null;
            break;
        case SampleWebMeta.ANI_LOCATION_ADDR_STATE:
            value = sa != null ? sa.getLocationAddress().getState() : null;
            break;
        case SampleWebMeta.ANI_LOCATION_ADDR_ZIP_CODE:
            value = sa != null ? sa.getLocationAddress().getZipCode() : null;
            break;
        case SampleWebMeta.ANI_PROVIDER_LAST_NAME:
            if (sa != null)
                value = sa.getProvider() != null ? sa.getProvider().getLastName() : null;
            break;
        case SampleWebMeta.ANI_PROVIDER_FIRST_NAME:
            if (sa != null)
                value = sa.getProvider() != null ? sa.getProvider().getFirstName() : null;
            break;
        case SampleWebMeta.ANI_PROVIDER_PHONE:
            value = sa != null ? sa.getProviderPhone() : null;
            break;
        default:
            throw new InconsistencyException("Unknown column " + column);
        }
        cell = row.createCell(i);
        style = pattern != null ? getDatetimeStyle(wb, dtStyles, pattern) : null;
        setCellValue(cell, value, style);
        setMaxChars(cell.getColumnIndex(), value, maxChars, pattern);
    }
}

From source file:org.openelis.bean.DataViewReportBean.java

License:Open Source License

/**
 * Creates the header row in "sheet" from "headers"; sets a style on the
 * header row to distinguish it from the other rows; updates "maxChars" to
 * account for the header labels because the header row is added after the
 * other rows have been added//  w  w w  .j ava  2 s .c  o  m
 * 
 * @param sheet
 *        the sheet that contains all rows in "wb"
 * @param wb
 *        the workbook that gets converted to an Excel file
 * @param headers
 *        the list of labels to be shown in the header row
 * @param maxChars
 *        the list containing the maximum number of characters in each
 *        column of "sheet"
 */
private void setHeaderCells(Sheet sheet, XSSFWorkbook wb, ArrayList<String> headers,
        ArrayList<Integer> maxChars) {
    Cell cell;
    Row row;
    Font font;
    CellStyle style;

    /*
     * create the style to distinguish the header row from the other rows in
     * the output
     */
    font = wb.createFont();
    font.setColor(IndexedColors.WHITE.getIndex());
    style = wb.createCellStyle();
    style.setAlignment(CellStyle.ALIGN_LEFT);
    style.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM);
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFillForegroundColor(IndexedColors.GREY_80_PERCENT.getIndex());
    style.setFont(font);

    row = sheet.createRow(0);
    for (int i = 0; i < headers.size(); i++) {
        cell = row.createCell(i);
        cell.setCellStyle(style);
        setCellValue(cell, headers.get(i), null);
        setMaxChars(cell.getColumnIndex(), headers.get(i), maxChars, null);
    }
}

From source file:org.openelis.bean.QcChartReport1Bean.java

License:Open Source License

/**
 * Keeps track of the maximum number of characters in each column of the
 * spreadsheet; if "cell" has more characters than the number in "maxChars"
 * for the cell's column, the number in "maxChars" is updated
 * // w  w w  .  j  av  a  2  s  . c  o m
 * @param cell
 *        a cell in a row in the spreadsheet
 * @param maxChars
 *        the list containing the maximum number of characters in each
 *        column of the spreadsheet
 */
private void setMaxChars(Cell cell, ArrayList<Integer> maxChars) {
    int col, chars;
    String val;

    col = cell.getColumnIndex();
    while (col > maxChars.size() - 1)
        maxChars.add(0);
    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        if (DateUtil.isCellDateFormatted(cell))
            val = ReportUtil.toString(cell.getDateCellValue(), Messages.get().dateTimePattern());
        else
            val = Double.toString(cell.getNumericCellValue());
    } else {
        val = cell.getStringCellValue();
    }
    chars = !DataBaseUtil.isEmpty(val) ? val.length() : 0;
    maxChars.set(col, Math.max(chars, maxChars.get(col)));
}

From source file:org.openelis.bean.WorksheetExcelHelperBean.java

License:Open Source License

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
private int createResultCellsForFormat(HSSFSheet sheet, Row row, Row tRow, String nameIndexPrefix,
        HashMap<String, String> cellNames, WorksheetViewDO wVDO, WorksheetAnalysisViewDO waVDO,
        ArrayList<WorksheetResultViewDO> wrList, boolean isEditable,
        HashMap<String, HashMap<Integer, ArrayList<AnalyteParameterViewDO>>> apMap) {
    int c, i, r;/* ww  w. j av  a  2 s  . c o  m*/
    String cellNameIndex, name;
    ArrayList<AnalyteParameterViewDO> anaParams, apList;
    DecimalFormat df;
    HashMap<Integer, ArrayList<AnalyteParameterViewDO>> pMap;
    Cell cell, tCell;
    Name cellName;
    AnalyteParameterViewDO apVDO;

    df = new DecimalFormat();
    df.setGroupingUsed(false);
    df.setMaximumFractionDigits(10);

    i = 0;
    r = row.getRowNum();
    for (WorksheetResultViewDO wrVDO : wrList) {
        if (i != 0) {
            row = sheet.createRow(r);
            for (c = 0; c < 7; c++) {
                cell = row.createCell(c);
                cell.setCellStyle(styles.get("row_no_edit"));
            }
        }

        cellNameIndex = nameIndexPrefix + "." + i;

        // analyte
        cell = row.createCell(7);
        cell.setCellStyle(styles.get("row_no_edit"));
        cell.setCellValue(wrVDO.getAnalyteName());

        // reportable
        cell = row.createCell(8);
        cell.setCellStyle(styles.get("row_no_edit"));
        cell.setCellValue(wrVDO.getIsReportable());
        cellName = sheet.getWorkbook().createName();
        cellName.setNameName("analyte_reportable." + cellNameIndex);
        cellName.setRefersToFormula(
                "Worksheet!$" + CellReference.convertNumToColString(8) + "$" + (row.getRowNum() + 1));

        apVDO = null;
        for (c = 9; c < tRow.getLastCellNum() && c < 39; c++) {
            tCell = tRow.getCell(c);

            cell = row.createCell(c);
            if (isEditable)
                cell.setCellStyle(tCell.getCellStyle());
            else
                cell.setCellStyle(styles.get("row_no_edit"));
            name = cellNames.get(
                    sheet.getSheetName() + "!$" + CellReference.convertNumToColString(tCell.getColumnIndex())
                            + "$" + (tCell.getRowIndex() + 1));
            if (name != null) {
                cellName = row.getSheet().getWorkbook().createName();
                cellName.setNameName(name + "." + cellNameIndex);
                cellName.setRefersToFormula(
                        sheet.getSheetName() + "!$" + CellReference.convertNumToColString(cell.getColumnIndex())
                                + "$" + (row.getRowNum() + 1));
            }
            if (tCell.getCellType() == Cell.CELL_TYPE_FORMULA && tCell.getCellFormula() != null) {
                cell.setCellFormula(tCell.getCellFormula());
            } else {
                setCellValue(cell, wrVDO.getValueAt(c - 9));
            }
            if ("p1".equals(name) || "p2".equals(name) || "p3".equals(name) || "p_1".equals(name)
                    || "p_2".equals(name) || "p_3".equals(name)) {
                if (wrVDO.getValueAt(c - 9) == null) {
                    pMap = apMap.get("T" + waVDO.getTestId());
                    if (pMap == null) {
                        pMap = new HashMap<Integer, ArrayList<AnalyteParameterViewDO>>();
                        apMap.put("T" + waVDO.getTestId(), pMap);
                        try {
                            anaParams = analyteParameter.fetchByActiveDate(waVDO.getTestId(),
                                    Constants.table().TEST, wVDO.getCreatedDate().getDate());
                            for (AnalyteParameterViewDO anaParam : anaParams) {
                                apList = pMap.get(anaParam.getAnalyteId());
                                if (apList == null) {
                                    apList = new ArrayList<AnalyteParameterViewDO>();
                                    pMap.put(anaParam.getAnalyteId(), apList);
                                }
                                apList.add(anaParam);
                            }
                        } catch (NotFoundException nfE) {
                            continue;
                        } catch (Exception anyE) {
                            log.log(Level.SEVERE,
                                    "Error retrieving analyte parameters for an analysis on worksheet.", anyE);
                            continue;
                        }
                    }

                    apList = pMap.get(wrVDO.getAnalyteId());
                    apVDO = null;
                    if (apList != null && apList.size() > 0) {
                        for (AnalyteParameterViewDO ap : apList) {
                            if (ap.getUnitOfMeasureId() == null
                                    || ap.getUnitOfMeasureId().equals(waVDO.getUnitOfMeasureId())) {
                                if (ap.getUnitOfMeasureId() != null) {
                                    apVDO = ap;
                                    break;
                                } else if (apVDO == null) {
                                    apVDO = ap;
                                }
                            }
                        }
                    }
                    if (apVDO != null) {
                        if (("p1".equals(name) || "p_1".equals(name)) && apVDO.getP1() != null) {
                            setCellValue(cell, df.format(apVDO.getP1()));
                        } else if (("p2".equals(name) || "p_2".equals(name)) && apVDO.getP2() != null) {
                            setCellValue(cell, df.format(apVDO.getP2()));
                        } else if (("p3".equals(name) || "p_3".equals(name)) && apVDO.getP3() != null) {
                            setCellValue(cell, df.format(apVDO.getP3()));
                        }
                    }
                }
            }
        }

        i++;
        r++;
    }

    return r;
}

From source file:org.openelis.bean.WorksheetExcelHelperBean.java

License:Open Source License

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
private int createQcResultCellsForFormat(HSSFSheet sheet, Row row, Row tRow, String nameIndexPrefix,
        HashMap<String, String> cellNames, WorksheetViewDO wVDO, Integer qcId,
        ArrayList<WorksheetQcResultViewDO> wqrList,
        HashMap<String, HashMap<Integer, ArrayList<AnalyteParameterViewDO>>> apMap) {
    int c, i, r;/*from www .j av a  2s.co  m*/
    String cellNameIndex, name;
    ArrayList<AnalyteParameterViewDO> anaParams, apList;
    DecimalFormat df;
    HashMap<Integer, ArrayList<AnalyteParameterViewDO>> pMap;
    Cell cell, tCell;
    Name cellName;
    AnalyteParameterViewDO apVDO;

    df = new DecimalFormat();
    df.setGroupingUsed(false);
    df.setMaximumFractionDigits(10);

    i = 0;
    r = row.getRowNum();
    for (WorksheetQcResultViewDO wqrVDO : wqrList) {
        if (i != 0) {
            row = sheet.createRow(r);
            for (c = 0; c < 7; c++) {
                cell = row.createCell(c);
                cell.setCellStyle(styles.get("row_no_edit"));
            }
        }

        cellNameIndex = nameIndexPrefix + "." + i;

        // analyte
        cell = row.createCell(7);
        cell.setCellStyle(styles.get("row_no_edit"));
        cell.setCellValue(wqrVDO.getAnalyteName());

        // reportable
        cell = row.createCell(8);
        cell.setCellStyle(styles.get("row_no_edit"));
        cell.setCellValue("N");

        apVDO = null;
        for (c = 9; c < tRow.getLastCellNum() && c < 39; c++) {
            tCell = tRow.getCell(c);

            cell = row.createCell(c);
            cell.setCellStyle(tCell.getCellStyle());
            name = cellNames.get(
                    sheet.getSheetName() + "!$" + CellReference.convertNumToColString(tCell.getColumnIndex())
                            + "$" + (tCell.getRowIndex() + 1));
            if (name != null) {
                cellName = row.getSheet().getWorkbook().createName();
                cellName.setNameName(name + "." + cellNameIndex);
                cellName.setRefersToFormula(
                        sheet.getSheetName() + "!$" + CellReference.convertNumToColString(cell.getColumnIndex())
                                + "$" + (row.getRowNum() + 1));
            }
            if (tCell.getCellType() == Cell.CELL_TYPE_FORMULA && tCell.getCellFormula() != null) {
                cell.setCellFormula(tCell.getCellFormula());
            } else {
                setCellValue(cell, wqrVDO.getValueAt(c - 9));
            }
            if ("p1".equals(name) || "p2".equals(name) || "p3".equals(name) || "p_1".equals(name)
                    || "p_2".equals(name) || "p_3".equals(name)) {
                if (wqrVDO.getValueAt(c - 9) == null) {
                    pMap = apMap.get("Q" + qcId);
                    if (pMap == null) {
                        pMap = new HashMap<Integer, ArrayList<AnalyteParameterViewDO>>();
                        apMap.put("Q" + qcId, pMap);
                        try {
                            anaParams = analyteParameter.fetchByActiveDate(qcId, Constants.table().QC,
                                    wVDO.getCreatedDate().getDate());
                            for (AnalyteParameterViewDO anaParam : anaParams) {
                                apList = pMap.get(anaParam.getAnalyteId());
                                if (apList == null) {
                                    apList = new ArrayList<AnalyteParameterViewDO>();
                                    pMap.put(anaParam.getAnalyteId(), apList);
                                }
                                apList.add(anaParam);
                            }
                        } catch (NotFoundException nfE) {
                            continue;
                        } catch (Exception anyE) {
                            log.log(Level.SEVERE, "Error retrieving analyte parameters for a qc on worksheet.",
                                    anyE);
                            continue;
                        }
                    }

                    apList = pMap.get(wqrVDO.getAnalyteId());
                    apVDO = null;
                    if (apList != null && apList.size() > 0)
                        apVDO = apList.get(0);
                    if (apVDO != null) {
                        if (("p1".equals(name) || "p_1".equals(name)) && apVDO.getP1() != null) {
                            setCellValue(cell, String.valueOf(apVDO.getP1()));
                        } else if (("p2".equals(name) || "p_2".equals(name)) && apVDO.getP2() != null) {
                            setCellValue(cell, String.valueOf(apVDO.getP2()));
                        } else if (("p3".equals(name) || "p_3".equals(name)) && apVDO.getP3() != null) {
                            setCellValue(cell, String.valueOf(apVDO.getP3()));
                        }
                    }
                }
            }
        }

        i++;
        r++;
    }

    return r;
}

From source file:org.openmrs.module.kenyaemr.fragment.controller.patient.ImportPatientsListFragmentController.java

License:Open Source License

@SuppressWarnings("deprecation")
public Object submit(HttpServletRequest request) throws Exception {
    // Constant values used across all the code

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartModuleFile = multipartRequest.getFile("upload");
    InputStream inputStream = multipartModuleFile.getInputStream();
    Workbook workbook = new XSSFWorkbook(inputStream);

    Sheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> iterator = firstSheet.iterator();
    int rowCount = 0;

    while (iterator.hasNext()) {
        Row nextRow = iterator.next();/* ww w  . j  av a  2s.co m*/
        Iterator<Cell> cellIterator = nextRow.cellIterator();
        try {
            if (rowCount > 0) {

                ArrayList<String> legacyData = new ArrayList<String>();
                int columnCount = 0;

                while (cellIterator.hasNext() && columnCount < 31) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        legacyData.add(cell.getColumnIndex(), cell.getStringCellValue().trim());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            legacyData.add(cell.getColumnIndex(), String.valueOf(cell.getDateCellValue()));

                        } else {

                            legacyData.add(cell.getColumnIndex(),
                                    NumberToTextConverter.toText(cell.getNumericCellValue()));
                        }
                        break;
                    case Cell.CELL_TYPE_BLANK:
                        legacyData.add(cell.getColumnIndex(), null);
                        break;
                    }
                    columnCount++;
                }
                int i = 0;
                for (String s : legacyData) {
                    i++;
                }
                /*
                 * Start Patient Creation
                 */
                try {
                    if (legacyData.get(0) != null) {
                        Patient toSave = new Patient(); // Creating a new
                        // patient
                        // and
                        // person
                        PersonName personName = new PersonName();
                        PersonAddress personAddress = new PersonAddress();
                        Location location;

                        SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                        Date dateBith = new Date();
                        try {
                            dateBith = (Date) formatter.parse(legacyData.get(2));

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        toSave.setGender(legacyData.get(3));
                        toSave.setBirthdate(dateBith);
                        toSave.setBirthdateEstimated(false);
                        toSave.setDead(false);
                        /*
                         * toSave.setDeathDate(deathDate);
                         * toSave.setCauseOfDeath(dead ? Dictionary
                         * .getConcept(CAUSE_OF_DEATH_PLACEHOLDER) : null);
                         */

                        if (legacyData.get(1) != "") {
                            personName.setGivenName(legacyData.get(1));

                            personName.setFamilyName("(NULL)");
                            toSave.addName(personName);
                        }

                        // toSave.
                        personAddress.setAddress1(legacyData.get(9));
                        personAddress.setCountyDistrict(legacyData.get(10));
                        toSave.addAddress(personAddress);

                        PatientWrapper wrapper = new PatientWrapper(toSave);

                        wrapper.getPerson().setTelephoneContact(legacyData.get(8));

                        location = Context.getService(KenyaEmrService.class).getDefaultLocation();

                        if (legacyData.get(4) != null) {
                            wrapper.setPreArtRegistrationNumber(legacyData.get(4), location);
                        }

                        if (legacyData.get(6) != null) {
                            wrapper.setArtRegistrationNumber(legacyData.get(6), location);
                        }

                        if (legacyData.get(5) != null) {
                            wrapper.setNapArtRegistrationNumber(legacyData.get(5), location);
                        }

                        // Algorithm to generate system generated patient
                        // Identifier
                        Calendar now = Calendar.getInstance();
                        String shortName = Context.getAdministrationService()
                                .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX);

                        String noCheck = shortName + String.valueOf(now.get(Calendar.YEAR)).substring(2, 4)
                                + String.valueOf(now.get(Calendar.MONTH) + 1)
                                + String.valueOf(now.get(Calendar.DATE))

                                + String.valueOf(now.get(Calendar.HOUR))
                                + String.valueOf(now.get(Calendar.MINUTE))
                                + String.valueOf(now.get(Calendar.SECOND))
                                + String.valueOf(new Random().nextInt(9999 - 999 + 1));

                        wrapper.setSystemPatientId(noCheck + "-" + generateCheckdigit(noCheck), location);

                        wrapper.setNextOfKinName(legacyData.get(11));
                        wrapper.setNextOfKinContact(legacyData.get(12));

                        if (legacyData.get(13) != null) {
                            wrapper.setPreviousHivTestStatus("Yes");
                            wrapper.setPreviousHivTestPlace(legacyData.get(14));

                            Date capturedTestDate = new Date();
                            try {
                                capturedTestDate = formatter.parse(legacyData.get(13));

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            DateFormat testDate = new SimpleDateFormat("dd-MMMM-yyyy");
                            wrapper.setPreviousHivTestDate(testDate.format(capturedTestDate));
                        } else {
                            wrapper.setPreviousHivTestStatus("No");
                        }

                        wrapper.setPreviousClinicName(legacyData.get(16));

                        // Make sure everyone gets an OpenMRS ID
                        PatientIdentifierType openmrsIdType = MetadataUtils.existing(
                                PatientIdentifierType.class, CommonMetadata._PatientIdentifierType.OPENMRS_ID);
                        PatientIdentifier openmrsId = toSave.getPatientIdentifier(openmrsIdType);

                        if (openmrsId == null) {
                            String generated = Context.getService(IdentifierSourceService.class)
                                    .generateIdentifier(openmrsIdType, "Registration");
                            openmrsId = new PatientIdentifier(generated, openmrsIdType, location);
                            toSave.addIdentifier(openmrsId);

                            if (!toSave.getPatientIdentifier().isPreferred()) {
                                openmrsId.setPreferred(true);
                            }
                        }

                        Patient ret = Context.getPatientService().savePatient(toSave);

                        // Explicitly save all identifier objects including
                        // voided
                        for (PatientIdentifier identifier : toSave.getIdentifiers()) {
                            Context.getPatientService().savePatientIdentifier(identifier);
                        }

                        /*
                         * End Patient Creation
                         */

                        /**
                         ** Start : Visit, Encounter and Program creation for
                         * Patient entered as Legacy Data Visit start date
                         **/
                        Date curDate = new Date();
                        Date dateVisit = null;
                        try {
                            dateVisit = formatter.parse(legacyData.get(18));

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        DateFormat visitDateInExcel = new SimpleDateFormat("dd-MMM-yyyy");
                        String dateCheck = visitDateInExcel.format(dateVisit);
                        SimpleDateFormat mysqlDateTimeFormatter = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");

                        if (legacyData.get(18) != null) {
                            try {
                                dateVisit = mysqlDateTimeFormatter.parse(dateCheck + " " + curDate.getHours()
                                        + ":" + curDate.getMinutes() + ":" + curDate.getSeconds());
                            } catch (ParseException e) {
                                dateVisit = curDate;
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        Visit visit = new Visit();
                        visit.setPatient(ret);
                        visit.setStartDatetime(dateVisit);
                        visit.setVisitType(
                                MetadataUtils.existing(VisitType.class, CommonMetadata._VisitType.OUTPATIENT));
                        visit.setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        VisitAttributeType attrType = Context.getService(VisitService.class)
                                .getVisitAttributeTypeByUuid(CommonMetadata._VisitAttributeType.NEW_PATIENT);
                        if (attrType != null) {
                            VisitAttribute attr = new VisitAttribute();
                            attr.setAttributeType(attrType);
                            attr.setVisit(visit);
                            attr.setDateCreated(curDate);
                            attr.setValue(true);
                            visit.addAttribute(attr);
                        }

                        Visit visitSave = Context.getVisitService().saveVisit(visit);

                        // With value text and Date
                        if (legacyData.get(15) != null) {

                            Date dateTransfer = null;
                            if (legacyData.get(17) != null) {
                                try {
                                    dateTransfer = formatter.parse(legacyData.get(17));

                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }

                            Concept enrollementConcept = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(15)));

                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.METHOD_OF_ENROLLMENT),
                                    enrollementConcept, "", dateTransfer, null, visitSave);
                        }

                        if (legacyData.get(7) != null) {
                            Concept ingoConcept = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(7)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.INGO_NAME),
                                    ingoConcept, "", null, null, visitSave);
                        }

                        EncounterType hivEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                HivMetadata._EncounterType.HIV_ENROLLMENT);

                        EncounterType registrationEncType = MetadataUtils.existing(EncounterType.class,
                                CommonMetadata._EncounterType.REGISTRATION);

                        Encounter hivEnrollmentEncounter = new Encounter();

                        hivEnrollmentEncounter.setEncounterType(hivEnrollEncType);
                        hivEnrollmentEncounter.setPatient(ret);
                        hivEnrollmentEncounter
                                .setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        hivEnrollmentEncounter.setDateCreated(curDate);
                        hivEnrollmentEncounter.setEncounterDatetime(dateVisit);

                        hivEnrollmentEncounter
                                .setForm(MetadataUtils.existing(Form.class, HivMetadata._Form.HIV_ENROLLMENT));
                        hivEnrollmentEncounter.setVisit(visitSave);
                        hivEnrollmentEncounter.setVoided(false);
                        Encounter enHivNew = Context.getEncounterService()
                                .saveEncounter(hivEnrollmentEncounter);

                        PatientProgram patientProgram = new PatientProgram();
                        patientProgram.setPatient(ret);
                        patientProgram
                                .setProgram(MetadataUtils.existing(Program.class, HivMetadata._Program.HIV));
                        patientProgram.setDateEnrolled(enHivNew.getEncounterDatetime());
                        patientProgram.setDateCreated(curDate);
                        Context.getProgramWorkflowService().savePatientProgram(patientProgram);

                        Encounter personalEncounter = new Encounter();

                        personalEncounter.setEncounterType(hivEnrollEncType);
                        personalEncounter.setPatient(ret);

                        personalEncounter.setDateCreated(curDate);
                        personalEncounter.setEncounterDatetime(dateVisit);
                        personalEncounter
                                .setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        personalEncounter.setForm(
                                MetadataUtils.existing(Form.class, Metadata.Form.HIV_PERSONAL_HISTORY));
                        personalEncounter.setVisit(visitSave);
                        personalEncounter.setVoided(false);
                        Encounter enpersonalrecordresultNew = Context.getEncounterService()
                                .saveEncounter(personalEncounter);
                        if (legacyData.get(19) != null) {

                            Concept literate = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(19)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.LITERATE), literate,
                                    "", null, null, enpersonalrecordresultNew, null, visitSave);

                        }
                        if (legacyData.get(21) != null) {

                            String value = legacyData.get(21);

                            String[] valueList = value.split("\\s*,\\s*");

                            for (String riskname : valueList) {

                                Concept riskConcept = Context.getConceptService().getConcept(riskname);

                                handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.HIV_RISK_FACTOR),
                                        riskConcept, "", null, null, enpersonalrecordresultNew, null,
                                        visitSave);

                            }

                        }
                        if (legacyData.get(22) != null) {

                            Concept idssubstituion = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(22)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.IDU_PERSONAL_HISTORY),
                                    idssubstituion, "", null, null, enpersonalrecordresultNew, null, visitSave);

                        }

                        if (legacyData.get(23) != null) {

                            Concept idssubstituionvalue = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(23)));
                            handleOncePerPatientObs(ret,
                                    Dictionary.getConcept(Dictionary.IDU_NAME_PERSONAL_HISTORY),
                                    idssubstituionvalue, "", null, null, enpersonalrecordresultNew, null,
                                    visitSave);

                        }
                        if (legacyData.get(29) != null) {

                            Concept employedvalue = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(29)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.EMPLOYED),
                                    employedvalue, "", null, null, enpersonalrecordresultNew, null, visitSave);
                        }

                        if (legacyData.get(30) != null) {

                            Concept alcoholicvalue = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(30)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.ALCOHOLIC_TYPE),
                                    alcoholicvalue, "", null, null, enpersonalrecordresultNew, null, visitSave);
                        }

                        Encounter familyEncounter = new Encounter();

                        familyEncounter.setEncounterType(registrationEncType);
                        familyEncounter.setPatient(ret);

                        familyEncounter.setDateCreated(curDate);
                        familyEncounter.setEncounterDatetime(dateVisit);
                        familyEncounter
                                .setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        familyEncounter
                                .setForm(MetadataUtils.existing(Form.class, Metadata.Form.HIV_FAMILY_HISTORY));
                        familyEncounter.setVisit(visitSave);
                        familyEncounter.setVoided(false);
                        Encounter enfamilyrecordresultNew = Context.getEncounterService()
                                .saveEncounter(familyEncounter);
                        if (legacyData.get(20) != null) {

                            Concept martalstatus = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(20)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.CIVIL_STATUS),
                                    martalstatus, "", null, null, enfamilyrecordresultNew, null, visitSave);
                        }

                        Encounter drugEncounter = new Encounter();

                        drugEncounter.setEncounterType(hivEnrollEncType);
                        drugEncounter.setPatient(ret);

                        drugEncounter.setDateCreated(curDate);
                        drugEncounter.setEncounterDatetime(dateVisit);
                        drugEncounter
                                .setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        drugEncounter
                                .setForm(MetadataUtils.existing(Form.class, Metadata.Form.HIV_DRUG_HISTORY));
                        drugEncounter.setVisit(visitSave);
                        drugEncounter.setVoided(false);
                        Encounter endrugrecordresultNew = Context.getEncounterService()
                                .saveEncounter(drugEncounter);

                        if (legacyData.get(24) != null) {

                            Concept drughistoryart = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(24)));

                            handleOncePerPatientObs(ret,
                                    Dictionary.getConcept(Dictionary.DRUG_HISTORY_ART_RECEIVED), drughistoryart,
                                    "", null, null, endrugrecordresultNew, null, visitSave);

                        }

                        if (legacyData.get(25) != null) {

                            Concept drughistoryarttype = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(25)));

                            handleOncePerPatientObs(ret,
                                    Dictionary.getConcept(Dictionary.DRUG_HISTORY_ART_RECEIVED_TYPE),
                                    drughistoryarttype, "", null, null, endrugrecordresultNew, null, visitSave);

                        }

                        if (legacyData.get(26) != null && legacyData.get(27) != null
                                && legacyData.get(28) != null) {

                            boolean value = false;
                            Obs drugtreatmentGroup = new Obs();
                            drugtreatmentGroup.setPerson(ret);
                            drugtreatmentGroup.setConcept(Dictionary.getConcept(Dictionary.DRUG_HISTORY_GROUP));

                            drugtreatmentGroup.setObsDatetime(endrugrecordresultNew.getEncounterDatetime());

                            // Added value coded as per default obs object
                            // format.
                            //drugtreatmentGroup.setValueCoded(null);
                            // drugtreatmentGroup.setValueText(text);
                            drugtreatmentGroup.setLocation(
                                    Context.getService(KenyaEmrService.class).getDefaultLocation());

                            drugtreatmentGroup.setEncounter(endrugrecordresultNew);

                            drugtreatmentGroup.setValueBoolean(value);
                            Obs drugtreat = Context.getObsService().saveObs(drugtreatmentGroup,
                                    "KenyaEMR History Details");
                            if (legacyData.get(26) != null) {

                                Concept place = Context.getConceptService()
                                        .getConcept(Integer.parseInt(legacyData.get(26)));
                                handleOncePerPatientObs(ret,
                                        Dictionary.getConcept(Dictionary.DRUG_HISTORY_ART_RECEIVED_PLACE),
                                        place, "", null, null, endrugrecordresultNew, drugtreat, visitSave);
                            }

                            if (legacyData.get(27) != null) {

                                Concept drugarv = Context.getConceptService()
                                        .getConcept(Integer.parseInt(legacyData.get(27)));
                                handleOncePerPatientObs(ret,
                                        Dictionary.getConcept(Dictionary.DRUG_REGIMEN_DRUG_HISTORY), drugarv,
                                        "", null, null, endrugrecordresultNew, drugtreat, visitSave);
                            }

                            if (legacyData.get(28) != null) {

                                Double dur = 0.0;
                                Integer durationreslt = 0;

                                durationreslt = Integer.parseInt(legacyData.get(28));
                                dur = durationreslt.doubleValue();
                                handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.DRUG_DURATION),
                                        null, null, null, dur, endrugrecordresultNew, drugtreat, visitSave);

                            }

                        }

                        /*
                         * End : Visit, Encounter and Program creation for
                         * Patient entered as Legacy Data
                         */

                    }
                } catch (IndexOutOfBoundsException e) {
                    break;
                }
            }
        } catch (IndexOutOfBoundsException e) {
            break;
        }

        rowCount++;
    }

    int noOfSheets = workbook.getNumberOfSheets();

    if (noOfSheets > 1) {
        Sheet secondSheet = workbook.getSheetAt(1);
        Iterator<Row> iteratorSecond = secondSheet.iterator();
        int rowCountVisit = 0;
        while (iteratorSecond.hasNext()) {
            Row nextRow = iteratorSecond.next();
            Iterator<Cell> cellIterator = nextRow.cellIterator();
            try {

                if (rowCountVisit > 0) {
                    ArrayList<String> legacyData = new ArrayList<String>();
                    int columnCount = 0;
                    while (cellIterator.hasNext() && columnCount < 44) {
                        Cell cell = cellIterator.next();

                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_STRING:
                            legacyData.add(cell.getColumnIndex(), cell.getStringCellValue().trim());
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                legacyData.add(cell.getColumnIndex(), String.valueOf(cell.getDateCellValue()));

                            } else {

                                legacyData.add(cell.getColumnIndex(),
                                        NumberToTextConverter.toText(cell.getNumericCellValue()));

                            }
                            break;
                        case Cell.CELL_TYPE_BLANK:
                            legacyData.add(cell.getColumnIndex(), "");
                            break;
                        }
                        columnCount++;
                    }

                    int i = 0;
                    for (String s : legacyData) {
                        i++;
                    }
                    Person person = null;
                    Patient patient = null;
                    PatientWrapper wrapper = null;
                    int count = 0;
                    Location location;
                    location = Context.getService(KenyaEmrService.class).getDefaultLocation();

                    if (legacyData.get(3) != null && legacyData.get(3) != "") {
                        try {

                            if (!legacyData.get(0).isEmpty()) {
                                PatientIdentifierType pt = Context.getPatientService()
                                        .getPatientIdentifierTypeByUuid("d59d0f67-4a05-4e41-bfad-342da68feb6f");

                                List<PatientIdentifier> patList = Context.getPatientService()
                                        .getPatientIdentifiers(legacyData.get(0).toString(), pt);

                                for (PatientIdentifier p : patList) {
                                    patient = Context.getPatientService()
                                            .getPatient(p.getPatient().getPatientId());
                                    wrapper = new PatientWrapper(patient);
                                    person = Context.getPersonService().getPerson(patient);
                                }
                            }

                            else if (!legacyData.get(1).isEmpty()) {
                                PatientIdentifierType pt = Context.getPatientService()
                                        .getPatientIdentifierTypeByUuid("3e5493e8-e76e-4d3f-a166-9a88b40747fa");

                                List<PatientIdentifier> patList = Context.getPatientService()
                                        .getPatientIdentifiers(legacyData.get(1).toString(), pt);

                                for (PatientIdentifier p : patList) {

                                    patient = Context.getPatientService()
                                            .getPatient(p.getPatient().getPatientId());
                                    wrapper = new PatientWrapper(patient);
                                    person = Context.getPersonService().getPerson(patient);
                                }

                            } else if (!legacyData.get(2).isEmpty()) {
                                PatientIdentifierType pt = Context.getPatientService()
                                        .getPatientIdentifierTypeByUuid("9e10c5d6-a58c-4236-8b65-b6b932beff1a");
                                List<PatientIdentifier> patList = Context.getPatientService()
                                        .getPatientIdentifiers(legacyData.get(2).toString(), pt);
                                for (PatientIdentifier p : patList) {
                                    patient = Context.getPatientService()
                                            .getPatient(p.getPatient().getPatientId());
                                    wrapper = new PatientWrapper(patient);
                                    person = Context.getPersonService().getPerson(patient);
                                }
                            } else {
                                break;
                            }

                            SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                            Date curDate = new Date();
                            Date dateVisit = null;
                            try {
                                if (legacyData.get(3) != null && legacyData.get(3) != "") {
                                    dateVisit = formatter.parse(legacyData.get(3));
                                }

                            } catch (ParseException e) {

                                e.printStackTrace();
                            }
                            DateFormat visitDateInExcel = new SimpleDateFormat("dd-MMM-yyyy");
                            String dateCheck = "";
                            SimpleDateFormat mysqlDateTimeFormatter = new SimpleDateFormat(
                                    "dd-MMM-yy HH:mm:ss");
                            if (legacyData.get(3) != null && legacyData.get(3) != "") {
                                Date curDatenew = new Date();
                                dateCheck = visitDateInExcel.format(dateVisit);
                                try {
                                    dateVisit = mysqlDateTimeFormatter
                                            .parse(dateCheck + " " + curDatenew.getHours() + ":"
                                                    + curDatenew.getMinutes() + ":" + curDatenew.getSeconds());

                                } catch (ParseException e) {
                                    dateVisit = curDatenew;
                                    e.printStackTrace();
                                }
                            }

                            List<Visit> visits = Context.getVisitService().getActiveVisitsByPatient(patient);

                            Visit v = new Visit();
                            if (visits.isEmpty()) {
                                Visit visit = new Visit();
                                visit.setPatient(patient);
                                visit.setStartDatetime(dateVisit);
                                visit.setVisitType(MetadataUtils.existing(VisitType.class,
                                        CommonMetadata._VisitType.OUTPATIENT));
                                visit.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());
                                if (person.getDead() == false) {
                                    v = Context.getVisitService().saveVisit(visit);
                                }

                            } else {
                                for (Visit vLoop : visits) {
                                    v = vLoop;

                                }
                            }

                            if (v.getId() != null) {
                                EncounterType artEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        ArtMetadata._EncounterType.INITIATE_ART);
                                Encounter artEncounter = new Encounter();

                                artEncounter.setEncounterType(artEnrollEncType);
                                artEncounter.setPatient(patient);
                                artEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                artEncounter.setDateCreated(curDate);
                                artEncounter.setEncounterDatetime(dateVisit);

                                artEncounter.setForm(
                                        MetadataUtils.existing(Form.class, ArtMetadata._Form.INITIATE_ART));
                                artEncounter.setVisit(v);

                                artEncounter.setVoided(false);
                                if (!legacyData.get(9).isEmpty()) {

                                    Encounter enartNew = Context.getEncounterService()
                                            .saveEncounter(artEncounter);
                                }
                                PatientProgram pp = new PatientProgram();
                                if (!legacyData.get(9).isEmpty()) {

                                    pp.setPatient(patient);
                                    pp.setProgram(
                                            MetadataUtils.existing(Program.class, ArtMetadata._Program.ART));

                                    Date artStartDate = null;
                                    Date curDatenew = new Date();

                                    try {
                                        artStartDate = (Date) formatter.parse(legacyData.get(9));
                                        dateCheck = visitDateInExcel.format(artStartDate);
                                        artStartDate = mysqlDateTimeFormatter.parse(dateCheck + " "
                                                + curDatenew.getHours() + ":" + curDatenew.getMinutes() + ":"
                                                + curDatenew.getSeconds());
                                        pp.setDateEnrolled(artStartDate);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    if (pp.getDateEnrolled() != null && pp.getDateCompleted() == null) {
                                        PatientProgram program = Context.getProgramWorkflowService()
                                                .savePatientProgram(pp);
                                    }

                                }

                                /*
                                 * Changes code
                                 */
                                String reg = "";

                                if (!legacyData.get(4).isEmpty()) {

                                    Concept regimenConcept = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(4)));
                                    reg = reg.concat(regimenConcept.getName().toString());

                                    KenyaEmrService kes = (KenyaEmrService) Context
                                            .getService(KenyaEmrService.class);

                                    List<DrugOrderProcessed> dopp = kes.getDrugOrderProcessedByPatient(patient);

                                    // Created drug order processed
                                    DrugOrderProcessed orderprocess = new DrugOrderProcessed();

                                    orderprocess.setPatient(patient);
                                    orderprocess.setDrugRegimen(reg);
                                    orderprocess.setCreatedDate(dateVisit);
                                    orderprocess.setStartDate(dateVisit);
                                    orderprocess.setVisit(v);
                                    orderprocess.setRoute(Context.getConceptService()
                                            .getConceptByUuid("160240AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
                                    Integer tablet = 0;

                                    if (legacyData.get(4).equals("163494") || legacyData.get(4).equals("163495")
                                            || legacyData.get(4).equals("163496")
                                            || legacyData.get(4).equals("162959")
                                            || legacyData.get(4).equals("163503")
                                            || legacyData.get(4).equals("163505")
                                            || legacyData.get(4).equals("163506")
                                            || legacyData.get(4).equals(" 163507")
                                            || legacyData.get(4).equals("163508")
                                            || legacyData.get(4).equals("163510")) {

                                        orderprocess.setNoOfTablet(1);
                                        tablet = Integer.parseInt(legacyData.get(6));
                                    } else {
                                        tablet = Integer.parseInt(legacyData.get(6)) * 2;
                                        orderprocess.setNoOfTablet(2);
                                    }

                                    if (!legacyData.get(6).isEmpty()) {
                                        orderprocess.setDurationPreProcess(Integer.parseInt(legacyData.get(6)));

                                        orderprocess.setQuantityPostProcess(tablet);

                                        orderprocess.setProcessedStatus(true);
                                        try {
                                            Date curDat = new Date();

                                            dateVisit = mysqlDateTimeFormatter
                                                    .parse(dateCheck + " " + curDat.getHours() + ":"
                                                            + curDat.getMinutes() + ":" + curDat.getSeconds());

                                            orderprocess.setProcessedDate(dateVisit);

                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    if (!legacyData.get(5).isEmpty()) {
                                        orderprocess.setDose(legacyData.get(5));
                                        orderprocess.setDoseRegimen(legacyData.get(5));
                                    }
                                    String cahngeRegimenType = "";
                                    if (patient.getAge() > 14) {
                                        for (String firstline : firstlineConcept) {
                                            if (legacyData.get(4).equals(firstline)) {
                                                orderprocess
                                                        .setTypeOfRegimen("First line Anti-retoviral drugs");
                                                cahngeRegimenType = "First line Anti-retoviral drugs";
                                            }
                                        }
                                        for (String secndline : secondlineConcept) {
                                            if (legacyData.get(4).equals(secndline)) {
                                                orderprocess.setTypeOfRegimen("Second line ART");
                                                cahngeRegimenType = "Second line ART";
                                            }
                                        }
                                        for (String thirdline : thirdlineConcept) {
                                            if (legacyData.get(4).equals(thirdline)) {
                                                orderprocess.setTypeOfRegimen("HIV/HBV co-infection");
                                                cahngeRegimenType = "HIV/HBV co-infection";
                                            }
                                        }
                                    } else {
                                        for (String child : childArvConcept) {
                                            if (legacyData.get(4).equals(child)) {
                                                orderprocess.setTypeOfRegimen("ARV drugs for child");
                                                cahngeRegimenType = "ARV drugs for child";

                                            }
                                        }
                                    }

                                    if (dopp.size() == 0) {
                                        orderprocess.setRegimenChangeType("Start");
                                        // Encounter Created
                                        EncounterType regEnrollEncType = MetadataUtils.existing(
                                                EncounterType.class,
                                                CommonMetadata._EncounterType.REGIMEN_ORDER);

                                        Encounter regEncounter = new Encounter();
                                        regEncounter.setEncounterType(regEnrollEncType);
                                        regEncounter.setPatient(patient);
                                        regEncounter.setLocation(Context.getLocationService()
                                                .getLocationByUuid("8d6c993e-c2cc-11de-8d13-0010c6dffd0f"));

                                        regEncounter.setDateCreated(curDate);
                                        regEncounter.setEncounterDatetime(dateVisit);
                                        regEncounter.setVisit(v);

                                        regEncounter.setVoided(false);

                                        // Save encounter
                                        Encounter enregNew = Context.getEncounterService()
                                                .saveEncounter(regEncounter);

                                        // Create order
                                        Order ordersave = new Order();

                                        // Create Drug order
                                        DrugOrder dod = new DrugOrder();

                                        dod.setOrderType(Context.getOrderService().getOrderType(2));
                                        dod.setConcept(Context.getConceptService()
                                                .getConcept(Integer.parseInt(legacyData.get(4))));
                                        dod.setEncounter(enregNew);

                                        dod.setStartDate(dateVisit);
                                        dod.setDateCreated(curDate);
                                        dod.setPatient(patient);
                                        dod.setUnits("tab");
                                        if (legacyData.get(4).equals("163494")
                                                || legacyData.get(4).equals("163495")
                                                || legacyData.get(4).equals("163496")
                                                || legacyData.get(4).equals("162959")
                                                || legacyData.get(4).equals("163503")
                                                || legacyData.get(4).equals("163505")
                                                || legacyData.get(4).equals("163506")
                                                || legacyData.get(4).equals(" 163507")
                                                || legacyData.get(4).equals("163508")
                                                || legacyData.get(4).equals("163510")) {

                                            dod.setFrequency("od");
                                        } else {
                                            dod.setFrequency("bd");
                                        }

                                        // /Save drug order
                                        ordersave = Context.getOrderService().saveOrder(dod);

                                        orderprocess.setDrugOrder(dod);

                                    }

                                    if (dopp.size() > 0) {
                                        DrugOrderProcessed dd = dopp.get(dopp.size() - 1);
                                        // for (DrugOrderProcessed dd :
                                        // dopp) {
                                        if (dd.getDrugRegimen().equals(reg) && !legacyData.get(5).isEmpty()
                                                && dd.getDoseRegimen().equals(legacyData.get(5))
                                                && dd.getTypeOfRegimen().equals(cahngeRegimenType)) {
                                            orderprocess.setRegimenChangeType("Continue");
                                            orderprocess.setDrugOrder(dd.getDrugOrder());

                                        } else {
                                            if (dd.getTypeOfRegimen().equals(cahngeRegimenType)) {
                                                orderprocess.setRegimenChangeType("Substitue");
                                            } else if (dd.getTypeOfRegimen().equals(cahngeRegimenType)) {
                                                orderprocess.setRegimenChangeType("Switch");
                                            }
                                            // Encounter Created
                                            EncounterType regEnrollEncType = MetadataUtils.existing(
                                                    EncounterType.class,
                                                    CommonMetadata._EncounterType.REGIMEN_ORDER);

                                            Encounter regEncounter = new Encounter();
                                            regEncounter.setEncounterType(regEnrollEncType);
                                            regEncounter.setPatient(patient);
                                            regEncounter.setLocation(Context.getLocationService()
                                                    .getLocationByUuid("8d6c993e-c2cc-11de-8d13-0010c6dffd0f"));

                                            regEncounter.setDateCreated(curDate);
                                            regEncounter.setEncounterDatetime(dateVisit);
                                            regEncounter.setVisit(v);

                                            regEncounter.setVoided(false);

                                            // Save encounter
                                            Encounter enregNew = Context.getEncounterService()
                                                    .saveEncounter(regEncounter);

                                            // Create order
                                            Order ordersave = new Order();

                                            // Create Drug order
                                            DrugOrder dod = new DrugOrder();

                                            dod.setOrderType(Context.getOrderService().getOrderType(2));
                                            dod.setConcept(Context.getConceptService()
                                                    .getConcept(Integer.parseInt(legacyData.get(4))));
                                            dod.setEncounter(enregNew);

                                            dod.setStartDate(dateVisit);
                                            dod.setDateCreated(curDate);
                                            dod.setPatient(patient);
                                            dod.setUnits("tab");
                                            if (legacyData.get(4).equals("163494")
                                                    || legacyData.get(4).equals("163495")
                                                    || legacyData.get(4).equals("163496")
                                                    || legacyData.get(4).equals("162959")
                                                    || legacyData.get(4).equals("163503")
                                                    || legacyData.get(4).equals("163505")
                                                    || legacyData.get(4).equals("163506")
                                                    || legacyData.get(4).equals(" 163507")
                                                    || legacyData.get(4).equals("163508")
                                                    || legacyData.get(4).equals("163510")) {

                                                dod.setFrequency("od");
                                            } else {
                                                dod.setFrequency("bd");
                                            }

                                            // /Save drug order
                                            ordersave = Context.getOrderService().saveOrder(dod);

                                            orderprocess.setDrugOrder(dod);

                                        }

                                    }

                                    kes.saveDrugOrderProcessed(orderprocess);

                                    Order oo = new Order();
                                    DrugOrderProcessed drugoo = new DrugOrderProcessed();
                                    for (DrugOrderProcessed ooo : dopp) {
                                        if (!legacyData.get(36).isEmpty()) {
                                            Date discontinuedDate = new Date();
                                            discontinuedDate = (Date) formatter.parse(legacyData.get(36));
                                            String dtechk = visitDateInExcel.format(discontinuedDate);
                                            try {
                                                Date curDat = new Date();
                                                List<Visit> visitdrug = Context.getVisitService()
                                                        .getVisitsByPatient(patient);

                                                for (Visit visdr : visitdrug) {
                                                    if (visdr.getStopDatetime() != null) {
                                                        if (drugoo.getDiscontinuedDate() == null) {
                                                            discontinuedDate = mysqlDateTimeFormatter
                                                                    .parse(dtechk + " " + curDat.getHours()
                                                                            + ":" + curDat.getMinutes() + ":"
                                                                            + curDat.getSeconds());

                                                            drugoo.setDiscontinuedDate(dateVisit);
                                                            break;
                                                        }
                                                    }
                                                }

                                            } catch (ParseException e) {
                                                e.printStackTrace();
                                            }

                                        }
                                        if (!legacyData.get(35).isEmpty()) {
                                            List<Visit> visitdrug = Context.getVisitService()
                                                    .getVisitsByPatient(patient);
                                            Concept discontinuedReason = Context.getConceptService()
                                                    .getConcept(Integer.parseInt(legacyData.get(35)));

                                            for (Visit visdr : visitdrug) {
                                                Order orderPrevious = Context.getOrderService()
                                                        .getOrder(ooo.getDrugOrder().getOrderId());
                                                if (visdr.getStopDatetime() != null) {
                                                    if (orderPrevious.getDiscontinuedReason() == null) {
                                                        if (!ooo.getDrugRegimen()
                                                                .equals(drugoo.getDrugRegimen())) {
                                                            drugoo.setDiscontinuedReason(discontinuedReason);
                                                            orderPrevious.setDiscontinued(true);
                                                            orderPrevious
                                                                    .setDiscontinuedBy(Context.getUserService()
                                                                            .getUserByUsername("admin"));
                                                            orderPrevious
                                                                    .setDiscontinuedReason(discontinuedReason);
                                                            orderPrevious.setDiscontinuedDate(dateVisit);
                                                            Context.getOrderService().saveOrder(orderPrevious);
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        drugoo = ooo;

                                        kes.saveDrugOrderProcessed(drugoo);
                                    }
                                }

                                EncounterType labEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.LAB_ORDERS);
                                Encounter labEncounter = new Encounter();

                                labEncounter.setEncounterType(labEnrollEncType);
                                labEncounter.setPatient(patient);
                                labEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                labEncounter.setDateCreated(curDate);
                                labEncounter.setEncounterDatetime(dateVisit);

                                labEncounter.setForm(
                                        MetadataUtils.existing(Form.class, CommonMetadata._Form.LAB_ORDERS));
                                labEncounter.setVisit(v);

                                labEncounter.setVoided(false);

                                Encounter enlabNew = Context.getEncounterService().saveEncounter(labEncounter);

                                if (!legacyData.get(7).isEmpty()) {
                                    Concept labOrder = Dictionary.getConcept(Dictionary.CD4_COUNT);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labOrder, "",
                                            null, null, enlabNew, null, v);

                                }
                                if (!legacyData.get(39).isEmpty()) {
                                    Concept labOrder = Context.getConceptService()
                                            .getConceptByUuid("122858AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labOrder, "",
                                            null, null, enlabNew, null, v);

                                }
                                if (!legacyData.get(38).isEmpty()) {
                                    Concept labOrder = Context.getConceptService()
                                            .getConceptByUuid("654AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labOrder, "",
                                            null, null, enlabNew, null, v);

                                }
                                if (!legacyData.get(8).isEmpty()) {

                                    Concept labviralOrder = Dictionary.getConcept(Dictionary.HIV_VIRAL_LOAD);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labviralOrder,
                                            "", null, null, enlabNew, null, v);

                                }

                                if (!legacyData.get(37).isEmpty()) {

                                    Concept labhaemoOrder = Context.getConceptService()
                                            .getConceptByUuid("1019AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labhaemoOrder,
                                            "", null, null, enlabNew, null, v);

                                }
                                if (!legacyData.get(40).isEmpty()) {

                                    Concept labcreatinineOrder = Context.getConceptService()
                                            .getConceptByUuid("790AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER),
                                            labcreatinineOrder, "", null, null, enlabNew, null, v);

                                }
                                EncounterType labresultEnrollEncType = MetadataUtils.existing(
                                        EncounterType.class, CommonMetadata._EncounterType.LAB_RESULTS);
                                Encounter labresultEncounter = new Encounter();

                                labresultEncounter.setEncounterType(labresultEnrollEncType);
                                labresultEncounter.setPatient(patient);

                                labresultEncounter.setDateCreated(curDate);
                                labresultEncounter.setEncounterDatetime(dateVisit);
                                labresultEncounter.setVisit(v);

                                labresultEncounter.setVoided(false);
                                Encounter enlabresultNew = Context.getEncounterService()
                                        .saveEncounter(labresultEncounter);

                                if (!legacyData.get(7).isEmpty()) {

                                    String cd4Result = legacyData.get(7);
                                    Double cd4Count = Double.parseDouble(cd4Result);
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.CD4_COUNT), null,
                                            legacyData.get(7), null, cd4Count, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(37).isEmpty()) {

                                    String labResult = legacyData.get(37);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("1019AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            null, labResult, null, null, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(38).isEmpty()) {

                                    String labResult = legacyData.get(38);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("122858AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            null, labResult, null, lab, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(39).isEmpty()) {

                                    String labResult = legacyData.get(39);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("654AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            null, labResult, null, lab, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(8).isEmpty()) {

                                    String labResult = legacyData.get(8);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.HIV_VIRAL_LOAD), null, labResult,
                                            null, lab, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(40).isEmpty()) {

                                    String labResult = legacyData.get(40);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("790AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            null, labResult, null, lab, enlabresultNew, null, v);

                                }
                                EncounterType tbOIEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.CONSULTATION);
                                Encounter tbOIEncounter = new Encounter();

                                tbOIEncounter.setEncounterType(tbOIEnrollEncType);
                                tbOIEncounter.setPatient(patient);

                                tbOIEncounter.setDateCreated(curDate);
                                tbOIEncounter.setEncounterDatetime(dateVisit);
                                tbOIEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                tbOIEncounter.setForm(
                                        MetadataUtils.existing(Form.class, CommonMetadata._Form.TB_SCREENING));
                                tbOIEncounter.setVisit(v);
                                tbOIEncounter.setVoided(false);
                                Encounter entbOIresultNew = Context.getEncounterService()
                                        .saveEncounter(tbOIEncounter);
                                Obs o = null;
                                if (!legacyData.get(27).isEmpty()) {
                                    String text = "";
                                    Obs OIGroup = new Obs();
                                    OIGroup.setPerson(patient);
                                    OIGroup.setConcept(Dictionary.getConcept(Dictionary.OI_GROUP_TB_FORM));

                                    OIGroup.setObsDatetime(entbOIresultNew.getEncounterDatetime());
                                    // Added value coded as per default obs
                                    // object
                                    // format.
                                    OIGroup.setValueCoded(null);
                                    OIGroup.setValueText(text);
                                    OIGroup.setLocation(
                                            Context.getService(KenyaEmrService.class).getDefaultLocation());

                                    OIGroup.setEncounter(entbOIresultNew);

                                    if (!legacyData.get(27).isEmpty()) {
                                        o = Context.getObsService().saveObs(OIGroup,
                                                "KenyaEMR History Details");
                                    }

                                    if (!legacyData.get(27).isEmpty()) {
                                        String oivalue = legacyData.get(27);
                                        String[] valueList = oivalue.split("\\s*,\\s*");

                                        for (String oiname : valueList) {

                                            Concept oiConcept = Context.getConceptService().getConcept(oiname);

                                            handleOncePerPatientObs(patient,
                                                    Dictionary.getConcept(Dictionary.HIV_CARE_DIAGNOSIS),
                                                    oiConcept, "", null, null, entbOIresultNew, o, v);

                                        }

                                    }

                                }

                                if (!legacyData.get(10).isEmpty()) {

                                    Concept tbStatus = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(10)));

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TB_PATIENT), tbStatus, "", null,
                                            null, entbOIresultNew, null, v);

                                }
                                if (!legacyData.get(11).isEmpty()) {

                                    Concept tbDiseaseClassification = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(11)));
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.SITE_OF_TUBERCULOSIS_DISEASE),
                                            tbDiseaseClassification, "", null, null, entbOIresultNew, null, v);
                                    if (!legacyData.get(12).isEmpty()) {
                                        if (!tbDiseaseClassification.equals("42")) {
                                            Concept tbsiteClassification = Context.getConceptService()
                                                    .getConcept(Integer.parseInt(legacyData.get(12)));
                                            handleOncePerPatientObs(patient,
                                                    Dictionary.getConcept(Dictionary.TB_SITE),
                                                    tbsiteClassification, "", null, null, entbOIresultNew, null,
                                                    v);
                                        }
                                    }
                                }

                                if (!legacyData.get(13).isEmpty()) {

                                    SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                                    Date tbStartDate = new Date();
                                    try {
                                        tbStartDate = (Date) formatter.parse(legacyData.get(13));

                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(
                                                    Dictionary.TUBERCULOSIS_DRUG_TREATMENT_START_DATE),
                                            null, null, tbStartDate, null, entbOIresultNew, null, v);
                                }
                                if (!legacyData.get(14).isEmpty()) {

                                    Concept tbTownship = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(14)));
                                    handleOncePerPatientObs(patient, Dictionary.getConcept(Dictionary.TOWNSHIP),
                                            tbTownship, "", null, null, entbOIresultNew, null, v);
                                }
                                if (!legacyData.get(15).isEmpty()) {

                                    String tbclinicName = "";
                                    tbclinicName = legacyData.get(15);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TB_CLINIC_NAME), null,
                                            tbclinicName, null, null, entbOIresultNew, null, v);
                                }
                                if (!legacyData.get(16).isEmpty()) {

                                    String tbregistrationNumber = "";
                                    tbregistrationNumber = legacyData.get(16);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TUBERCULOSIS_TREATMENT_NUMBER),
                                            null, tbregistrationNumber, null, null, entbOIresultNew, null, v);
                                }
                                if (!legacyData.get(17).isEmpty()) {
                                    Concept tbRegimen = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(17)));
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TB_FORM_REGIMEN), tbRegimen, "",
                                            null, null, entbOIresultNew, null, v);

                                }
                                if (!legacyData.get(18).isEmpty()) {

                                    Concept tbOutcome = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(18)));

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TUBERCULOSIS_TREATMENT_OUTCOME),
                                            tbOutcome, null, null, null, entbOIresultNew, null, v);
                                }

                                if (!legacyData.get(19).isEmpty()) {

                                    Date tbOutcomeDate = null;
                                    Date curDatenew = new Date();
                                    try {
                                        tbOutcomeDate = (Date) formatter.parse(legacyData.get(19));
                                        dateCheck = visitDateInExcel.format(tbOutcomeDate);
                                        tbOutcomeDate = mysqlDateTimeFormatter.parse(dateCheck + " "
                                                + curDatenew.getHours() + ":" + curDatenew.getMinutes() + ":"
                                                + curDatenew.getSeconds());
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TB_OUTCOME_DATE), null, null,
                                            tbOutcomeDate, null, entbOIresultNew, null, v);
                                }
                                int flag = 0;

                                if (!legacyData.get(20).isEmpty()) {

                                    EncounterType HivdiscontEnrollEncType = MetadataUtils.existing(
                                            EncounterType.class,
                                            HivMetadata._EncounterType.HIV_DISCONTINUATION);
                                    Encounter hivDiscontEncounter = new Encounter();

                                    hivDiscontEncounter.setEncounterType(HivdiscontEnrollEncType);
                                    hivDiscontEncounter.setPatient(patient);

                                    hivDiscontEncounter.setDateCreated(curDate);
                                    hivDiscontEncounter.setEncounterDatetime(dateVisit);
                                    hivDiscontEncounter.setLocation(
                                            Context.getService(KenyaEmrService.class).getDefaultLocation());

                                    hivDiscontEncounter.setForm(MetadataUtils.existing(Form.class,
                                            HivMetadata._Form.HIV_DISCONTINUATION));
                                    hivDiscontEncounter.setVisit(v);
                                    hivDiscontEncounter.setVoided(false);
                                    Encounter enhivDiscontresultNew = Context.getEncounterService()
                                            .saveEncounter(hivDiscontEncounter);

                                    Concept endOfFollowup = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(20)));
                                    if (legacyData.get(20).equals("160034")) {
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(
                                                        Dictionary.REASON_FOR_PROGRAM_DISCONTINUATION),
                                                endOfFollowup, null, null, null, enhivDiscontresultNew, null,
                                                v);
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(Dictionary.DEATH_DATE), null, null,
                                                dateVisit, null, enhivDiscontresultNew, null, v);
                                        flag = 1;

                                    } else if (legacyData.get(20).equals("159492")) {
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(
                                                        Dictionary.REASON_FOR_PROGRAM_DISCONTINUATION),
                                                endOfFollowup, null, null, null, enhivDiscontresultNew, null,
                                                v);
                                        if (!legacyData.get(22).isEmpty()) {
                                            String transferdto = legacyData.get(22);

                                            handleOncePerPatientObs(patient,
                                                    Dictionary.getConcept(Dictionary.TRANSFERRED_OUT_TO), null,
                                                    transferdto, null, null, enhivDiscontresultNew, null, v);

                                        }
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(Dictionary.DATE_TRANSFERRED_OUT), null,
                                                null, dateVisit, null, enhivDiscontresultNew, null, v);

                                    } else {
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(
                                                        Dictionary.REASON_FOR_PROGRAM_DISCONTINUATION),
                                                endOfFollowup, null, null, null, enhivDiscontresultNew, null,
                                                v);

                                    }

                                    if (!legacyData.get(21).isEmpty()) {
                                        Date programcmpleteDate = null;
                                        Date curDatenew = new Date();
                                        try {
                                            programcmpleteDate = (Date) formatter.parse(legacyData.get(21));
                                            dateCheck = visitDateInExcel.format(programcmpleteDate);
                                            programcmpleteDate = mysqlDateTimeFormatter.parse(dateCheck + " "
                                                    + curDatenew.getHours() + ":" + curDatenew.getMinutes()
                                                    + ":" + curDatenew.getSeconds());
                                            Collection<PatientProgram> hivprogram = Context
                                                    .getProgramWorkflowService().getPatientPrograms(patient);
                                            for (PatientProgram prog : hivprogram) {
                                                if (prog.getPatient().equals(patient)) {
                                                    if (prog.getProgram().getUuid()
                                                            .equals("dfdc6d40-2f2f-463d-ba90-cc97350441a8")
                                                            && prog.getDateCompleted() == null) {
                                                        prog.setDateCompleted(programcmpleteDate);
                                                        Context.getProgramWorkflowService()
                                                                .savePatientProgram(prog);
                                                    }

                                                }
                                            }
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }

                                    }

                                }

                                if (!legacyData.get(23).isEmpty() && !legacyData.get(24).isEmpty()) {
                                    PatientProgram activeArtProgram = null;
                                    Collection<PatientProgram> artProgram = Context.getProgramWorkflowService()
                                            .getPatientPrograms(patient);
                                    for (PatientProgram artProg : artProgram) {
                                        if (artProg.getProgram().getUuid()
                                                .equals("96ec813f-aaf0-45b2-add6-e661d5bf79d6")
                                                && artProg.getDateCompleted() == null) {
                                            activeArtProgram = artProg;
                                        }
                                    }

                                    EncounterType ArtdiscontEnrollEncType = MetadataUtils
                                            .existing(EncounterType.class, ArtMetadata._EncounterType.STOP_ART);
                                    Encounter artDiscontEncounter = new Encounter();

                                    artDiscontEncounter.setEncounterType(ArtdiscontEnrollEncType);
                                    artDiscontEncounter.setPatient(patient);

                                    artDiscontEncounter.setDateCreated(curDate);
                                    artDiscontEncounter.setEncounterDatetime(dateVisit);
                                    artDiscontEncounter.setLocation(
                                            Context.getService(KenyaEmrService.class).getDefaultLocation());

                                    artDiscontEncounter.setForm(
                                            MetadataUtils.existing(Form.class, ArtMetadata._Form.STOP_ART));
                                    artDiscontEncounter.setVisit(v);
                                    artDiscontEncounter.setVoided(false);
                                    Encounter enartDiscontresultNew = Context.getEncounterService()
                                            .saveEncounter(artDiscontEncounter);
                                    Date programcmpleteDate = null;
                                    Date curDatenew = new Date();
                                    try {
                                        programcmpleteDate = (Date) formatter.parse(legacyData.get(23));
                                        dateCheck = visitDateInExcel.format(programcmpleteDate);
                                        programcmpleteDate = mysqlDateTimeFormatter.parse(dateCheck + " "
                                                + curDatenew.getHours() + ":" + curDatenew.getMinutes() + ":"
                                                + curDatenew.getSeconds());
                                        if (activeArtProgram != null) {
                                            activeArtProgram.setDateCompleted(programcmpleteDate);
                                        }
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    Context.getProgramWorkflowService().savePatientProgram(activeArtProgram);

                                    if (!legacyData.get(24).isEmpty()) {
                                        Concept endOfArt = Context.getConceptService()
                                                .getConcept(Integer.parseInt(legacyData.get(24)));

                                        handleOncePerPatientObs(patient,
                                                Context.getConceptService().getConceptByUuid(
                                                        "1252AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                                endOfArt, null, null, null, enartDiscontresultNew, null, v);

                                    }
                                }

                                EncounterType consultEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.CONSULTATION);
                                Encounter consultEncounter = new Encounter();

                                consultEncounter.setEncounterType(consultEnrollEncType);
                                consultEncounter.setPatient(patient);

                                consultEncounter.setDateCreated(curDate);
                                consultEncounter.setEncounterDatetime(dateVisit);
                                consultEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                consultEncounter.setForm(MetadataUtils.existing(Form.class,
                                        CommonMetadata._Form.CONSULTATION_ENCOUNTER));
                                consultEncounter.setVisit(v);
                                consultEncounter.setVoided(false);
                                Encounter enconsultresultNew = Context.getEncounterService()
                                        .saveEncounter(consultEncounter);
                                if (!legacyData.get(30).isEmpty()) {

                                    Concept sideffectsOfArt = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(30)));

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("159935AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            Dictionary.getConcept(Dictionary.YES), null, null, null,
                                            enconsultresultNew, null, v);
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.ART_SIDE_EFFECTS_VALUES),
                                            sideffectsOfArt, null, null, null, enconsultresultNew, null, v);

                                }
                                if (!legacyData.get(31).isEmpty()) {

                                    String levelOfAdherence = legacyData.get(31);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.ART_ADHERENCE), null,
                                            levelOfAdherence, null, null, enconsultresultNew, null, v);

                                }
                                if (!legacyData.get(41).isEmpty()) {

                                    Concept temporaryreferal = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(41)));

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("5e05d243-e039-4f04-9988-18d5a499329e"),
                                            Dictionary.getConcept(Dictionary.YES), null, null, null,
                                            enconsultresultNew, null, v);
                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("c648f69b-7065-4255-9af2-6076348c87dc"),
                                            temporaryreferal, null, null, null, enconsultresultNew, null, v);

                                }
                                if (!legacyData.get(28).isEmpty()) {

                                    Concept tbOutcome = new Concept();
                                    String performance = legacyData.get(28);
                                    if (performance.equals("A")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.PERFSCALE_A);
                                    } else if (performance.equals("B")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.PERFSCALE_B);
                                    } else {
                                        tbOutcome = Dictionary.getConcept(Dictionary.PERFSCALE_C);
                                    }
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.PERFORMANCE), tbOutcome, null,
                                            null, null, entbOIresultNew, null, v);
                                }

                                if (!legacyData.get(29).isEmpty()) {

                                    Concept tbOutcome = new Concept();
                                    String stage = legacyData.get(29);
                                    if (stage.equals("IV")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.WHO_STAGE_4_ADULT);
                                    } else if (stage.equals("III")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.WHO_STAGE_3_ADULT);
                                    } else if (stage.equals("II")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.WHO_STAGE_2_ADULT);
                                    } else {
                                        tbOutcome = Dictionary.getConcept(Dictionary.WHO_STAGE_1_ADULT);
                                    }
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.CURRENT_WHO_STAGE), tbOutcome,
                                            null, null, null, entbOIresultNew, null, v);

                                }
                                EncounterType nextAppointEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.CONSULTATION);
                                Encounter nextAppointEncounter = new Encounter();

                                nextAppointEncounter.setEncounterType(nextAppointEncType);
                                nextAppointEncounter.setPatient(patient);

                                nextAppointEncounter.setDateCreated(curDate);
                                nextAppointEncounter.setEncounterDatetime(dateVisit);
                                nextAppointEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());
                                nextAppointEncounter.setVisit(v);
                                nextAppointEncounter.setVoided(false);
                                Encounter ennextAppointresultNew = new Encounter();
                                if (!legacyData.get(32).isEmpty()) {
                                    ennextAppointresultNew = Context.getEncounterService()
                                            .saveEncounter(nextAppointEncounter);
                                }
                                if (!legacyData.get(32).isEmpty()) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                                    Date nextAppointDate = new Date();
                                    try {
                                        nextAppointDate = (Date) formatter.parse(legacyData.get(32));

                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.RETURN_VISIT_DATE), null, null,
                                            nextAppointDate, null, ennextAppointresultNew, null, v);
                                }

                                // For OI or PROPHYLAXIS
                                if (!legacyData.get(33).isEmpty() || !legacyData.get(34).isEmpty()) {

                                    // For Duration of Medication
                                    if (!legacyData.get(6).isEmpty()) {

                                        EncounterType otherMedicationEnrollEncType = MetadataUtils.existing(
                                                EncounterType.class,
                                                CommonMetadata._EncounterType.CONSULTATION);
                                        Encounter otherMedEncounter = new Encounter();

                                        otherMedEncounter.setEncounterType(otherMedicationEnrollEncType);
                                        otherMedEncounter.setPatient(patient);

                                        otherMedEncounter.setDateCreated(curDate);
                                        otherMedEncounter.setEncounterDatetime(dateVisit);
                                        otherMedEncounter.setLocation(
                                                Context.getService(KenyaEmrService.class).getDefaultLocation());

                                        otherMedEncounter.setForm(MetadataUtils.existing(Form.class,
                                                CommonMetadata._Form.OTHER_MEDICATIONS));
                                        otherMedEncounter.setVisit(v);
                                        otherMedEncounter.setVoided(false);
                                        Encounter enotherresultNew = Context.getEncounterService()
                                                .saveEncounter(otherMedEncounter);

                                        String duration = legacyData.get(6);
                                        Double durationDouble = Double.parseDouble(duration);
                                        int durationInteger = Integer.parseInt(legacyData.get(6));

                                        /*
                                         * PROPHYLAXIS start
                                         */

                                        if (!legacyData.get(33).isEmpty()) {

                                            String value = legacyData.get(33);

                                            String[] valueList = value.split("\\s*,\\s*");

                                            for (String prop : valueList) {
                                                // Group for each Drug
                                                String text = "";
                                                Obs prophylGroup = new Obs();
                                                prophylGroup.setPerson(patient);
                                                prophylGroup.setConcept(
                                                        Context.getConceptService().getConceptByUuid(
                                                                "163022AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
                                                prophylGroup.setObsDatetime(
                                                        enotherresultNew.getEncounterDatetime());
                                                prophylGroup.setValueCoded(null);
                                                prophylGroup.setValueText(text);
                                                prophylGroup
                                                        .setLocation(Context.getService(KenyaEmrService.class)
                                                                .getDefaultLocation());

                                                prophylGroup.setEncounter(enotherresultNew);
                                                prophylGroup.setComment("1");
                                                Obs prophyl = Context.getObsService().saveObs(prophylGroup,
                                                        "KenyaEMR History Details");

                                                Concept oivalue = Context.getConceptService().getConcept(prop);

                                                // CPT for CTX
                                                if (oivalue.getUuid().toString()
                                                        .equals("105281AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")) {
                                                    handleOncePerPatientObs(patient,
                                                            Dictionary.getConcept(Dictionary.CPT_VALUE),
                                                            Context.getConceptService().getConcept(1065), "",
                                                            null, null, enotherresultNew, null, v);
                                                }

                                                // IPT for Isoniazid
                                                if (oivalue.getUuid().toString()
                                                        .equals("78280AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")) {
                                                    handleOncePerPatientObs(patient,
                                                            Dictionary.getConcept(Dictionary.IPT_VALUE),
                                                            Context.getConceptService().getConcept(1065), "",
                                                            null, null, enotherresultNew, null, v);
                                                }

                                                handleOncePerPatientObs(patient,
                                                        Dictionary.getConcept(Dictionary.PROPHYLAXIS), oivalue,
                                                        "", null, null, enotherresultNew, prophyl, v);

                                                handleOncePerPatientObs(patient,
                                                        Dictionary.getConcept(Dictionary.MEDICATION_DURATION),
                                                        null, "", null, durationDouble, enotherresultNew,
                                                        prophyl, v);

                                                // Capture Drug in Drug obs
                                                // processed
                                                DrugObsProcessed dop = new DrugObsProcessed();
                                                dop.setObs(prophyl);
                                                dop.setCreatedDate(curDate);
                                                dop.setPatient(patient);
                                                dop.setProcessedDate(dateVisit);
                                                dop.setQuantityPostProcess(durationInteger);

                                                KenyaEmrService kes = (KenyaEmrService) Context
                                                        .getService(KenyaEmrService.class);
                                                kes.saveDrugObsProcessed(dop);
                                            }

                                        }

                                        /*
                                         * PROPHYLAXIS End
                                         */

                                        if (!legacyData.get(34).isEmpty()) {

                                            String value = legacyData.get(34);

                                            String[] valueList = value.split("\\s*,\\s*");

                                            for (String oil : valueList) {
                                                // Group for each Drug
                                                String text = "";
                                                Obs oitreatmentGroup = new Obs();
                                                oitreatmentGroup.setPerson(patient);
                                                oitreatmentGroup.setConcept(
                                                        Context.getConceptService().getConceptByUuid(
                                                                "163021AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));

                                                oitreatmentGroup.setObsDatetime(
                                                        enotherresultNew.getEncounterDatetime());

                                                oitreatmentGroup.setValueCoded(null);
                                                oitreatmentGroup.setValueText(text);
                                                oitreatmentGroup
                                                        .setLocation(Context.getService(KenyaEmrService.class)
                                                                .getDefaultLocation());

                                                oitreatmentGroup.setEncounter(enotherresultNew);
                                                oitreatmentGroup.setComment("1");
                                                Obs oitreat = Context.getObsService().saveObs(oitreatmentGroup,
                                                        "KenyaEMR History Details");

                                                Concept oivalue = Context.getConceptService().getConcept(oil);

                                                handleOncePerPatientObs(patient,
                                                        Dictionary.getConcept(Dictionary.OI_TREATMENT_DRUG),
                                                        oivalue, "", null, null, enotherresultNew, oitreat, v);

                                                handleOncePerPatientObs(patient,
                                                        Dictionary.getConcept(Dictionary.MEDICATION_DURATION),
                                                        null, "", null, durationDouble, enotherresultNew,
                                                        oitreat, v);

                                                // Capture Drug in Drug obs
                                                // processed
                                                DrugObsProcessed dop = new DrugObsProcessed();
                                                dop.setObs(oitreat);
                                                dop.setCreatedDate(curDate);
                                                dop.setPatient(patient);
                                                dop.setProcessedDate(dateVisit);
                                                dop.setQuantityPostProcess(durationInteger);

                                                KenyaEmrService kes = (KenyaEmrService) Context
                                                        .getService(KenyaEmrService.class);
                                                kes.saveDrugObsProcessed(dop);
                                            }
                                        }
                                    }
                                }

                                EncounterType recordEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.CONSULTATION);
                                Encounter recordEncounter = new Encounter();

                                recordEncounter.setEncounterType(recordEncType);
                                recordEncounter.setPatient(patient);

                                recordEncounter.setDateCreated(curDate);
                                recordEncounter.setEncounterDatetime(dateVisit);
                                recordEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                recordEncounter.setForm(
                                        MetadataUtils.existing(Form.class, CommonMetadata._Form.TRIAGE));
                                recordEncounter.setVisit(v);
                                recordEncounter.setVoided(false);
                                Encounter enrecordvitalresultNew = Context.getEncounterService()
                                        .saveEncounter(recordEncounter);
                                if (!legacyData.get(25).isEmpty()) {

                                    String labResult = legacyData.get(25);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.WEIGHT_KG), null, null, null, lab,
                                            enrecordvitalresultNew, null, v);

                                }

                                if (!legacyData.get(26).isEmpty()) {

                                    String labResult = legacyData.get(26);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.HEIGHT_CM), null, null, null, lab,
                                            enrecordvitalresultNew, null, v);

                                }

                                EncounterType hivEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        HivMetadata._EncounterType.HIV_ENROLLMENT);
                                EncounterType registrationEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.REGISTRATION);
                                Encounter obstericEncounter = new Encounter();

                                obstericEncounter.setEncounterType(registrationEncType);
                                obstericEncounter.setPatient(patient);

                                obstericEncounter.setDateCreated(curDate);
                                obstericEncounter.setEncounterDatetime(dateVisit);
                                obstericEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                obstericEncounter.setForm(
                                        MetadataUtils.existing(Form.class, Metadata.Form.OBSTETRIC_HISTORY));
                                obstericEncounter.setVisit(v);
                                obstericEncounter.setVoided(false);
                                Encounter enobstericrecordresultNew = Context.getEncounterService()
                                        .saveEncounter(obstericEncounter);
                                if (!legacyData.get(42).isEmpty()) {

                                    Concept pregstatus = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(42)));
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.PREGNANCY_STATUS), pregstatus, "",
                                            null, null, enobstericrecordresultNew, null, v);

                                }
                                if (!legacyData.get(43).isEmpty()) {

                                    Concept familyplanningstatus = Dictionary.getConcept(Dictionary.YES);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("5271AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            familyplanningstatus, "", null, null, enobstericrecordresultNew,
                                            null, v);

                                }
                                if (!legacyData.get(43).isEmpty()) {

                                    Concept familyplanningvalue = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(43)));

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.METHOD_OF_FAMILY_PLANNING),
                                            familyplanningvalue, "", null, null, enobstericrecordresultNew,
                                            null, v);

                                }

                                DateFormat visitDatesInExcel = new SimpleDateFormat("dd-MMM-yyyy");
                                String dateChecks = visitDatesInExcel.format(dateVisit);
                                if (legacyData.get(3) != null) {
                                    Date Datenew = new Date();
                                    try {
                                        dateVisit = mysqlDateTimeFormatter
                                                .parse(dateChecks + " " + Datenew.getHours() + ":"
                                                        + Datenew.getMinutes() + ":" + Datenew.getSeconds());

                                    } catch (ParseException e) {
                                        dateVisit = Datenew;

                                        e.printStackTrace();
                                    }
                                }

                                v.setStopDatetime(dateVisit);

                                Context.getVisitService().saveVisit(v);

                                if (flag == 1) {
                                    person.setDead(true);
                                    person.setDeathDate(dateVisit);
                                    person.setCauseOfDeath(Dictionary.getConcept(Dictionary.UNKNOWN));
                                    Context.getPersonService().savePerson(person);
                                }
                            }

                        }

                        catch (IndexOutOfBoundsException e) {
                            e.printStackTrace();
                        }
                    } else {
                        break;
                    }
                }
            } catch (IndexOutOfBoundsException e) {
                break;
            }

            rowCountVisit++;
        }
    }

    inputStream.close();
    // workbook.close();
    return new SuccessResult("Saved Patient Data");
}

From source file:org.openmrs.module.mksreports.renderer.PatientHistoryExcelTemplateRenderer.java

License:Open Source License

/**
 * Adds in a Row to the given Sheet/*from   www .  ja  va2s  .  c o  m*/
 */
public Row addRow(Workbook wb, SheetToAdd sheetToAdd, RowToAdd rowToAdd, int rowIndex, ReportData reportData,
        ReportDesign design, Map<String, String> repeatSections) {

    // Create a new row and copy over style attributes from the row to add
    Row newRow = sheetToAdd.getSheet().createRow(rowIndex);
    Row rowToClone = rowToAdd.getRowToClone();
    try {
        CellStyle rowStyle = rowToClone.getRowStyle();
        if (rowStyle != null) {
            newRow.setRowStyle(rowStyle);
        }
    } catch (Exception e) {
        // No idea why this is necessary, but this has thrown IndexOutOfBounds errors getting the rowStyle.  Mysteries of POI
    }
    newRow.setHeight(rowToClone.getHeight());

    // Iterate across all of the cells in the row, and configure all those that need to be added/cloned
    List<CellToAdd> cellsToAdd = new ArrayList<CellToAdd>();

    int totalCells = rowToClone.getPhysicalNumberOfCells();
    int cellsFound = 0;
    for (int cellNum = 0; cellsFound < totalCells; cellNum++) {
        Cell currentCell = rowToClone.getCell(cellNum);
        log.debug("Handling cell: " + currentCell);
        if (currentCell != null) {
            cellsFound++;
        }
        // If we find that the cell that we are on is a repeating cell, then add the appropriate number of cells to clone
        String repeatingColumnProperty = getRepeatingColumnProperty(sheetToAdd.getOriginalSheetNum(), cellNum,
                repeatSections);
        if (repeatingColumnProperty != null) {
            String[] dataSetSpanSplit = repeatingColumnProperty.split(",");
            String dataSetName = dataSetSpanSplit[0];
            DataSet dataSet = getDataSet(reportData, dataSetName, rowToAdd.getReplacementData());
            int numCellsToRepeat = 1;
            if (dataSetSpanSplit.length == 2) {
                numCellsToRepeat = Integer.parseInt(dataSetSpanSplit[1]);
            }
            log.debug("Repeating this cell with dataset: " + dataSet + " and repeat of " + numCellsToRepeat);
            int repeatNum = 0;
            for (DataSetRow dataSetRow : dataSet) {
                repeatNum++;
                for (int i = 0; i < numCellsToRepeat; i++) {
                    Cell cell = (i == 0 ? currentCell : rowToClone.getCell(cellNum + i));
                    if (repeatNum == 1 && cell != null && cell != currentCell) {
                        cellsFound++;
                    }
                    Map<String, Object> newReplacements = getReplacementData(rowToAdd.getReplacementData(),
                            reportData, design, dataSetName, dataSetRow, repeatNum);
                    cellsToAdd.add(new CellToAdd(cell, newReplacements));
                    log.debug("Adding " + cell + " with dataSetRow: " + dataSetRow);
                }
            }
            cellNum += numCellsToRepeat;
        } else {
            cellsToAdd.add(new CellToAdd(currentCell, rowToAdd.getReplacementData()));
            log.debug("Adding " + currentCell);
        }
    }

    // Now, go through all of the collected cells, and add them back in

    String prefix = getExpressionPrefix(design);
    String suffix = getExpressionSuffix(design);

    List<CellRangeAddress> newMergedRegions = new ArrayList<CellRangeAddress>();

    for (int i = 0; i < cellsToAdd.size(); i++) {
        CellToAdd cellToAdd = cellsToAdd.get(i);
        Cell newCell = newRow.createCell(i);
        Cell cellToClone = cellToAdd.getCellToClone();
        if (cellToClone != null) {
            Object contents = ExcelUtil.getCellContents(cellToClone);
            newCell.setCellStyle(cellToClone.getCellStyle());

            int numFormattings = sheetToAdd.getSheet().getSheetConditionalFormatting()
                    .getNumConditionalFormattings();
            for (int n = 0; n < numFormattings; n++) {
                ConditionalFormatting f = sheetToAdd.getSheet().getSheetConditionalFormatting()
                        .getConditionalFormattingAt(n);
                for (CellRangeAddress add : f.getFormattingRanges()) {

                    if (add.getFirstRow() == rowToAdd.getRowToClone().getRowNum()
                            && add.getLastRow() == rowToClone.getRowNum()) {
                        if (add.getFirstColumn() == cellToClone.getColumnIndex()
                                && add.getLastColumn() == cellToClone.getColumnIndex()) {
                            ConditionalFormattingRule[] rules = new ConditionalFormattingRule[f
                                    .getNumberOfRules()];
                            for (int j = 0; j < f.getNumberOfRules(); j++) {
                                rules[j] = f.getRule(j);
                            }
                            CellRangeAddress[] cellRange = new CellRangeAddress[1];
                            cellRange[0] = new CellRangeAddress(rowIndex, rowIndex, i, i);
                            sheetToAdd.getSheet().getSheetConditionalFormatting()
                                    .addConditionalFormatting(cellRange, rules);
                        }
                    }
                }
            }

            int numMergedRegions = sheetToAdd.getSheet().getNumMergedRegions();
            for (int n = 0; n < numMergedRegions; n++) {
                CellRangeAddress add = sheetToAdd.getSheet().getMergedRegion(n);
                int rowNum = rowToClone.getRowNum();
                if (add.getFirstRow() == rowNum && add.getLastRow() == rowNum) {
                    if (add.getFirstColumn() == cellToClone.getColumnIndex()) {
                        newMergedRegions
                                .add(new CellRangeAddress(rowNum, rowNum, i, i + add.getNumberOfCells() - 1));
                    }
                }
            }

            if (ObjectUtil.notNull(contents)) {
                if (contents instanceof String) {
                    contents = EvaluationUtil.evaluateExpression(contents.toString(),
                            cellToAdd.getReplacementData(), prefix, suffix);
                }
                ExcelUtil.setCellContents(newCell, contents);
            }

            ExcelUtil.copyFormula(cellToClone, newCell);
        }
    }

    for (CellRangeAddress mergedRegion : newMergedRegions) {
        sheetToAdd.getSheet().addMergedRegion(mergedRegion);
    }

    return newRow;
}