Search in sources :

Example 6 with FileInfoEntity

use of com.varsql.web.model.entity.app.FileInfoEntity in project varsql by varsqlinfo.

the class FileDownloadController method fileDownload.

// 첨부파일 다운로드
@RequestMapping(value = "/download")
public void fileDownload(@RequestParam(value = "contId") String contId, @RequestParam(value = "fileId") String fileId, HttpServletRequest req, HttpServletResponse res) throws Exception {
    logger.debug("fileDownload");
    List<FileInfoEntity> fileList = new ArrayList<>();
    if (!StringUtils.isBlank(fileId)) {
        FileInfoEntity fie = fileInfoEntityRepository.findByFileId(fileId);
        if (fie != null) {
            fileList.add(fie);
        }
    } else if (!StringUtils.isBlank(contId)) {
        fileList = fileInfoEntityRepository.findByFileContId(fileId);
    }
    if (fileList.size() < 1) {
        res.setContentType("text/html");
        res.setStatus(HttpStatus.OK.value());
        try (PrintWriter out = res.getWriter()) {
            out.write("<script>alert('file not found')</script>");
        }
        return;
    }
    ParamMap param = HttpUtils.getServletRequestParam(req);
    String downFileName = "";
    int fileSize = fileList.size();
    if (fileSize == 1) {
        downFileName = fileList.get(0).getFileName();
    } else {
        downFileName = param.getString("downFileName", "downloadFile");
        downFileName = java.net.URLDecoder.decode(downFileName, "UTF-8");
        downFileName = downFileName + ".zip";
    }
    FileServiceUtils.fileDownload(req, res, downFileName, fileList.toArray(new FileInfoEntity[0]));
}
Also used : ParamMap(com.vartech.common.app.beans.ParamMap) ArrayList(java.util.ArrayList) FileInfoEntity(com.varsql.web.model.entity.app.FileInfoEntity) PrintWriter(java.io.PrintWriter) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with FileInfoEntity

use of com.varsql.web.model.entity.app.FileInfoEntity in project varsql by varsqlinfo.

the class FileUploadController method fileUpload.

/**
 * @Method Name  : fileUpload
 * @Method 설명 : unit file upload
 * @작성자   : ytkim
 * @작성일   : 2019. 11. 29.
 * @변경이력  :
 * @param uploadfile
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public ResponseResult fileUpload(@RequestParam(name = "div", required = true) String div, @RequestParam(name = "fileContId", defaultValue = "") String paramFileContId, MultipartHttpServletRequest mtfRequest) throws IOException {
    logger.debug("file upload!");
    ResponseResult result = new ResponseResult();
    List<FileInfoEntity> uploadFiles = fileUploadService.uploadFiles(mtfRequest, UploadFileType.getDivType(div), paramFileContId);
    if (uploadFiles.size() > 0) {
        result.setItemList(uploadFiles);
    } else {
        result.setResultCode(VarsqlAppCode.COMM_FILE_EMPTY);
        result.setMessage("select file");
    }
    return result;
}
Also used : ResponseResult(com.vartech.common.app.beans.ResponseResult) FileInfoEntity(com.varsql.web.model.entity.app.FileInfoEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 8 with FileInfoEntity

use of com.varsql.web.model.entity.app.FileInfoEntity in project varsql by varsqlinfo.

the class FileUploadService method uploadFiles.

public List<FileInfoEntity> uploadFiles(UploadFileType fileType, List<MultipartFile> files, String fileContId, String contGroupId, String fieldName, boolean addExtensionSuffix, boolean fileInfoSaveFlag) {
    List<FileInfoEntity> fileInfos = new ArrayList<FileInfoEntity>();
    files.forEach(file -> {
        if (!(file.getSize() <= 0 && "blob".equals(file.getOriginalFilename()))) {
            try {
                FileInfoEntity fileInfo = saveFile(fileType, file, fileContId, addExtensionSuffix);
                fileInfo.setFileContId(fileContId);
                fileInfo.setFileFieldName(fieldName);
                fileInfo.setContGroupId(contGroupId);
                fileInfos.add(fileInfo);
            } catch (IllegalStateException | IOException e) {
                logger.error("file upload exception : {}", e.getMessage(), e);
                throw new VarsqlRuntimeException(VarsqlAppCode.COMM_FILE_UPLOAD_ERROR, "file upload error", e);
            }
        }
    });
    if (fileInfoSaveFlag) {
        fileInfoEntityRepository.saveAll(fileInfos);
    }
    return fileInfos;
}
Also used : ArrayList(java.util.ArrayList) FileInfoEntity(com.varsql.web.model.entity.app.FileInfoEntity) IOException(java.io.IOException) VarsqlRuntimeException(com.varsql.core.exception.VarsqlRuntimeException)

Example 9 with FileInfoEntity

use of com.varsql.web.model.entity.app.FileInfoEntity in project varsql by varsqlinfo.

the class FileImportExportController method upload.

/**
 * @Method Name  : fileImport
 * @Method 설명 : file import
 * @작성자   : ytkim
 * @작성일   : 2019. 11. 29.
 * @변경이력  :
 * @param uploadfile
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public ResponseResult upload(@RequestParam(name = "div", required = true) String div, @RequestParam(name = "fileExtensions", required = true) String fileExtensions, @RequestParam(name = "fileContId", defaultValue = "") String paramFileContId, @RequestParam(name = "conuid", defaultValue = "") String conuid, MultipartHttpServletRequest mtfRequest) throws IOException {
    logger.debug("file upload!");
    ResponseResult result = new ResponseResult();
    String vconnid = SecurityUtil.getVconnid(conuid);
    List<FileInfoEntity> uploadFiles = fileUploadService.uploadFiles(mtfRequest, UploadFileType.getDivType(div), paramFileContId, vconnid);
    if (uploadFiles.size() > 0) {
        result.setItemList(uploadFiles);
    } else {
        result.setResultCode(VarsqlAppCode.COMM_FILE_EMPTY);
        result.setMessage("select file");
    }
    return result;
}
Also used : ResponseResult(com.vartech.common.app.beans.ResponseResult) FileInfoEntity(com.varsql.web.model.entity.app.FileInfoEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 10 with FileInfoEntity

use of com.varsql.web.model.entity.app.FileInfoEntity in project varsql by varsqlinfo.

the class ExportServiceImpl method downloadTableData2.

public ResponseResult downloadTableData2(PreferencesRequestDTO preferencesInfo, HttpServletRequest req, HttpServletResponse res) throws Exception {
    DataDownloadInfo ddi = VartechUtils.jsonStringToObject(preferencesInfo.getPrefVal(), DataDownloadInfo.class, true);
    DatabaseInfo databaseInfo = SecurityUtil.loginInfo().getDatabaseInfo().get(ddi.getConuid());
    logger.debug("downloadTableData : {}", preferencesInfo.getPrefVal());
    String prefixSchema = StringUtils.isBlank(ddi.getSchema()) ? "" : ddi.getSchema() + ".";
    String charset = StringUtils.isBlank(ddi.getCharset()) ? VarsqlConstants.CHAR_SET : ddi.getCharset();
    String exportFileName = ValidateUtils.getValidFileName(ddi.getFileName());
    String fileId = VartechUtils.generateUUID();
    Path fileExportPath = FileServiceUtils.getSavePath(UploadFileType.EXPORT);
    File zipFile = new File(FileUtils.pathConcat(fileExportPath.toAbsolutePath().toString(), VarsqlFileType.ZIP.concatExtension(fileId)));
    int bufferSize = 2048;
    final VarsqlFileType exportType = ddi.getExportType();
    DBType dbType = DBType.getDBType(databaseInfo.getType());
    String requid = ddi.getRequid();
    ProgressInfo progressInfo = new ProgressInfo();
    progressInfo.setTotalItemSize(ddi.getItems().size());
    String sessAttrKey = HttpSessionConstants.progressKey(requid);
    System.out.println("downloadTableData2 sessAttrKey : " + sessAttrKey);
    HttpSession session = req.getSession();
    session.setAttribute(sessAttrKey, progressInfo);
    try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile), Charset.forName(charset))) {
        int idx = 0;
        for (DownloadItemInfo item : ddi.getItems()) {
            ++idx;
            SqlExecuteDTO seDto = new SqlExecuteDTO();
            seDto.setLimit(ddi.getLimit());
            seDto.setConuid(ddi.getConuid(), exportFileName, databaseInfo);
            String objectName = prefixSchema + item.getName();
            seDto.setSqlParam("{}");
            seDto.setSql(SQLUtils.generateSelectQuery(objectName, item.getCondition(), dbType));
            String downloadFilePath = FileUtils.pathConcat(fileExportPath.toAbsolutePath().toString(), exportType.concatExtension(VartechUtils.generateUUID()));
            progressInfo.setName(item.getName());
            progressInfo.setItemIdx(idx);
            AbstractWriter writer = null;
            try (OutputStream outstream = new FileOutputStream(downloadFilePath)) {
                if (VarsqlFileType.CSV.equals(exportType)) {
                    writer = new CSVWriter(outstream, ',', charset);
                } else if (VarsqlFileType.JSON.equals(exportType)) {
                    writer = new JSONWriter(outstream, "row", charset);
                } else if (VarsqlFileType.XML.equals(exportType)) {
                    writer = new XMLWriter(outstream, "row", charset);
                } else if (VarsqlFileType.EXCEL.equals(exportType)) {
                    writer = new ExcelWriter(outstream);
                } else {
                    writer = new SQLWriter(outstream, dbType, objectName, charset);
                }
                logger.debug("data export downloadFilePath :{} , query : {}", downloadFilePath, seDto.getSql());
                final String tableName = item.getName();
                SQLExecuteResult ser = (new SelectExecutor()).execute(seDto, new AbstractSQLExecutorHandler(writer) {

                    private boolean firstFlag = true;

                    private int rowIdx = 0;

                    public boolean handle(SQLHandlerParameter handleParam) {
                        if (this.firstFlag) {
                            WriteMetadataInfo whi = new WriteMetadataInfo("exportInfo");
                            List<ExportColumnInfo> columns = new LinkedList<>();
                            handleParam.getColumnInfoList().forEach(item -> {
                                ExportColumnInfo gci = new ExportColumnInfo();
                                gci.setName(item.getLabel());
                                // 추가 할것.
                                gci.setAlias(item.getKey());
                                gci.setType(item.getDbType());
                                gci.setNumber(item.isNumber());
                                gci.setLob(item.isLob());
                                columns.add(gci);
                            });
                            whi.addMetedata("tableName", tableName);
                            whi.addMetedata("columns", columns);
                            getWriter().setMetadata(new WriteMetadataInfo[] { whi });
                            if (VarsqlFileType.SQL.equals(exportType)) {
                                ((SQLWriter) getWriter()).setColumnInfos(handleParam.getColumnInfoList());
                            }
                            this.firstFlag = false;
                        }
                        progressInfo.setProgressContentLength(++rowIdx);
                        try {
                            getWriter().addRow(handleParam.getRowObject());
                        } catch (IOException e) {
                            logger.error(e.getMessage(), e);
                            return false;
                        }
                        return true;
                    }
                });
                writer.writeAndClose();
                String zipFileName = exportType.concatExtension(item.getName());
                if (ser.getResultCode() != null) {
                    VarsqlUtils.textDownload(new FileOutputStream(downloadFilePath), ser.getMessage());
                    zipFileName = item.getName() + "-export-error.txt";
                }
                try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downloadFilePath))) {
                    ZipEntry zentry = new ZipEntry(zipFileName);
                    zentry.setSize(new File(downloadFilePath).length());
                    zos.putNextEntry(zentry);
                    byte[] buffer = new byte[bufferSize];
                    int cnt = 0;
                    while ((cnt = bis.read(buffer, 0, bufferSize)) != -1) {
                        zos.write(buffer, 0, cnt);
                    }
                    zos.closeEntry();
                }
                new File(downloadFilePath).delete();
            } catch (Exception e) {
                throw e;
            } finally {
                IOUtils.close(writer);
            }
        }
        IOUtils.close(zos);
    }
    FileInfoEntity fie = FileInfoEntity.builder().fileId(fileId).fileContId(fileId).contGroupId(databaseInfo.getVconnid()).fileDiv(UploadFileType.EXPORT.getDiv()).fileFieldName("downloadZipFile").fileName(VarsqlFileType.ZIP.concatExtension(exportFileName)).fileSize(zipFile.length()).fileExt(VarsqlFileType.ZIP.getExtension()).filePath(FileUtils.pathConcat(FileServiceUtils.getSaveRelativePath(UploadFileType.EXPORT), zipFile.getName())).build();
    fileInfoEntityRepository.save(fie);
    session.setAttribute(sessAttrKey, "complete");
    return VarsqlUtils.getResponseResultItemOne(fie);
}
Also used : JSONWriter(com.vartech.common.io.writer.JSONWriter) SelectExecutor(com.varsql.core.sql.executor.SelectExecutor) ExportColumnInfo(com.varsql.core.sql.beans.ExportColumnInfo) Arrays(java.util.Arrays) MetaControlBean(com.varsql.core.db.MetaControlBean) DatabaseParamInfo(com.varsql.core.db.valueobject.DatabaseParamInfo) BufferedInputStream(java.io.BufferedInputStream) WriteMetadataInfo(com.vartech.common.io.writer.WriteMetadataInfo) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) VarsqlUtils(com.varsql.web.util.VarsqlUtils) ModelMap(org.springframework.ui.ModelMap) DatabaseInfo(com.varsql.core.db.valueobject.DatabaseInfo) ObjectType(com.varsql.core.db.servicemenu.ObjectType) DataCommonVO(com.varsql.web.common.beans.DataCommonVO) DownloadItemInfo(com.varsql.web.dto.DownloadItemInfo) Map(java.util.Map) SQLUtils(com.varsql.core.sql.util.SQLUtils) VarsqlReportConfig(com.varsql.core.db.report.VarsqlReportConfig) JSONWriter(com.vartech.common.io.writer.JSONWriter) XMLWriter(com.vartech.common.io.writer.XMLWriter) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) HttpSession(javax.servlet.http.HttpSession) DataDownloadInfo(com.varsql.web.dto.DataDownloadInfo) PreferencesConstants(com.varsql.web.constants.PreferencesConstants) ProgressInfo(com.varsql.core.common.beans.ProgressInfo) VarsqlFileType(com.varsql.core.common.code.VarsqlFileType) Collectors(java.util.stream.Collectors) CSVWriter(com.vartech.common.io.writer.CSVWriter) DDLCreateOption(com.varsql.core.db.valueobject.ddl.DDLCreateOption) List(java.util.List) ZipOutputStream(java.util.zip.ZipOutputStream) DDLInfo(com.varsql.core.db.valueobject.ddl.DDLInfo) FileInfoEntity(com.varsql.web.model.entity.app.FileInfoEntity) ExcelWriter(com.vartech.common.io.writer.ExcelWriter) IOUtils(com.vartech.common.utils.IOUtils) SQLWriter(com.varsql.core.data.writer.SQLWriter) ValidateUtils(com.varsql.web.util.ValidateUtils) HashMap(java.util.HashMap) ResponseResult(com.vartech.common.app.beans.ResponseResult) SQLExecuteResult(com.varsql.core.sql.executor.SQLExecuteResult) FileUtils(com.vartech.common.utils.FileUtils) BufferedOutputStream(java.io.BufferedOutputStream) SecurityUtil(com.varsql.core.common.util.SecurityUtil) VartechUtils(com.vartech.common.utils.VartechUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) UploadFileType(com.varsql.web.constants.UploadFileType) Charset(java.nio.charset.Charset) BlankConstants(com.varsql.core.common.constants.BlankConstants) AbstractWriter(com.vartech.common.io.writer.AbstractWriter) Service(org.springframework.stereotype.Service) LinkedList(java.util.LinkedList) HttpSessionConstants(com.varsql.web.constants.HttpSessionConstants) EnumMapperValue(com.vartech.common.app.beans.EnumMapperValue) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) FileServiceUtils(com.varsql.web.util.FileServiceUtils) StringUtils(com.vartech.common.utils.StringUtils) HttpServletResponse(javax.servlet.http.HttpServletResponse) VarsqlConstants(com.varsql.core.common.constants.VarsqlConstants) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) File(java.io.File) PreferencesRequestDTO(com.varsql.web.dto.user.PreferencesRequestDTO) SQLHandlerParameter(com.varsql.core.sql.executor.handler.SQLHandlerParameter) DBType(com.varsql.core.db.DBType) MetaControlFactory(com.varsql.core.db.MetaControlFactory) FileInfoEntityRepository(com.varsql.web.repository.user.FileInfoEntityRepository) SqlExecuteDTO(com.varsql.web.dto.sql.SqlExecuteDTO) SelectExecutor(com.varsql.core.sql.executor.SelectExecutor) AbstractSQLExecutorHandler(com.varsql.core.sql.executor.handler.AbstractSQLExecutorHandler) ExcelReport(com.vartech.common.excel.ExcelReport) DatabaseInfo(com.varsql.core.db.valueobject.DatabaseInfo) ZipOutputStream(java.util.zip.ZipOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ExcelWriter(com.vartech.common.io.writer.ExcelWriter) SQLHandlerParameter(com.varsql.core.sql.executor.handler.SQLHandlerParameter) WriteMetadataInfo(com.vartech.common.io.writer.WriteMetadataInfo) ZipEntry(java.util.zip.ZipEntry) CSVWriter(com.vartech.common.io.writer.CSVWriter) DBType(com.varsql.core.db.DBType) AbstractWriter(com.vartech.common.io.writer.AbstractWriter) XMLWriter(com.vartech.common.io.writer.XMLWriter) VarsqlFileType(com.varsql.core.common.code.VarsqlFileType) AbstractSQLExecutorHandler(com.varsql.core.sql.executor.handler.AbstractSQLExecutorHandler) ExportColumnInfo(com.varsql.core.sql.beans.ExportColumnInfo) BufferedInputStream(java.io.BufferedInputStream) ProgressInfo(com.varsql.core.common.beans.ProgressInfo) List(java.util.List) LinkedList(java.util.LinkedList) FileInfoEntity(com.varsql.web.model.entity.app.FileInfoEntity) DownloadItemInfo(com.varsql.web.dto.DownloadItemInfo) Path(java.nio.file.Path) SqlExecuteDTO(com.varsql.web.dto.sql.SqlExecuteDTO) HttpSession(javax.servlet.http.HttpSession) DataDownloadInfo(com.varsql.web.dto.DataDownloadInfo) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) SQLWriter(com.varsql.core.data.writer.SQLWriter) SQLExecuteResult(com.varsql.core.sql.executor.SQLExecuteResult) File(java.io.File)

Aggregations

FileInfoEntity (com.varsql.web.model.entity.app.FileInfoEntity)10 ResponseResult (com.vartech.common.app.beans.ResponseResult)5 ArrayList (java.util.ArrayList)5 FileInputStream (java.io.FileInputStream)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ZipEntry (java.util.zip.ZipEntry)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 FileNotFoundException (com.varsql.core.exception.FileNotFoundException)2 SQLExecuteResult (com.varsql.core.sql.executor.SQLExecuteResult)2 BufferedReader (java.io.BufferedReader)2 InputStreamReader (java.io.InputStreamReader)2 ZipFile (java.util.zip.ZipFile)2 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)2 ProgressInfo (com.varsql.core.common.beans.ProgressInfo)1 VarsqlFileType (com.varsql.core.common.code.VarsqlFileType)1 BlankConstants (com.varsql.core.common.constants.BlankConstants)1 VarsqlConstants (com.varsql.core.common.constants.VarsqlConstants)1 SecurityUtil (com.varsql.core.common.util.SecurityUtil)1