Search in sources :

Example 6 with ExportDataFailedOneTableEvent

use of com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent in project cubrid-manager by CUBRID.

the class ExportToXlsHandler method exportByQuerying.

public void exportByQuerying(String tableName) throws IOException, SQLException {
    if (StringUtil.isEmpty(tableName)) {
        // FIXME move this logic to core module
        return;
    }
    long totalRecord = exportConfig.getTotalCount(tableName);
    if (totalRecord == 0) {
        return;
    }
    Connection conn = null;
    CUBRIDPreparedStatementProxy pStmt = null;
    CUBRIDResultSetProxy rs = null;
    WritableWorkbook workbook = null;
    int workbookNum = 0;
    String whereCondition = exportConfig.getWhereCondition(tableName);
    boolean hasNextPage = true;
    long beginIndex = 1;
    int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
    // 65536: limit xls row number.
    int rowLimit = ImportFileConstants.XLS_ROW_LIMIT;
    boolean isInitedColumnTitles = false;
    List<String> columnTitles = new ArrayList<String>();
    try {
        conn = getConnection();
        int sheetNum = 0;
        int xlsRecordNum = 0;
        workbook = createWorkbook(exportConfig.getDataFilePath(tableName), workbookNum++);
        WritableSheet sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
        sheetNum++;
        int exportedCount = 0;
        String sql = QueryUtil.getSelectSQL(conn, tableName);
        isPaginating = isPagination(whereCondition, sql, whereCondition);
        while (hasNextPage) {
            try {
                String executeSQL = null;
                if (isPaginating) {
                    long endIndex = beginIndex + RSPAGESIZE;
                    executeSQL = getExecuteSQL(sql, beginIndex, endIndex, whereCondition);
                    executeSQL = dbInfo.wrapShardQuery(executeSQL);
                    beginIndex = endIndex + 1;
                } else {
                    executeSQL = getExecuteSQL(sql, whereCondition);
                    executeSQL = dbInfo.wrapShardQuery(sql);
                    beginIndex = totalRecord + 1;
                }
                pStmt = getStatement(conn, executeSQL, tableName);
                rs = (CUBRIDResultSetProxy) pStmt.executeQuery();
                CUBRIDResultSetMetaDataProxy rsmt = (CUBRIDResultSetMetaDataProxy) rs.getMetaData();
                int colCount = rsmt.getColumnCount();
                if (!isInitedColumnTitles) {
                    isInitedColumnTitles = true;
                    columnTitles = getColumnTitleList(rsmt);
                    if (isExit) {
                        return;
                    }
                    // first line add column name
                    if (exportConfig.isFirstRowAsColumnName()) {
                        writeHeader(sheet, columnTitles);
                        xlsRecordNum++;
                    }
                }
                while (rs.next()) {
                    //Check memory
                    if (!CommonUITool.isAvailableMemory(REMAINING_MEMORY_SIZE)) {
                        closeWorkbook(workbook);
                        workbook = null;
                        System.gc();
                        workbook = createWorkbook(exportConfig.getDataFilePath(tableName), workbookNum++);
                        sheetNum = 0;
                        sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
                        sheetNum++;
                        xlsRecordNum = 0;
                        // first line add column name
                        if (exportConfig.isFirstRowAsColumnName()) {
                            writeHeader(sheet, columnTitles);
                            xlsRecordNum++;
                        }
                    }
                    for (int j = 1; j <= colCount; j++) {
                        String colType = rsmt.getColumnTypeName(j);
                        colType = FieldHandlerUtils.amendDataTypeByResult(rs, j, colType);
                        int precision = rsmt.getPrecision(j);
                        setIsHasBigValue(colType, precision);
                        Object cellValue = FieldHandlerUtils.getRsValueForExport(colType, rs, j, exportConfig.getNULLValueTranslation());
                        // We need judge the CLOB/BLOD data by column type
                        if (DataType.DATATYPE_BLOB.equals(colType) || DataType.DATATYPE_CLOB.equals(colType)) {
                            if (DataType.DATATYPE_BLOB.equals(colType)) {
                                String fileName = exportBlobData(tableName, rs, j);
                                String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                                if (StringUtil.isNotEmpty(fileName)) {
                                    dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + BLOB_FOLDER_POSTFIX + File.separator + fileName;
                                }
                                sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                            } else {
                                String fileName = exportClobData(tableName, rs, j);
                                String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                                if (StringUtil.isNotEmpty(fileName)) {
                                    dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + CLOB_FOLDER_POSTFIX + File.separator + fileName;
                                }
                                sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                            }
                        } else if (cellValue instanceof Long) {
                            sheet.addCell(new Number(j - 1, xlsRecordNum, (Long) cellValue));
                        } else if (cellValue instanceof Double) {
                            sheet.addCell(new Number(j - 1, xlsRecordNum, (Double) cellValue));
                        } else if (cellValue instanceof Timestamp) {
                            String dataCellValue = FieldHandlerUtils.formatDateTime((Timestamp) cellValue);
                            sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                        } else if (cellValue instanceof java.sql.Time) {
                            String dataCellValue = DateUtil.getDatetimeString(((java.sql.Time) cellValue).getTime(), FieldHandlerUtils.FORMAT_TIME);
                            sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                        } else if (cellValue instanceof java.sql.Date) {
                            String dataCellValue = DateUtil.getDatetimeString(((java.sql.Date) cellValue).getTime(), FieldHandlerUtils.FORMAT_DATE);
                            sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                        } else {
                            sheet.addCell(new Label(j - 1, xlsRecordNum, cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString()));
                        }
                    }
                    xlsRecordNum++;
                    if ((xlsRecordNum + 1) % rowLimit == 0) {
                        xlsRecordNum = 0;
                        sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
                        sheetNum++;
                        // first line add column name
                        if (exportConfig.isFirstRowAsColumnName()) {
                            writeHeader(sheet, columnTitles);
                            xlsRecordNum++;
                        }
                    }
                    exportedCount++;
                    if (exportedCount >= COMMIT_LINES) {
                        exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                        exportedCount = 0;
                    }
                    if (stop) {
                        break;
                    }
                }
                exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                exportedCount = 0;
            } catch (Exception e) {
                LOGGER.error("", e);
                exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(tableName));
            } finally {
                QueryUtil.freeQuery(pStmt, rs);
            }
            if (hasNextPage(beginIndex, totalRecord)) {
                hasNextPage = true;
            } else {
                hasNextPage = false;
            }
            System.gc();
        }
    } catch (Exception e) {
        LOGGER.error("", e);
    } finally {
        QueryUtil.freeQuery(conn);
        closeWorkbook(workbook);
    }
}
Also used : CUBRIDPreparedStatementProxy(com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy) ArrayList(java.util.ArrayList) Label(jxl.write.Label) Timestamp(java.sql.Timestamp) CUBRIDResultSetMetaDataProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetMetaDataProxy) ExportDataFailedOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent) Number(jxl.write.Number) CUBRIDResultSetProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetProxy) Connection(java.sql.Connection) WritableSheet(jxl.write.WritableSheet) WriteException(jxl.write.WriteException) SQLException(java.sql.SQLException) IOException(java.io.IOException) RowsExceededException(jxl.write.biff.RowsExceededException) WritableWorkbook(jxl.write.WritableWorkbook) ExportDataSuccessEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent)

Example 7 with ExportDataFailedOneTableEvent

use of com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent in project cubrid-manager by CUBRID.

the class ExportToXlsHandler method exportFromCache.

public void exportFromCache(String tableName) throws IOException {
    if (StringUtil.isEmpty(tableName)) {
        // FIXME move this logic to core module
        return;
    }
    WritableWorkbook workbook = null;
    int workbookNum = 0;
    int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
    // 65536: limit xls row number.
    int rowLimit = ImportFileConstants.XLS_ROW_LIMIT;
    boolean isInitedColumnTitles = false;
    List<String> columnTitles = new ArrayList<String>();
    try {
        int sheetNum = 0;
        int xlsRecordNum = 0;
        workbook = createWorkbook(exportConfig.getDataFilePath(tableName), workbookNum++);
        WritableSheet sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
        sheetNum++;
        int exportedCount = 0;
        try {
            ResultSetDataCache resultSetDataCache = exportConfig.getResultSetDataCache();
            List<ArrayList<Object>> datas = resultSetDataCache.getDatas();
            List<ColumnInfo> columnInfos = resultSetDataCache.getColumnInfos();
            int colCount = columnInfos.size();
            if (!isInitedColumnTitles) {
                isInitedColumnTitles = true;
                for (ColumnInfo column : columnInfos) {
                    columnTitles.add(column.getName());
                }
                if (isExit) {
                    return;
                }
                // first line add column name
                if (exportConfig.isFirstRowAsColumnName()) {
                    writeHeader(sheet, columnTitles);
                    xlsRecordNum++;
                }
            }
            for (ArrayList<Object> rowData : datas) {
                //Check memory
                if (!CommonUITool.isAvailableMemory(REMAINING_MEMORY_SIZE)) {
                    closeWorkbook(workbook);
                    workbook = null;
                    System.gc();
                    workbook = createWorkbook(exportConfig.getDataFilePath(tableName), workbookNum++);
                    sheetNum = 0;
                    sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
                    sheetNum++;
                    xlsRecordNum = 0;
                    // first line add column name
                    if (exportConfig.isFirstRowAsColumnName()) {
                        writeHeader(sheet, columnTitles);
                        xlsRecordNum++;
                    }
                }
                for (int j = 1; j <= colCount; j++) {
                    String colType = columnInfos.get(j - 1).getType();
                    int precision = columnInfos.get(j - 1).getPrecision();
                    setIsHasBigValue(colType, precision);
                    Object cellValue = rowData.get(j - 1);
                    // We need judge the CLOB/BLOD data by column type
                    if (DataType.DATATYPE_BLOB.equals(colType) || DataType.DATATYPE_CLOB.equals(colType)) {
                        if (DataType.DATATYPE_BLOB.equals(colType)) {
                            String fileName = exportBlobData(tableName, (Blob) cellValue);
                            String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                            if (StringUtil.isNotEmpty(fileName)) {
                                dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + BLOB_FOLDER_POSTFIX + File.separator + fileName;
                            }
                            sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                        } else {
                            String fileName = exportClobData(tableName, (Clob) cellValue);
                            String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                            if (StringUtil.isNotEmpty(fileName)) {
                                dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + CLOB_FOLDER_POSTFIX + File.separator + fileName;
                            }
                            sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                        }
                    } else if (cellValue instanceof Long) {
                        sheet.addCell(new Number(j - 1, xlsRecordNum, (Long) cellValue));
                    } else if (cellValue instanceof Double) {
                        sheet.addCell(new Number(j - 1, xlsRecordNum, (Double) cellValue));
                    } else if (cellValue instanceof Timestamp) {
                        String dataCellValue = FieldHandlerUtils.formatDateTime((Timestamp) cellValue);
                        sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                    } else if (cellValue instanceof java.sql.Time) {
                        String dataCellValue = DateUtil.getDatetimeString(((java.sql.Time) cellValue).getTime(), FieldHandlerUtils.FORMAT_TIME);
                        sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                    } else if (cellValue instanceof java.sql.Date) {
                        String dataCellValue = DateUtil.getDatetimeString(((java.sql.Date) cellValue).getTime(), FieldHandlerUtils.FORMAT_DATE);
                        sheet.addCell(new Label(j - 1, xlsRecordNum, dataCellValue));
                    } else {
                        sheet.addCell(new Label(j - 1, xlsRecordNum, cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString()));
                    }
                }
                xlsRecordNum++;
                if ((xlsRecordNum + 1) % rowLimit == 0) {
                    xlsRecordNum = 0;
                    sheet = workbook.createSheet("Sheet " + sheetNum, sheetNum);
                    sheetNum++;
                    // first line add column name
                    if (exportConfig.isFirstRowAsColumnName()) {
                        writeHeader(sheet, columnTitles);
                        xlsRecordNum++;
                    }
                }
                exportedCount++;
                if (exportedCount >= COMMIT_LINES) {
                    exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                    exportedCount = 0;
                }
                if (stop) {
                    break;
                }
            }
            exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
            exportedCount = 0;
        } catch (Exception e) {
            LOGGER.error("", e);
            exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(tableName));
        }
        System.gc();
    } catch (Exception e) {
        LOGGER.error("", e);
    } finally {
        closeWorkbook(workbook);
    }
}
Also used : ArrayList(java.util.ArrayList) Label(jxl.write.Label) ColumnInfo(com.cubrid.common.ui.query.control.ColumnInfo) Timestamp(java.sql.Timestamp) ExportDataFailedOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent) Number(jxl.write.Number) ResultSetDataCache(com.cubrid.common.ui.cubrid.table.export.ResultSetDataCache) WritableSheet(jxl.write.WritableSheet) WriteException(jxl.write.WriteException) SQLException(java.sql.SQLException) IOException(java.io.IOException) RowsExceededException(jxl.write.biff.RowsExceededException) WritableWorkbook(jxl.write.WritableWorkbook) ExportDataSuccessEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent)

Example 8 with ExportDataFailedOneTableEvent

use of com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent in project cubrid-manager by CUBRID.

the class ExportDataThread method doRun.

protected void doRun() {
    exportDataEventHandler.handleEvent(new ExportDataBeginOneTableEvent(tableName));
    try {
        AbsExportDataHandler handler = ExportHandlerFactory.getExportHandler(dbInfo, exportConfig, exportDataEventHandler);
        handler.handle(tableName);
    } catch (Exception e) {
        isSuccess = false;
        LOGGER.error("", e);
    } catch (OutOfMemoryError error) {
        isSuccess = false;
        error.printStackTrace();
    } finally {
        if (isSuccess) {
            exportDataEventHandler.handleEvent(new ExportDataFinishOneTableEvent(tableName));
        } else {
            exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(tableName));
        }
    }
}
Also used : ExportDataFailedOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent) AbsExportDataHandler(com.cubrid.common.ui.cubrid.table.export.handler.AbsExportDataHandler) ExportDataFinishOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFinishOneTableEvent) ExportDataBeginOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataBeginOneTableEvent)

Example 9 with ExportDataFailedOneTableEvent

use of com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent in project cubrid-manager by CUBRID.

the class ExportLoadDBHandler method handle.

public void handle(String nullValue) throws IOException, SQLException {
    // FIXME move this logic to core module
    Connection conn = null;
    CUBRIDPreparedStatementProxy pStmt = null;
    CUBRIDResultSetProxy rs = null;
    BufferedWriter fs = null;
    String schemaFile = exportConfig.getDataFilePath(ExportConfig.LOADDB_SCHEMAFILEKEY);
    String indexFile = exportConfig.getDataFilePath(ExportConfig.LOADDB_INDEXFILEKEY);
    String dataTablesName = exportConfig.getDataFilePath(ExportConfig.LOADDB_DATAFILEKEY);
    // Get connection
    try {
        conn = getConnection();
    } catch (SQLException e) {
        LOGGER.error(e.getMessage(), e);
        if (exportConfig.isExportSchema()) {
            exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(schemaFile));
        }
        if (exportConfig.isExportIndex()) {
            exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(indexFile));
        }
        exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(dataTablesName));
        QueryUtil.freeQuery(conn);
        throw e;
    }
    // Export schema
    boolean isExportSchemaSuccess = true;
    try {
        if (exportConfig.isExportSchema()) {
            exportDataEventHandler.handleEvent(new ExportDataBeginOneTableEvent(schemaFile));
        }
        if (exportConfig.isExportIndex()) {
            exportDataEventHandler.handleEvent(new ExportDataBeginOneTableEvent(indexFile));
        }
        Set<String> tableSet = new HashSet<String>();
        tableSet.addAll(exportConfig.getTableNameList());
        exportSchemaToOBSFile(dbInfo, exportDataEventHandler, tableSet, schemaFile, indexFile, exportConfig.getFileCharset(), exportConfig.isExportSerialStartValue());
        if (exportConfig.isExportSchema()) {
            exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(schemaFile));
            exportDataEventHandler.handleEvent(new ExportDataFinishOneTableEvent(schemaFile));
        }
        if (exportConfig.isExportIndex()) {
            exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(indexFile));
            exportDataEventHandler.handleEvent(new ExportDataFinishOneTableEvent(indexFile));
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        isExportSchemaSuccess = false;
    } catch (SQLException e) {
        LOGGER.error(e.getMessage(), e);
        isExportSchemaSuccess = false;
    } finally {
        if (!isExportSchemaSuccess) {
            if (exportConfig.isExportSchema()) {
                exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(schemaFile));
            }
            if (exportConfig.isExportIndex()) {
                exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(indexFile));
            }
        }
    }
    // Export data
    try {
        exportDataEventHandler.handleEvent(new ExportDataBeginOneTableEvent(dataTablesName));
        fs = FileUtil.getBufferedWriter(exportConfig.getDataFilePath(ExportConfig.LOADDB_DATAFILEKEY), exportConfig.getFileCharset());
        for (String tableName : exportConfig.getTableNameList()) {
            String whereCondition = exportConfig.getWhereCondition(tableName);
            long totalRecord = exportConfig.getTotalCount(tableName);
            if (totalRecord == 0) {
                continue;
            }
            boolean hasNextPage = true;
            int exportedCount = 0;
            long beginIndex = 1;
            String sql = QueryUtil.getSelectSQL(conn, tableName);
            isPaginating = isPagination(tableName, sql, whereCondition);
            boolean isExportedColumnTitles = false;
            while (hasNextPage) {
                try {
                    String executeSQL = null;
                    if (isPaginating) {
                        long endIndex = beginIndex + RSPAGESIZE;
                        executeSQL = getExecuteSQL(sql, beginIndex, endIndex, whereCondition);
                        executeSQL = dbInfo.wrapShardQuery(executeSQL);
                        beginIndex = endIndex + 1;
                    } else {
                        executeSQL = getExecuteSQL(sql, whereCondition);
                        executeSQL = dbInfo.wrapShardQuery(sql);
                        beginIndex = totalRecord + 1;
                    }
                    pStmt = getStatement(conn, executeSQL, tableName);
                    rs = (CUBRIDResultSetProxy) pStmt.executeQuery();
                    CUBRIDResultSetMetaDataProxy rsmt = (CUBRIDResultSetMetaDataProxy) rs.getMetaData();
                    if (!isExportedColumnTitles) {
                        StringBuilder header = new StringBuilder("%class \"");
                        header.append(tableName);
                        header.append("\" (");
                        for (int i = 1; i < rsmt.getColumnCount() + 1; i++) {
                            if (i > 1) {
                                header.append(" ");
                            }
                            header.append("\"");
                            header.append(rsmt.getColumnName(i));
                            header.append("\"");
                        }
                        header.append(")\n");
                        fs.write(header.toString());
                        isExportedColumnTitles = true;
                    }
                    while (rs.next()) {
                        StringBuffer values = new StringBuffer();
                        for (int j = 1; j < rsmt.getColumnCount() + 1; j++) {
                            String columnType = rsmt.getColumnTypeName(j);
                            int precision = rsmt.getPrecision(j);
                            columnType = FieldHandlerUtils.amendDataTypeByResult(rs, j, columnType);
                            setIsHasBigValue(columnType, precision);
                            values.append(FieldHandlerUtils.getRsValueForExportOBS(columnType, rs, j).toString());
                        }
                        values.append("\n");
                        fs.write(values.toString());
                        exportedCount++;
                        if (exportedCount >= COMMIT_LINES) {
                            fs.flush();
                            exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                            exportedCount = 0;
                        }
                        if (stop) {
                            break;
                        }
                    }
                    exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                    exportedCount = 0;
                } catch (SQLException e) {
                    LOGGER.error(e.getMessage(), e);
                    exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(tableName));
                } finally {
                    QueryUtil.freeQuery(rs);
                }
                if (hasNextPage(beginIndex, totalRecord)) {
                    hasNextPage = true;
                    fs.write(StringUtil.NEWLINE);
                } else {
                    hasNextPage = false;
                }
                System.gc();
            }
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw e;
    } finally {
        try {
            if (fs != null) {
                fs.flush();
                fs.close();
                fs = null;
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}
Also used : CUBRIDResultSetProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetProxy) SQLException(java.sql.SQLException) CUBRIDPreparedStatementProxy(com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy) ExportDataFinishOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFinishOneTableEvent) Connection(java.sql.Connection) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) CUBRIDResultSetMetaDataProxy(com.cubrid.jdbc.proxy.driver.CUBRIDResultSetMetaDataProxy) ExportDataFailedOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent) ExportDataSuccessEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent) ExportDataBeginOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataBeginOneTableEvent) HashSet(java.util.HashSet)

Example 10 with ExportDataFailedOneTableEvent

use of com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent in project cubrid-manager by CUBRID.

the class ExportToXlsxHandler method exportFromCache.

public void exportFromCache(String tableName) throws IOException {
    if (StringUtil.isEmpty(tableName)) {
        return;
    }
    // 1048576: limit xlsx row number.
    int rowLimit = ImportFileConstants.XLSX_ROW_LIMIT;
    // 16384: limit xlsx column number.
    int columnLimit = ImportFileConstants.XLSX_COLUMN_LIMIT;
    int cellCharacterLimit = ImportFileConstants.XLSX_CELL_CHAR_LIMIT;
    XlsxWriterHelper xlsxWriterhelper = new XlsxWriterHelper();
    //create memory workbook
    XSSFWorkbook workbook = new XSSFWorkbook();
    Calendar cal = Calendar.getInstance();
    int datetimeStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("datetime")).getIndex();
    int timestampStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("timestamp")).getIndex();
    int dateStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("date")).getIndex();
    int timeStyleIndex = ((XSSFCellStyle) xlsxWriterhelper.getStyles(workbook).get("time")).getIndex();
    int sheetNum = 0;
    int xssfRowNum = 0;
    File file = new File(exportConfig.getDataFilePath(tableName));
    Map<String, File> fileMap = new HashMap<String, File>();
    XlsxWriterHelper.SpreadsheetWriter sheetWriter = null;
    boolean isInitedColumnTitle = false;
    List<String> columnTitles = new ArrayList<String>();
    try {
        int exportedCount = 0;
        ResultSetDataCache resultSetDataCache = exportConfig.getResultSetDataCache();
        List<ColumnInfo> columnInfos = resultSetDataCache.getColumnInfos();
        List<ArrayList<Object>> datas = resultSetDataCache.getDatas();
        int colCount = columnInfos.size();
        if (colCount >= columnLimit && !isConfirmColumnLimit) {
            isConfirmColumnLimit = true;
            Display.getDefault().syncExec(new Runnable() {

                public void run() {
                    if (!CommonUITool.openConfirmBox(Messages.exportColumnCountOverWarnInfo)) {
                        isExit = true;
                    }
                }
            });
            if (isExit) {
                return;
            }
            colCount = columnLimit;
        }
        if (!isInitedColumnTitle) {
            for (ColumnInfo column : columnInfos) {
                columnTitles.add(column.getName());
            }
            isInitedColumnTitle = true;
            if (isExit) {
                return;
            }
            sheetWriter = createSheetWriter(workbook, xlsxWriterhelper, sheetNum++, fileMap, columnTitles, xssfRowNum);
            if (exportConfig.isFirstRowAsColumnName()) {
                xssfRowNum++;
            }
        }
        try {
            for (ArrayList<Object> rowData : datas) {
                sheetWriter.insertRow(xssfRowNum);
                for (int k = 1; k <= colCount; k++) {
                    String colType = columnInfos.get(k - 1).getType();
                    int precision = columnInfos.get(k - 1).getPrecision();
                    setIsHasBigValue(colType, precision);
                    Object cellValue = rowData.get(k - 1);
                    // We need judge the CLOB/BLOD data by column type
                    if (DataType.DATATYPE_BLOB.equals(colType) || DataType.DATATYPE_CLOB.equals(colType)) {
                        if (DataType.DATATYPE_BLOB.equals(colType)) {
                            String fileName = exportBlobData(tableName, (Blob) cellValue);
                            String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                            if (StringUtil.isNotEmpty(fileName)) {
                                dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + BLOB_FOLDER_POSTFIX + File.separator + fileName;
                            }
                            sheetWriter.createCell(k - 1, dataCellValue);
                        } else {
                            String fileName = exportClobData(tableName, (Clob) cellValue);
                            String dataCellValue = DataType.NULL_EXPORT_FORMAT;
                            if (StringUtil.isNotEmpty(fileName)) {
                                dataCellValue = DBAttrTypeFormatter.FILE_URL_PREFIX + tableName + CLOB_FOLDER_POSTFIX + File.separator + fileName;
                            }
                            sheetWriter.createCell(k - 1, dataCellValue);
                        }
                    } else if (cellValue instanceof Long) {
                        sheetWriter.createCell(k - 1, ((Long) cellValue).longValue());
                    } else if (cellValue instanceof Double) {
                        sheetWriter.createCell(k - 1, ((Double) cellValue).doubleValue());
                    } else if (cellValue instanceof Date) {
                        cal.setTime((Date) cellValue);
                        if (DataType.DATATYPE_DATETIME.equals(colType)) {
                            sheetWriter.createCell(k - 1, cal, datetimeStyleIndex);
                        } else if (DataType.DATATYPE_DATE.equals(colType)) {
                            sheetWriter.createCell(k - 1, cal, dateStyleIndex);
                        } else if (DataType.DATATYPE_TIME.equals(colType)) {
                            sheetWriter.createCell(k - 1, cal, timeStyleIndex);
                        } else {
                            sheetWriter.createCell(k - 1, cal, timestampStyleIndex);
                        }
                    } else {
                        String cellStr = cellValue.toString().length() > cellCharacterLimit ? cellValue.toString().substring(0, cellCharacterLimit) : cellValue.toString();
                        sheetWriter.createCell(k - 1, Export.covertXMLString(cellStr));
                    }
                }
                sheetWriter.endRow();
                xssfRowNum++;
                exportedCount++;
                if ((xssfRowNum + 1) % rowLimit == 0) {
                    xssfRowNum = 0;
                    if (sheetWriter != null) {
                        try {
                            XlsxWriterHelper.writeSheetWriter(sheetWriter);
                        } catch (IOException e) {
                            sheetWriter = null;
                            throw e;
                        }
                    }
                    sheetWriter = createSheetWriter(workbook, xlsxWriterhelper, sheetNum, fileMap, columnTitles, xssfRowNum);
                    sheetNum++;
                    if (exportConfig.isFirstRowAsColumnName()) {
                        xssfRowNum++;
                    }
                }
                if (exportedCount >= COMMIT_LINES) {
                    exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
                    exportedCount = 0;
                }
                if (stop) {
                    break;
                }
            }
            exportDataEventHandler.handleEvent(new ExportDataSuccessEvent(tableName, exportedCount));
            exportedCount = 0;
        } catch (Exception e) {
            LOGGER.error("", e);
            exportDataEventHandler.handleEvent(new ExportDataFailedOneTableEvent(tableName));
        }
        System.gc();
    } finally {
        try {
            if (sheetWriter != null) {
                XlsxWriterHelper.writeSheetWriter(sheetWriter);
            }
        } catch (IOException e) {
            sheetWriter = null;
            throw e;
        } finally {
            XlsxWriterHelper.writeWorkbook(workbook, xlsxWriterhelper, fileMap, file);
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ColumnInfo(com.cubrid.common.ui.query.control.ColumnInfo) XlsxWriterHelper(com.cubrid.common.ui.cubrid.table.control.XlsxWriterHelper) XSSFCellStyle(org.apache.poi.xssf.usermodel.XSSFCellStyle) ExportDataFailedOneTableEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) ResultSetDataCache(com.cubrid.common.ui.cubrid.table.export.ResultSetDataCache) Calendar(java.util.Calendar) IOException(java.io.IOException) Date(java.util.Date) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExportDataSuccessEvent(com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent) File(java.io.File)

Aggregations

ExportDataFailedOneTableEvent (com.cubrid.common.ui.cubrid.table.event.ExportDataFailedOneTableEvent)13 ExportDataSuccessEvent (com.cubrid.common.ui.cubrid.table.event.ExportDataSuccessEvent)11 IOException (java.io.IOException)11 SQLException (java.sql.SQLException)10 ArrayList (java.util.ArrayList)7 BufferedWriter (java.io.BufferedWriter)6 Connection (java.sql.Connection)6 ExportDataBeginOneTableEvent (com.cubrid.common.ui.cubrid.table.event.ExportDataBeginOneTableEvent)5 ExportDataFinishOneTableEvent (com.cubrid.common.ui.cubrid.table.event.ExportDataFinishOneTableEvent)5 CUBRIDPreparedStatementProxy (com.cubrid.jdbc.proxy.driver.CUBRIDPreparedStatementProxy)5 CUBRIDResultSetMetaDataProxy (com.cubrid.jdbc.proxy.driver.CUBRIDResultSetMetaDataProxy)5 CUBRIDResultSetProxy (com.cubrid.jdbc.proxy.driver.CUBRIDResultSetProxy)5 ResultSetDataCache (com.cubrid.common.ui.cubrid.table.export.ResultSetDataCache)4 ColumnInfo (com.cubrid.common.ui.query.control.ColumnInfo)4 File (java.io.File)3 HashSet (java.util.HashSet)3 XlsxWriterHelper (com.cubrid.common.ui.cubrid.table.control.XlsxWriterHelper)2 AbsExportDataHandler (com.cubrid.common.ui.cubrid.table.export.handler.AbsExportDataHandler)2 Timestamp (java.sql.Timestamp)2 Calendar (java.util.Calendar)2